001/**
002 *
003 * Copyright 2003-2007 Jive Software, 2017-2024 Florian Schmaus.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.jivesoftware.smack;
019
020import java.io.ByteArrayInputStream;
021import java.io.FileInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.lang.reflect.Constructor;
025import java.lang.reflect.InvocationTargetException;
026import java.net.InetAddress;
027import java.net.UnknownHostException;
028import java.nio.charset.StandardCharsets;
029import java.security.KeyManagementException;
030import java.security.KeyStore;
031import java.security.KeyStoreException;
032import java.security.NoSuchAlgorithmException;
033import java.security.NoSuchProviderException;
034import java.security.Provider;
035import java.security.SecureRandom;
036import java.security.Security;
037import java.security.UnrecoverableKeyException;
038import java.security.cert.CertificateException;
039import java.util.Arrays;
040import java.util.Collection;
041import java.util.Collections;
042import java.util.HashSet;
043import java.util.Locale;
044import java.util.Set;
045import java.util.logging.Level;
046import java.util.logging.Logger;
047
048import javax.net.SocketFactory;
049import javax.net.ssl.HostnameVerifier;
050import javax.net.ssl.KeyManager;
051import javax.net.ssl.KeyManagerFactory;
052import javax.net.ssl.SSLContext;
053import javax.net.ssl.TrustManager;
054import javax.net.ssl.X509TrustManager;
055import javax.security.auth.callback.Callback;
056import javax.security.auth.callback.CallbackHandler;
057import javax.security.auth.callback.PasswordCallback;
058import javax.security.auth.callback.UnsupportedCallbackException;
059
060import org.jivesoftware.smack.datatypes.UInt16;
061import org.jivesoftware.smack.debugger.SmackDebuggerFactory;
062import org.jivesoftware.smack.internal.SmackTlsContext;
063import org.jivesoftware.smack.packet.id.StandardStanzaIdSource;
064import org.jivesoftware.smack.packet.id.StanzaIdSource;
065import org.jivesoftware.smack.packet.id.StanzaIdSourceFactory;
066import org.jivesoftware.smack.proxy.ProxyInfo;
067import org.jivesoftware.smack.sasl.SASLMechanism;
068import org.jivesoftware.smack.sasl.core.SASLAnonymous;
069import org.jivesoftware.smack.util.CloseableUtil;
070import org.jivesoftware.smack.util.CollectionUtil;
071import org.jivesoftware.smack.util.DNSUtil;
072import org.jivesoftware.smack.util.Objects;
073import org.jivesoftware.smack.util.SslContextFactory;
074import org.jivesoftware.smack.util.StringUtils;
075import org.jivesoftware.smack.util.TLSUtils;
076import org.jivesoftware.smack.util.dns.SmackDaneProvider;
077import org.jivesoftware.smack.util.dns.SmackDaneVerifier;
078
079import org.jxmpp.jid.DomainBareJid;
080import org.jxmpp.jid.EntityBareJid;
081import org.jxmpp.jid.impl.JidCreate;
082import org.jxmpp.jid.parts.Resourcepart;
083import org.jxmpp.stringprep.XmppStringprepException;
084import org.minidns.dnsname.DnsName;
085import org.minidns.dnsname.InvalidDnsNameException;
086import org.minidns.util.InetAddressUtil;
087
088/**
089 * The connection configuration used for XMPP client-to-server connections. A well configured XMPP service will
090 * typically only require you to provide two parameters: The XMPP address, also known as the JID, of the user and the
091 * password. All other configuration parameters could ideally be determined automatically by Smack. Hence, it is often
092 * enough to call {@link Builder#setXmppAddressAndPassword(CharSequence, String)}.
093 * <p>
094 * Technically there are typically at least two parameters required: Some kind of credentials for authentication. And
095 * the XMPP service domain. The credentials often consists of a username and password use for the SASL authentication.
096 * But there are also other authentication mechanisms, like client side certificates, which do not require a particular
097 * username and password.
098 * </p>
099 * <p>
100 * There are some misconceptions about XMPP client-to-server parameters: The first is that the username used for
101 * authentication will be equal to the localpart of the bound XMPP address after authentication. While this is usually
102 * true, it is not required. Technically the username used for authentication and the resulting XMPP address are
103 * completely independent from each other. The second common misconception steers from the terms "XMPP host" and "XMPP
104 * service domain": An XMPP service host is a system which hosts one or multiple XMPP domains. The "XMPP service domain"
105 * will be usually the domainpart of the bound JID. This domain is used to verify the remote endpoint, typically using
106 * TLS. This third misconception is that the XMPP service domain is required to become the domainpart of the bound JID.
107 * Again, while this is very common to be true, it is not strictly required.
108 * </p>
109 *
110 * @author Gaston Dombiak
111 * @author Florian Schmaus
112 */
113public abstract class ConnectionConfiguration {
114
115    static {
116        Smack.ensureInitialized();
117    }
118
119    private static final Logger LOGGER = Logger.getLogger(ConnectionConfiguration.class.getName());
120
121    /**
122     * The XMPP domain of the XMPP Service. Usually servers use the same service name as the name
123     * of the server. However, there are some servers like google where host would be
124     * talk.google.com and the serviceName would be gmail.com.
125     */
126    protected final DomainBareJid xmppServiceDomain;
127
128    protected final DnsName xmppServiceDomainDnsName;
129
130    protected final InetAddress hostAddress;
131    protected final DnsName host;
132    protected final UInt16 port;
133
134    /**
135     * Used to get information from the user
136     */
137    private final CallbackHandler callbackHandler;
138
139    private final SmackDebuggerFactory debuggerFactory;
140
141    // Holds the socket factory that is used to generate the socket in the connection
142    private final SocketFactory socketFactory;
143
144    private final CharSequence username;
145    private final String password;
146    private final Resourcepart resource;
147
148    private final Locale language;
149
150    /**
151     * The optional SASL authorization identity (see RFC 6120 § 6.3.8).
152     */
153    private final EntityBareJid authzid;
154
155    /**
156     * Initial presence as of RFC 6121 § 4.2
157     * @see <a href="http://xmpp.org/rfcs/rfc6121.html#presence-initial">RFC 6121 § 4.2 Initial Presence</a>
158     */
159    private final boolean sendPresence;
160
161    private final SecurityMode securityMode;
162
163    final SmackTlsContext smackTlsContext;
164
165    private final DnssecMode dnssecMode;
166
167    /**
168     *
169     */
170    private final String[] enabledSSLProtocols;
171
172    /**
173     *
174     */
175    private final String[] enabledSSLCiphers;
176
177    private final HostnameVerifier hostnameVerifier;
178
179    // Holds the proxy information (such as proxyhost, proxyport, username, password etc)
180    protected final ProxyInfo proxy;
181
182    protected final boolean allowNullOrEmptyUsername;
183
184    private final Set<String> enabledSaslMechanisms;
185
186    private final boolean compressionEnabled;
187
188    private final StanzaIdSourceFactory stanzaIdSourceFactory;
189
190    protected ConnectionConfiguration(Builder<?, ?> builder) {
191        try {
192            smackTlsContext = getSmackTlsContext(builder.dnssecMode, builder.sslContextFactory,
193                            builder.customX509TrustManager, builder.keyManagers, builder.sslContextSecureRandom, builder.keystoreType, builder.keystorePath,
194                            builder.callbackHandler, builder.pkcs11Library);
195        } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | CertificateException
196                        | KeyStoreException | NoSuchProviderException | IOException | NoSuchMethodException
197                        | SecurityException | ClassNotFoundException | InstantiationException | IllegalAccessException
198                        | IllegalArgumentException | InvocationTargetException | UnsupportedCallbackException e) {
199            throw new IllegalArgumentException(e);
200        }
201
202        authzid = builder.authzid;
203        username = builder.username;
204        password = builder.password;
205        callbackHandler = builder.callbackHandler;
206
207        // Resource can be null, this means that the server must provide one
208        resource = builder.resource;
209
210        language = builder.language;
211
212        xmppServiceDomain = builder.xmppServiceDomain;
213        if (xmppServiceDomain == null) {
214            throw new IllegalArgumentException("Must define the XMPP domain");
215        }
216
217        DnsName xmppServiceDomainDnsName;
218        try {
219            xmppServiceDomainDnsName = DnsName.from(xmppServiceDomain);
220        } catch (InvalidDnsNameException e) {
221            LOGGER.log(Level.INFO,
222                            "Could not transform XMPP service domain '" + xmppServiceDomain
223                          + "' to a DNS name. TLS X.509 certificate validiation may not be possible.",
224                            e);
225            xmppServiceDomainDnsName = null;
226        }
227        this.xmppServiceDomainDnsName = xmppServiceDomainDnsName;
228
229        hostAddress = builder.hostAddress;
230        host = builder.host;
231        port = builder.port;
232
233        proxy = builder.proxy;
234        socketFactory = builder.socketFactory;
235
236        dnssecMode = builder.dnssecMode;
237
238        securityMode = builder.securityMode;
239        enabledSSLProtocols = builder.enabledSSLProtocols;
240        enabledSSLCiphers = builder.enabledSSLCiphers;
241        hostnameVerifier = builder.hostnameVerifier;
242        sendPresence = builder.sendPresence;
243        debuggerFactory = builder.debuggerFactory;
244        allowNullOrEmptyUsername = builder.allowEmptyOrNullUsername;
245        enabledSaslMechanisms = builder.enabledSaslMechanisms;
246
247        compressionEnabled = builder.compressionEnabled;
248
249        stanzaIdSourceFactory = builder.stanzaIdSourceFactory;
250
251        // If the enabledSaslMechanisms are set, then they must not be empty
252        assert enabledSaslMechanisms == null || !enabledSaslMechanisms.isEmpty();
253    }
254
255    private static SmackTlsContext getSmackTlsContext(DnssecMode dnssecMode, SslContextFactory sslContextFactory,
256                    X509TrustManager trustManager, KeyManager[] keyManagers, SecureRandom secureRandom, String keystoreType, String keystorePath,
257                    CallbackHandler callbackHandler, String pkcs11Library) throws NoSuchAlgorithmException,
258                    CertificateException, IOException, KeyStoreException, NoSuchProviderException,
259                    UnrecoverableKeyException, KeyManagementException, UnsupportedCallbackException,
260                    NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException,
261                    IllegalAccessException, IllegalArgumentException, InvocationTargetException {
262        final SSLContext context;
263        if (sslContextFactory != null) {
264            context = sslContextFactory.createSslContext();
265        } else {
266            // If the user didn't specify a SslContextFactory, use the default one
267            context = SSLContext.getInstance("TLS");
268        }
269
270        // TODO: Remove the block below once we removed setKeystorePath(), setKeystoreType(), setCallbackHandler() and
271        // setPKCS11Library() in the builder, and all related fields and the parameters of this function.
272        if (keyManagers == null) {
273            keyManagers = Builder.getKeyManagersFrom(keystoreType, keystorePath, callbackHandler, pkcs11Library);
274        }
275
276        SmackDaneVerifier daneVerifier = null;
277        if (dnssecMode == DnssecMode.needsDnssecAndDane) {
278            SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
279            if (daneProvider == null) {
280                throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
281            }
282            daneVerifier = daneProvider.newInstance();
283            if (daneVerifier == null) {
284                throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
285            }
286
287            // User requested DANE verification.
288            daneVerifier.init(context, keyManagers, trustManager, secureRandom);
289        } else {
290            final TrustManager[] trustManagers;
291            if (trustManager != null) {
292                trustManagers = new TrustManager[] { trustManager };
293            } else {
294                // Ensure trustManagers is null in case there was no explicit trust manager provided, so that the
295                // default one is used.
296                trustManagers = null;
297            }
298
299            context.init(keyManagers, trustManagers, secureRandom);
300        }
301
302        return new SmackTlsContext(context, daneVerifier);
303    }
304
305    public String getHostString() {
306        if (hostAddress != null) {
307            return hostAddress.toString();
308        }
309        if (host != null) {
310            return host.toString();
311        }
312        return xmppServiceDomain.toString();
313    }
314
315    public DnsName getHost() {
316        return host;
317    }
318
319    public InetAddress getHostAddress() {
320        return hostAddress;
321    }
322
323    public UInt16 getPort() {
324        return port;
325    }
326
327    /**
328     * Returns the server name of the target server.
329     *
330     * @return the server name of the target server.
331     * @deprecated use {@link #getXMPPServiceDomain()} instead.
332     */
333    @Deprecated
334    public DomainBareJid getServiceName() {
335        return xmppServiceDomain;
336    }
337
338    /**
339     * Returns the XMPP domain used by this configuration.
340     *
341     * @return the XMPP domain.
342     */
343    public DomainBareJid getXMPPServiceDomain() {
344        return xmppServiceDomain;
345    }
346
347    /**
348     * Returns the XMPP service domain as DNS name if possible. Note that since not every XMPP address domainpart is a
349     * valid DNS name, this method may return <code>null</code>.
350     *
351     * @return the XMPP service domain as DNS name or <code>null</code>.
352     * @since 4.3.4
353     */
354    public DnsName getXmppServiceDomainAsDnsNameIfPossible() {
355        return xmppServiceDomainDnsName;
356    }
357
358    /**
359     * Returns the TLS security mode used when making the connection. By default,
360     * the mode is {@link SecurityMode#required}.
361     *
362     * @return the security mode.
363     */
364    public SecurityMode getSecurityMode() {
365        return securityMode;
366    }
367
368    public DnssecMode getDnssecMode() {
369        return dnssecMode;
370    }
371
372    /**
373     * Return the enabled SSL/TLS protocols.
374     *
375     * @return the enabled SSL/TLS protocols
376     */
377    public String[] getEnabledSSLProtocols() {
378        return enabledSSLProtocols;
379    }
380
381    /**
382     * Return the enabled SSL/TLS ciphers.
383     *
384     * @return the enabled SSL/TLS ciphers
385     */
386    public String[] getEnabledSSLCiphers() {
387        return enabledSSLCiphers;
388    }
389
390    /**
391     * Returns the configured HostnameVerifier of this ConnectionConfiguration or the Smack default
392     * HostnameVerifier configured with
393     * {@link SmackConfiguration#setDefaultHostnameVerifier(HostnameVerifier)}.
394     *
395     * @return a configured HostnameVerifier or <code>null</code>
396     */
397    public HostnameVerifier getHostnameVerifier() {
398        if (hostnameVerifier != null)
399            return hostnameVerifier;
400        return SmackConfiguration.getDefaultHostnameVerifier();
401    }
402
403    /**
404     * Returns the Smack debugger factory.
405     *
406     * @return the Smack debugger factory or <code>null</code>
407     */
408    public SmackDebuggerFactory getDebuggerFactory() {
409        return debuggerFactory;
410    }
411
412    /**
413     * Returns a CallbackHandler to obtain information, such as the password or
414     * principal information during the SASL authentication. A CallbackHandler
415     * will be used <b>ONLY</b> if no password was specified during the login while
416     * using SASL authentication.
417     *
418     * @return a CallbackHandler to obtain information, such as the password or
419     * principal information during the SASL authentication.
420     */
421    public CallbackHandler getCallbackHandler() {
422        return callbackHandler;
423    }
424
425    /**
426     * Returns the socket factory used to create new xmppConnection sockets.
427     * This is useful when connecting through SOCKS5 proxies.
428     *
429     * @return socketFactory used to create new sockets.
430     */
431    public SocketFactory getSocketFactory() {
432        return this.socketFactory;
433    }
434
435    /**
436     * Get the configured proxy information (if any).
437     *
438     * @return the configured proxy information or <code>null</code>.
439     */
440    public ProxyInfo getProxyInfo() {
441        return proxy;
442    }
443
444    /**
445     * An enumeration for TLS security modes that are available when making a connection
446     * to the XMPP server.
447     */
448    public enum SecurityMode {
449
450        /**
451         * Security via TLS encryption is required in order to connect. If the server
452         * does not offer TLS or if the TLS negotiation fails, the connection to the server
453         * will fail.
454         */
455        required,
456
457        /**
458         * Security via TLS encryption is used whenever it's available. This is the
459         * default setting.
460         * <p>
461         * <b>Do not use this setting</b> unless you can't use {@link #required}. An attacker could easily perform a
462         * Man-in-the-middle attack and prevent TLS from being used, leaving you with an unencrypted (and
463         * unauthenticated) connection.
464         * </p>
465         */
466        ifpossible,
467
468        /**
469         * Security via TLS encryption is disabled and only un-encrypted connections will
470         * be used. If only TLS encryption is available from the server, the connection
471         * will fail.
472         */
473        disabled
474    }
475
476    /**
477     * Determines the requested DNSSEC security mode.
478     * <b>Note that Smack's support for DNSSEC/DANE is experimental!</b>
479     * <p>
480     * The default '{@link #disabled}' means that neither DNSSEC nor DANE verification will be performed. When
481     * '{@link #needsDnssec}' is used, then the connection will not be established if the resource records used to connect
482     * to the XMPP service are not authenticated by DNSSEC. Additionally, if '{@link #needsDnssecAndDane}' is used, then
483     * the XMPP service's TLS certificate is verified using DANE.
484     *
485     */
486    public enum DnssecMode {
487
488        /**
489         * Do not perform any DNSSEC authentication or DANE verification.
490         */
491        disabled,
492
493        /**
494         * <b>Experimental!</b>
495         * Require all DNS information to be authenticated by DNSSEC.
496         */
497        needsDnssec,
498
499        /**
500         * <b>Experimental!</b>
501         * Require all DNS information to be authenticated by DNSSEC and require the XMPP service's TLS certificate to be verified using DANE.
502         */
503        needsDnssecAndDane,
504
505    }
506
507    /**
508     * Returns the username to use when trying to reconnect to the server.
509     *
510     * @return the username to use when trying to reconnect to the server.
511     */
512    public CharSequence getUsername() {
513        return this.username;
514    }
515
516    /**
517     * Returns the password to use when trying to reconnect to the server.
518     *
519     * @return the password to use when trying to reconnect to the server.
520     */
521    public String getPassword() {
522        return this.password;
523    }
524
525    /**
526     * Returns the resource to use when trying to reconnect to the server.
527     *
528     * @return the resource to use when trying to reconnect to the server.
529     */
530    public Resourcepart getResource() {
531        return resource;
532    }
533
534    /**
535     * Returns the stream language to use when connecting to the server.
536     *
537     * @return the stream language to use when connecting to the server or <code>null</code>.
538     */
539    public Locale getLanguage() {
540        return language;
541    }
542
543    /**
544     * Returns the xml:lang string of the stream language to use when connecting to the server.
545     *
546     * <p>If the developer sets the language to null, this will also return null, leading to
547     * the removal of the xml:lang tag from the stream.</p>
548     *
549     * @return the stream language to use when connecting to the server or <code>null</code>.
550     */
551    public String getXmlLang() {
552        if (language == null) {
553            return null;
554        }
555
556        String languageTag = language.toLanguageTag();
557        if (languageTag.equals("und")) {
558            return null;
559        }
560
561        return languageTag;
562    }
563
564    /**
565     * Returns the optional XMPP address to be requested as the SASL authorization identity.
566     *
567     * @return the authorization identifier.
568     * @see <a href="http://tools.ietf.org/html/rfc6120#section-6.3.8">RFC 6120 § 6.3.8. Authorization Identity</a>
569     * @since 4.2
570     */
571    public EntityBareJid getAuthzid() {
572        return authzid;
573    }
574
575    /**
576     * Returns true if an available presence should be sent when logging in while reconnecting.
577     *
578     * @return true if an available presence should be sent when logging in while reconnecting
579     */
580    public boolean isSendPresence() {
581        return sendPresence;
582    }
583
584    /**
585     * Returns true if the connection is going to use stream compression. Stream compression
586     * will be requested after TLS was established (if TLS was enabled) and only if the server
587     * offered stream compression. With stream compression network traffic can be reduced
588     * up to 90%. By default,compression is disabled.
589     *
590     * @return true if the connection is going to use stream compression.
591     */
592    public boolean isCompressionEnabled() {
593        return compressionEnabled;
594    }
595
596    /**
597     * Check if the given SASL mechanism is enabled in this connection configuration.
598     *
599     * @param saslMechanism TODO javadoc me please
600     * @return true if the given SASL mechanism is enabled, false otherwise.
601     */
602    public boolean isEnabledSaslMechanism(String saslMechanism) {
603        // If enabledSaslMechanisms is not set, then all mechanisms which are not blacklisted are enabled per default.
604        if (enabledSaslMechanisms == null) {
605            return !SASLAuthentication.getBlacklistedSASLMechanisms().contains(saslMechanism);
606        }
607        return enabledSaslMechanisms.contains(saslMechanism);
608    }
609
610    /**
611     * Return the explicitly enabled SASL mechanisms. May return <code>null</code> if no SASL mechanisms where
612     * explicitly enabled, i.e. all SASL mechanisms supported and announced by the service will be considered.
613     *
614     * @return the enabled SASL mechanisms or <code>null</code>.
615     */
616    public Set<String> getEnabledSaslMechanisms() {
617        if (enabledSaslMechanisms == null) {
618            return null;
619        }
620        return Collections.unmodifiableSet(enabledSaslMechanisms);
621    }
622
623    StanzaIdSource constructStanzaIdSource() {
624        return stanzaIdSourceFactory.constructStanzaIdSource();
625    }
626
627    /**
628     * A builder for XMPP connection configurations.
629     * <p>
630     * This is an abstract class that uses the builder design pattern and the "getThis() trick" to recover the type of
631     * the builder in a class hierarchies with a self-referential generic supertype. Otherwise chaining of build
632     * instructions from the superclasses followed by build instructions of a subclass would not be possible, because
633     * the superclass build instructions would return the builder of the superclass and not the one of the subclass. You
634     * can read more about it a Angelika Langer's Generics FAQ, especially the entry <a
635     * href="http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206">What is the
636     * "getThis()" trick?</a>.
637     * </p>
638     *
639     * @param <B> the builder type parameter.
640     * @param <C> the resulting connection configuration type parameter.
641     */
642    public abstract static class Builder<B extends Builder<B, C>, C extends ConnectionConfiguration> {
643        private SecurityMode securityMode = SecurityMode.required;
644        private DnssecMode dnssecMode = DnssecMode.disabled;
645        private KeyManager[] keyManagers;
646        private SecureRandom sslContextSecureRandom;
647        private String keystorePath;
648        private String keystoreType;
649        private String pkcs11Library = "pkcs11.config";
650        private SslContextFactory sslContextFactory;
651        private String[] enabledSSLProtocols;
652        private String[] enabledSSLCiphers;
653        private HostnameVerifier hostnameVerifier;
654        private EntityBareJid authzid;
655        private CharSequence username;
656        private String password;
657        private Resourcepart resource;
658        private Locale language = Locale.getDefault();
659        private boolean sendPresence = true;
660        private ProxyInfo proxy;
661        private CallbackHandler callbackHandler;
662        private SmackDebuggerFactory debuggerFactory;
663        private SocketFactory socketFactory;
664        private DomainBareJid xmppServiceDomain;
665        private InetAddress hostAddress;
666        private DnsName host;
667        private UInt16 port = UInt16.from(5222);
668        private boolean allowEmptyOrNullUsername = false;
669        private boolean saslMechanismsSealed;
670        private Set<String> enabledSaslMechanisms;
671        private X509TrustManager customX509TrustManager;
672        private boolean compressionEnabled = false;
673        private StanzaIdSourceFactory stanzaIdSourceFactory = new StandardStanzaIdSource.Factory();
674
675        @SuppressWarnings("this-escape")
676        protected Builder() {
677            if (SmackConfiguration.DEBUG) {
678                enableDefaultDebugger();
679            }
680        }
681
682        /**
683         * Convenience method to configure the username, password and XMPP service domain.
684         *
685         * @param jid the XMPP address of the user.
686         * @param password the password of the user.
687         * @return a reference to this builder.
688         * @throws XmppStringprepException in case the XMPP address is not valid.
689         * @see #setXmppAddressAndPassword(EntityBareJid, String)
690         * @since 4.4.0
691         */
692        public B setXmppAddressAndPassword(CharSequence jid, String password) throws XmppStringprepException {
693            return setXmppAddressAndPassword(JidCreate.entityBareFrom(jid), password);
694        }
695
696        /**
697         * Convenience method to configure the username, password and XMPP service domain. The localpart of the provided
698         * JID is used as username and the domanipart is used as XMPP service domain.
699         * <p>
700         * Please note that this does and can not configure the client XMPP address. XMPP services are not required to
701         * assign bound JIDs where the localpart matches the username and the domainpart matches the verified domainpart.
702         * Although most services will follow that pattern.
703         * </p>
704         *
705         * @param jid TODO javadoc me please
706         * @param password TODO javadoc me please
707         * @return a reference to this builder.
708         * @since 4.4.0
709         */
710        public B setXmppAddressAndPassword(EntityBareJid jid, String password) {
711            setUsernameAndPassword(jid.getLocalpart(), password);
712            return setXmppDomain(jid.asDomainBareJid());
713        }
714
715        /**
716         * Set the XMPP entities username and password.
717         * <p>
718         * The username is usually the localpart of the clients JID. But some SASL mechanisms or services may require a different
719         * format (e.g. the full JID) as used authorization identity.
720         * </p>
721         *
722         * @param username the username or authorization identity
723         * @param password the password or token used to authenticate
724         * @return a reference to this builder.
725         */
726        public B setUsernameAndPassword(CharSequence username, String password) {
727            this.username = username;
728            this.password = password;
729            return getThis();
730        }
731
732        /**
733         * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs).
734         *
735         * @param serviceName the service name
736         * @return a reference to this builder.
737         * @deprecated use {@link #setXmppDomain(DomainBareJid)} instead.
738         */
739        @Deprecated
740        public B setServiceName(DomainBareJid serviceName) {
741            return setXmppDomain(serviceName);
742        }
743
744        /**
745         * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs).
746         *
747         * @param xmppDomain the XMPP domain.
748         * @return a reference to this builder.
749         */
750        public B setXmppDomain(DomainBareJid xmppDomain) {
751            this.xmppServiceDomain = xmppDomain;
752            return getThis();
753        }
754
755        /**
756         * Set the XMPP domain. The XMPP domain is what follows after the '@' sign in XMPP addresses (JIDs).
757         *
758         * @param xmppServiceDomain the XMPP domain.
759         * @return a reference to this builder.
760         * @throws XmppStringprepException if the given string is not a domain bare JID.
761         */
762        public B setXmppDomain(String xmppServiceDomain) throws XmppStringprepException {
763            this.xmppServiceDomain = JidCreate.domainBareFrom(xmppServiceDomain);
764            return getThis();
765        }
766
767        /**
768         * Set the resource we are requesting from the server.
769         * <p>
770         * If <code>resource</code> is <code>null</code>, the default, then the server will automatically create a
771         * resource for the client. Note that XMPP clients only suggest this resource to the server. XMPP servers are
772         * allowed to ignore the client suggested resource and instead assign a completely different
773         * resource (see RFC 6120 § 7.7.1).
774         * </p>
775         *
776         * @param resource the resource to use.
777         * @return a reference to this builder.
778         * @see <a href="https://tools.ietf.org/html/rfc6120#section-7.7.1">RFC 6120 § 7.7.1</a>
779         */
780        public B setResource(Resourcepart resource) {
781            this.resource = resource;
782            return getThis();
783        }
784
785        /**
786         * Set the stream language.
787         *
788         * @param language the language to use.
789         * @return a reference to this builder.
790         * @see <a href="https://tools.ietf.org/html/rfc6120#section-4.7.4">RFC 6120 § 4.7.4</a>
791         * @see <a href="https://www.w3.org/TR/xml/#sec-lang-tag">XML 1.0 § 2.12 Language Identification</a>
792         */
793        public B setLanguage(Locale language) {
794            this.language = language;
795            return getThis();
796        }
797
798        /**
799         * Set the resource we are requesting from the server.
800         *
801         * @param resource the non-null CharSequence to use a resource.
802         * @return a reference ot this builder.
803         * @throws XmppStringprepException if the CharSequence is not a valid resourcepart.
804         * @see #setResource(Resourcepart)
805         */
806        public B setResource(CharSequence resource) throws XmppStringprepException {
807            Objects.requireNonNull(resource, "resource must not be null");
808            return setResource(Resourcepart.from(resource.toString()));
809        }
810
811        /**
812         * Set the Internet address of the host providing the XMPP service. If set, then this will overwrite anything
813         * set via {@link #setHost(CharSequence)}.
814         *
815         * @param address the Internet address of the host providing the XMPP service.
816         * @return a reference to this builder.
817         * @since 4.2
818         */
819        public B setHostAddress(InetAddress address) {
820            this.hostAddress = address;
821            return getThis();
822        }
823
824        /**
825         * Set the name of the host providing the XMPP service. This method takes DNS names and
826         * IP addresses.
827         *
828         * @param host the DNS name of the host providing the XMPP service.
829         * @return a reference to this builder.
830         */
831        public B setHost(CharSequence host) {
832            String fqdnOrIpString = host.toString();
833            if (InetAddressUtil.isIpAddress(fqdnOrIpString)) {
834                InetAddress hostInetAddress;
835                try {
836                    hostInetAddress = InetAddress.getByName(fqdnOrIpString);
837                }
838                catch (UnknownHostException e) {
839                    // Should never happen.
840                    throw new AssertionError(e);
841                }
842                setHostAddress(hostInetAddress);
843            } else {
844                DnsName dnsName = DnsName.from(fqdnOrIpString);
845                setHost(dnsName);
846            }
847            return getThis();
848        }
849
850        /**
851         * Set the name of the host providing the XMPP service. Note that this method does only allow DNS names and not
852         * IP addresses. Use {@link #setHostAddress(InetAddress)} if you want to explicitly set the Internet address of
853         * the host providing the XMPP service.
854         *
855         * @param host the DNS name of the host providing the XMPP service.
856         * @return a reference to this builder.
857         */
858        public B setHost(DnsName host) {
859            this.host = host;
860            return getThis();
861        }
862
863        public B setPort(int port) {
864            if (port < 0 || port > 65535) {
865                throw new IllegalArgumentException(
866                        "Port must be a 16-bit unsigned integer (i.e. between 0-65535. Port was: " + port);
867            }
868            UInt16 portUint16 = UInt16.from(port);
869            return setPort(portUint16);
870        }
871
872        public B setPort(UInt16 port) {
873            this.port = Objects.requireNonNull(port);
874            return getThis();
875        }
876
877        /**
878         * Sets a CallbackHandler to obtain information, such as the password or
879         * principal information during the SASL authentication. A CallbackHandler
880         * will be used <b>ONLY</b> if no password was specified during the login while
881         * using SASL authentication.
882         *
883         * @param callbackHandler to obtain information, such as the password or
884         * principal information during the SASL authentication.
885         * @return a reference to this builder.
886         * @deprecated set a callback-handler aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or
887         *             {@link #setKeyManagers(KeyManager[])}, created by
888         *             {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead.
889         */
890        // TODO: Remove in Smack 4.6.
891        @Deprecated
892        public B setCallbackHandler(CallbackHandler callbackHandler) {
893            this.callbackHandler = callbackHandler;
894            return getThis();
895        }
896
897        public B setDnssecMode(DnssecMode dnssecMode) {
898            this.dnssecMode = Objects.requireNonNull(dnssecMode, "DNSSEC mode must not be null");
899            return getThis();
900        }
901
902        public B setCustomX509TrustManager(X509TrustManager x509TrustManager) {
903            this.customX509TrustManager = x509TrustManager;
904            return getThis();
905        }
906
907        /**
908         * Sets the TLS security mode used when making the connection. By default,
909         * the mode is {@link SecurityMode#required}.
910         *
911         * @param securityMode the security mode.
912         * @return a reference to this builder.
913         */
914        public B setSecurityMode(SecurityMode securityMode) {
915            this.securityMode = securityMode;
916            return getThis();
917        }
918
919        /**
920         * Set the {@link KeyManager}s to initialize the {@link SSLContext} used by Smack to establish the XMPP connection.
921         *
922         * @param keyManagers an array of {@link KeyManager}s to initialize the {@link SSLContext} with.
923         * @return a reference to this builder.
924         * @since 4.4.5
925         */
926        public B setKeyManagers(KeyManager[] keyManagers) {
927            this.keyManagers = keyManagers;
928            return getThis();
929        }
930
931        /**
932         * Set the {@link KeyManager}s to initialize the {@link SSLContext} used by Smack to establish the XMPP connection.
933         *
934         * @param keyManager the {@link KeyManager}s to initialize the {@link SSLContext} with.
935         * @return a reference to this builder.
936         * @see #setKeyManagers(KeyManager[])
937         * @since 4.4.5
938         */
939        public B setKeyManager(KeyManager keyManager) {
940            KeyManager[] keyManagers = new KeyManager[] { keyManager };
941            return setKeyManagers(keyManagers);
942        }
943
944        /**
945         * Set the {@link SecureRandom} used to initialize the {@link SSLContext} used by Smack to establish the XMPP
946         * connection. Note that you usually do not need (nor want) to set this. Because if the {@link SecureRandom} is
947         * not explicitly set, Smack will initialize the {@link SSLContext} with <code>null</code> as
948         * {@link SecureRandom} argument. And all sane {@link SSLContext} implementations will then select a safe secure
949         * random source by default.
950         *
951         * @param secureRandom the {@link SecureRandom} to initialize the {@link SSLContext} with.
952         * @return a reference to this builder.
953         * @since 4.4.5
954         */
955        public B setSslContextSecureRandom(SecureRandom secureRandom) {
956            this.sslContextSecureRandom = secureRandom;
957            return getThis();
958        }
959
960        /**
961         * Sets the path to the keystore file. The key store file contains the
962         * certificates that may be used to authenticate the client to the server,
963         * in the event the server requests or requires it.
964         *
965         * @param keystorePath the path to the keystore file.
966         * @return a reference to this builder.
967         * @deprecated set a keystore-path aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or
968         *             {@link #setKeyManagers(KeyManager[])}, created by
969         *             {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead.
970         */
971        // TODO: Remove in Smack 4.6.
972        @Deprecated
973        public B setKeystorePath(String keystorePath) {
974            this.keystorePath = keystorePath;
975            return getThis();
976        }
977
978        /**
979         * Sets the keystore type.
980         *
981         * @param keystoreType the keystore type.
982         * @return a reference to this builder.
983         * @deprecated set a key-type aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or
984         *             {@link #setKeyManagers(KeyManager[])}, created by
985         *             {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead.
986         */
987        // TODO: Remove in Smack 4.6.
988        @Deprecated
989        public B setKeystoreType(String keystoreType) {
990            this.keystoreType = keystoreType;
991            return getThis();
992        }
993
994        /**
995         * Sets the PKCS11 library file location, needed when the
996         * Keystore type is PKCS11.
997         *
998         * @param pkcs11Library the path to the PKCS11 library file.
999         * @return a reference to this builder.
1000         * @deprecated set a PKCS11-library aware {@link KeyManager} via {@link #setKeyManager(KeyManager)} or
1001         *             {@link #setKeyManagers(KeyManager[])}, created by
1002         *             {@link #getKeyManagersFrom(String, String, CallbackHandler, String)}, instead.
1003         */
1004        // TODO: Remove in Smack 4.6.
1005        @Deprecated
1006        public B setPKCS11Library(String pkcs11Library) {
1007            this.pkcs11Library = pkcs11Library;
1008            return getThis();
1009        }
1010
1011        /**
1012         * Sets a custom SSLContext for creating SSL sockets.
1013         * <p>
1014         * For more information on how to create a SSLContext see <a href=
1015         * "http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#X509TrustManager"
1016         * >Java Secure Socket Extension (JSEE) Reference Guide: Creating Your Own X509TrustManager</a>
1017         *
1018         * @param sslContextFactory the custom SSLContext for new sockets.
1019         * @return a reference to this builder.
1020         */
1021        public B setSslContextFactory(SslContextFactory sslContextFactory) {
1022            this.sslContextFactory = Objects.requireNonNull(sslContextFactory, "The provided SslContextFactory must not be null");
1023            return getThis();
1024        }
1025
1026        /**
1027         * Set the enabled SSL/TLS protocols.
1028         *
1029         * @param enabledSSLProtocols TODO javadoc me please
1030         * @return a reference to this builder.
1031         */
1032        public B setEnabledSSLProtocols(String[] enabledSSLProtocols) {
1033            this.enabledSSLProtocols = enabledSSLProtocols;
1034            return getThis();
1035        }
1036
1037        /**
1038         * Set the enabled SSL/TLS ciphers.
1039         *
1040         * @param enabledSSLCiphers the enabled SSL/TLS ciphers
1041         * @return a reference to this builder.
1042         */
1043        public B setEnabledSSLCiphers(String[] enabledSSLCiphers) {
1044            this.enabledSSLCiphers = enabledSSLCiphers;
1045            return getThis();
1046        }
1047
1048        /**
1049         * Set the HostnameVerifier used to verify the hostname of SSLSockets used by XMPP connections
1050         * created with this ConnectionConfiguration.
1051         *
1052         * @param verifier TODO javadoc me please
1053         * @return a reference to this builder.
1054         */
1055        public B setHostnameVerifier(HostnameVerifier verifier) {
1056            hostnameVerifier = verifier;
1057            return getThis();
1058        }
1059
1060        /**
1061         * Sets if an initial available presence will be sent to the server. By default,         * an available presence will be sent to the server indicating that this presence
1062         * is not online and available to receive messages. If you want to log in without
1063         * being 'noticed' then pass a <code>false</code> value.
1064         *
1065         * @param sendPresence true if an initial available presence will be sent while logging in.
1066         * @return a reference to this builder.
1067         */
1068        public B setSendPresence(boolean sendPresence) {
1069            this.sendPresence = sendPresence;
1070            return getThis();
1071        }
1072
1073        public B enableDefaultDebugger() {
1074            this.debuggerFactory = SmackConfiguration.getDefaultSmackDebuggerFactory();
1075            assert this.debuggerFactory != null;
1076            return getThis();
1077        }
1078
1079        /**
1080         * Set the Smack debugger factory used to construct Smack debuggers.
1081         *
1082         * @param debuggerFactory the Smack debugger factory.
1083         * @return a reference to this builder.
1084         */
1085        public B setDebuggerFactory(SmackDebuggerFactory debuggerFactory) {
1086            this.debuggerFactory = debuggerFactory;
1087            return getThis();
1088        }
1089
1090        /**
1091         * Sets the socket factory used to create new xmppConnection sockets.
1092         * This is useful when connecting through SOCKS5 proxies.
1093         *
1094         * @param socketFactory used to create new sockets.
1095         * @return a reference to this builder.
1096         */
1097        public B setSocketFactory(SocketFactory socketFactory) {
1098            this.socketFactory = socketFactory;
1099            return getThis();
1100        }
1101
1102        /**
1103         * Set the information about the Proxy used for the connection.
1104         *
1105         * @param proxyInfo the Proxy information.
1106         * @return a reference to this builder.
1107         */
1108        public B setProxyInfo(ProxyInfo proxyInfo) {
1109            this.proxy = proxyInfo;
1110            return getThis();
1111        }
1112
1113        /**
1114         * Allow <code>null</code> or the empty String as username.
1115         *
1116         * Some SASL mechanisms (e.g. SASL External) may also signal the username (as "authorization identity"), in
1117         * which case Smack should not throw an IllegalArgumentException when the username is not set.
1118         *
1119         * @return a reference to this builder.
1120         */
1121        public B allowEmptyOrNullUsernames() {
1122            allowEmptyOrNullUsername = true;
1123            return getThis();
1124        }
1125
1126        /**
1127         * Perform anonymous authentication using SASL ANONYMOUS. Your XMPP service must support this authentication
1128         * mechanism. This method also calls {@link #addEnabledSaslMechanism(String)} with "ANONYMOUS" as argument.
1129         *
1130         * @return a reference to this builder.
1131         */
1132        public B performSaslAnonymousAuthentication() {
1133            if (!SASLAuthentication.isSaslMechanismRegistered(SASLAnonymous.NAME)) {
1134                throw new IllegalArgumentException("SASL " + SASLAnonymous.NAME + " is not registered");
1135            }
1136            throwIfEnabledSaslMechanismsSet();
1137
1138            allowEmptyOrNullUsernames();
1139            addEnabledSaslMechanism(SASLAnonymous.NAME);
1140            saslMechanismsSealed = true;
1141            return getThis();
1142        }
1143
1144        /**
1145         * Perform authentication using SASL EXTERNAL. Your XMPP service must support this
1146         * authentication mechanism. This method also calls {@link #addEnabledSaslMechanism(String)} with "EXTERNAL" as
1147         * argument. It also calls {@link #allowEmptyOrNullUsernames()} and {@link #setSecurityMode(ConnectionConfiguration.SecurityMode)} to
1148         * {@link SecurityMode#required}.
1149         *
1150         * @param sslContext custom SSLContext to be used.
1151         * @return a reference to this builder.
1152         */
1153        public B performSaslExternalAuthentication(SSLContext sslContext) {
1154            if (!SASLAuthentication.isSaslMechanismRegistered(SASLMechanism.EXTERNAL)) {
1155                throw new IllegalArgumentException("SASL " + SASLMechanism.EXTERNAL + " is not registered");
1156            }
1157            setSslContextFactory(() -> {
1158                return sslContext;
1159            });
1160            throwIfEnabledSaslMechanismsSet();
1161
1162            allowEmptyOrNullUsernames();
1163            setSecurityMode(SecurityMode.required);
1164            addEnabledSaslMechanism(SASLMechanism.EXTERNAL);
1165            saslMechanismsSealed = true;
1166            return getThis();
1167        }
1168
1169        private void throwIfEnabledSaslMechanismsSet() {
1170            if (enabledSaslMechanisms != null) {
1171                throw new IllegalStateException("Enabled SASL mechanisms found");
1172            }
1173        }
1174
1175        /**
1176         * Add the given mechanism to the enabled ones. See {@link #addEnabledSaslMechanism(Collection)} for a discussion about enabled SASL mechanisms.
1177         *
1178         * @param saslMechanism the name of the mechanism to enable.
1179         * @return a reference to this builder.
1180         */
1181        public B addEnabledSaslMechanism(String saslMechanism) {
1182            return addEnabledSaslMechanism(Arrays.asList(StringUtils.requireNotNullNorEmpty(saslMechanism,
1183                            "saslMechanism must not be null nor empty")));
1184        }
1185
1186        /**
1187         * Enable the given SASL mechanisms. If you never add a mechanism to the set of enabled ones, <b>all mechanisms
1188         * known to Smack</b> will be enabled. Only explicitly enable particular SASL mechanisms if you want to limit
1189         * the used mechanisms to the enabled ones.
1190         *
1191         * @param saslMechanisms a collection of names of mechanisms to enable.
1192         * @return a reference to this builder.
1193         */
1194        public B addEnabledSaslMechanism(Collection<String> saslMechanisms) {
1195            if (saslMechanismsSealed) {
1196                throw new IllegalStateException("The enabled SASL mechanisms are sealed, you can not add new ones");
1197            }
1198            CollectionUtil.requireNotEmpty(saslMechanisms, "saslMechanisms");
1199            Set<String> blacklistedMechanisms = SASLAuthentication.getBlacklistedSASLMechanisms();
1200            for (String mechanism : saslMechanisms) {
1201                if (!SASLAuthentication.isSaslMechanismRegistered(mechanism)) {
1202                    throw new IllegalArgumentException("SASL " + mechanism + " is not available. Consider registering it with Smack");
1203                }
1204                if (blacklistedMechanisms.contains(mechanism)) {
1205                    throw new IllegalArgumentException("SALS " + mechanism + " is blacklisted.");
1206                }
1207            }
1208            if (enabledSaslMechanisms == null) {
1209                enabledSaslMechanisms = new HashSet<>(saslMechanisms.size());
1210            }
1211            enabledSaslMechanisms.addAll(saslMechanisms);
1212            return getThis();
1213        }
1214
1215        /**
1216         * Set the XMPP address to be used as authorization identity.
1217         * <p>
1218         * In XMPP, authorization identities are bare jids. In general, callers should allow the server to select the
1219         * authorization identifier automatically, and not call this. Note that setting the authzid does not set the XMPP
1220         * service domain, which should typically match.
1221         * Calling this will also SASL CRAM, since this mechanism does not support authzid.
1222         * </p>
1223         *
1224         * @param authzid The BareJid to be requested as the authorization identifier.
1225         * @return a reference to this builder.
1226         * @see <a href="http://tools.ietf.org/html/rfc6120#section-6.3.8">RFC 6120 § 6.3.8. Authorization Identity</a>
1227         * @since 4.2
1228         */
1229        public B setAuthzid(EntityBareJid authzid) {
1230            this.authzid = authzid;
1231            return getThis();
1232        }
1233
1234        /**
1235         * Sets if the connection is going to use compression (default false).
1236         *
1237         * Compression is only activated if the server offers compression. With compression network
1238         * traffic can be reduced up to 90%. By default,compression is disabled.
1239         *
1240         * @param compressionEnabled if the connection is going to use compression on the HTTP level.
1241         * @return a reference to this object.
1242         */
1243        public B setCompressionEnabled(boolean compressionEnabled) {
1244            this.compressionEnabled = compressionEnabled;
1245            return getThis();
1246        }
1247
1248        /**
1249         * Set the factory for stanza ID sources to use.
1250         *
1251         * @param stanzaIdSourceFactory the factory for stanza ID sources to use.
1252         * @return a reference to this builder.
1253         * @since 4.4
1254         */
1255        public B setStanzaIdSourceFactory(StanzaIdSourceFactory stanzaIdSourceFactory) {
1256            this.stanzaIdSourceFactory = Objects.requireNonNull(stanzaIdSourceFactory);
1257            return getThis();
1258        }
1259
1260        public abstract C build();
1261
1262        protected abstract B getThis();
1263
1264        public static KeyManager[] getKeyManagersFrom(String keystoreType, String keystorePath,
1265                        CallbackHandler callbackHandler, String pkcs11Library)
1266                        throws NoSuchMethodException, SecurityException, ClassNotFoundException, KeyStoreException,
1267                        NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, UnsupportedCallbackException, UnrecoverableKeyException {
1268            KeyManager[] keyManagers = null;
1269            KeyStore ks = null;
1270            PasswordCallback pcb = null;
1271
1272            if ("PKCS11".equals(keystoreType)) {
1273                    Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
1274                    String pkcs11Config = "name = SmartCard\nlibrary = " + pkcs11Library;
1275                    ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StandardCharsets.UTF_8));
1276                    Provider p = (Provider) c.newInstance(config);
1277                    Security.addProvider(p);
1278                    ks = KeyStore.getInstance("PKCS11", p);
1279                    pcb = new PasswordCallback("PKCS11 Password: ", false);
1280                    callbackHandler.handle(new Callback[] { pcb });
1281                    ks.load(null, pcb.getPassword());
1282            } else if ("Apple".equals(keystoreType)) {
1283                ks = KeyStore.getInstance("KeychainStore", "Apple");
1284                ks.load(null, null);
1285                // pcb = new PasswordCallback("Apple Keychain",false);
1286                // pcb.setPassword(null);
1287            } else if (keystoreType != null) {
1288                ks = KeyStore.getInstance(keystoreType);
1289                if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
1290                    pcb = new PasswordCallback("Keystore Password: ", false);
1291                    callbackHandler.handle(new Callback[] { pcb });
1292                    ks.load(new FileInputStream(keystorePath), pcb.getPassword());
1293                } else {
1294                    InputStream stream = TLSUtils.getDefaultTruststoreStreamIfPossible();
1295                    try {
1296                        // Note that PKCS12 keystores need a password one some Java platforms. Hence, we try the famous
1297                        // 'changeit' here. See https://bugs.openjdk.java.net/browse/JDK-8194702
1298                        char[] password = "changeit".toCharArray();
1299                        try {
1300                            ks.load(stream, password);
1301                        } finally {
1302                            CloseableUtil.maybeClose(stream);
1303                        }
1304                    } catch (IOException e) {
1305                        LOGGER.log(Level.FINE, "KeyStore load() threw, attempting 'jks' fallback", e);
1306
1307                        ks = KeyStore.getInstance("jks");
1308                        // Open the stream again, so that we read it from the beginning.
1309                        stream = TLSUtils.getDefaultTruststoreStreamIfPossible();
1310                        try {
1311                            ks.load(stream, null);
1312                        } finally {
1313                            CloseableUtil.maybeClose(stream);
1314                        }
1315                    }
1316                }
1317            }
1318
1319            if (ks != null) {
1320                String keyManagerFactoryAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
1321                KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerFactoryAlgorithm);
1322                if (kmf != null) {
1323                    if (pcb == null) {
1324                        kmf.init(ks, null);
1325                    } else {
1326                        kmf.init(ks, pcb.getPassword());
1327                        pcb.clearPassword();
1328                    }
1329                    keyManagers = kmf.getKeyManagers();
1330                }
1331            }
1332
1333            return keyManagers;
1334        }
1335    }
1336}