public XMPPTCPConnectionConfiguration.Builder getConnectionConfigBuilder() { if (!isBasicConfigurationDone()) return null; if (confBuilderCache == null) { XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder(); String password = getPassword(); builder.setUsernameAndPassword(getMyJid().getLocalpart(), password); builder.setXmppDomain(getMyJid().asDomainBareJid()); builder.setSecurityMode(ConnectionConfiguration.SecurityMode.required); SSLContext sc; try { sc = SSLContext.getInstance("TLS"); sc.init(null, new X509TrustManager[] { mMemorizingTrustManager }, new java.security.SecureRandom()); } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new IllegalStateException(e); } builder.setCustomSSLContext(sc); confBuilderCache = builder; } return confBuilderCache; }
private KeyStore configKeyStore(XMPPTCPConnectionConfiguration.Builder builder) throws KeyStoreException { KeyStore keyStore; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { builder.setKeystorePath(null); builder.setKeystoreType("AndroidCAStore"); keyStore = KeyStore.getInstance("AndroidCAStore"); } else { builder.setKeystoreType("BKS"); keyStore = KeyStore.getInstance("BKS"); String path = System.getProperty("javax.net.ssl.trustStore"); if (path == null) path = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security" + File.separator + "cacerts.bks"; builder.setKeystorePath(path); } return keyStore; }
@Override public void connect(XmppURI uri, String password) throws IOException, XMPPException, SmackException { this.disconnect(); XMPPTCPConnectionConfiguration configuration = XMPPTCPConnectionConfiguration.builder() .setUsernameAndPassword(uri.getNode(), password) .setServiceName(uri.getDomain()) .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled) .setDebuggerEnabled(true) .build(); AbstractXMPPConnection connection = new XMPPTCPConnection(configuration); connection.connect(); connection.login(); // keep connection alive // when connection is idle it will run into timeout PingManager pingManager = PingManager.getInstanceFor(connection); pingManager.setPingInterval(60); pingManager.pingMyServer(); this.connection = connection; }
private XMPPTCPConnectionConfiguration newConnectionConfiguration(final BindingConfiguration configuration){ XMPPTCPConnectionConfiguration.Builder configurationBuilder = XMPPTCPConnectionConfiguration.builder(); configurationBuilder.setHost(configuration.getUrl()) .setPort(configuration.getPort()) .setServiceName(configuration.getServerName()) .setUsernameAndPassword(configuration.getUsername(),configuration.getPassword()) .setResource(configuration.getIdentifier()) .setDebuggerEnabled(configuration.isDebug()); if(allowSelfSigned){ try { configurationBuilder.setCustomSSLContext(SSLHelper.newAllTrustingSslContext()); } catch (KeyManagementException | NoSuchAlgorithmException e) { logger.error("Error registering custom ssl context",e); } } return configurationBuilder.build(); }
public void connect(String hostname, int port, String username, String password) throws Exception { purgeTask("reconnect"); this.hostname = hostname; this.serviceName = hostname; this.port = port; this.username = username; this.password = password; Builder builder = XMPPTCPConnectionConfiguration.builder(); builder.setUsernameAndPassword(username, password); builder.setServiceName(serviceName); builder.setServiceName(hostname); builder.setPort(port); builder.setSecurityMode(SecurityMode.disabled); builder.setDebuggerEnabled(true); XMPPTCPConnectionConfiguration config = builder.build(); connection = new XMPPTCPConnection(config); connection.connect().login(); roster = Roster.getInstanceFor(connection); chatManager = ChatManager.getInstanceFor(connection); roster.addRosterListener(this); isConnected = true; // not worth it - always empty right after connect // getContactList(); broadcastState(); }
@Before public void setUp() throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(XMPPIntegrationTest.class.getResourceAsStream("/server.jks"), "secret".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); String port = AvailablePortFinder.readServerData("xmpp-port"); ConnectionConfiguration connectionConfig = XMPPTCPConnectionConfiguration.builder() .setXmppDomain(JidCreate.domainBareFrom("apache.camel")) .setHostAddress(InetAddress.getLocalHost()) .setPort(Integer.parseInt(port)) .setCustomSSLContext(sslContext) .setHostnameVerifier((hostname, session) -> true) .build(); context.bind("customConnectionConfig", connectionConfig); }
private void initPrivateConnection() { long currentUserId = CurrentUser.getInstance().getCurrentUserId(); String currentUserPassword = CurrentUser.getInstance().getCurrentPassword(); String userName = currentUserId + "-" + ApiConstants.APP_ID; XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); configBuilder.setUsernameAndPassword(userName, currentUserPassword); configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); configBuilder.setServiceName(ApiConstants.CHAT_END_POINT); configBuilder.setHost(ApiConstants.CHAT_END_POINT); configBuilder.setDebuggerEnabled(true); privateChatConnection = new XMPPTCPConnection(configBuilder.build()); privateChatConnection.addConnectionListener(this); ReconnectionManager manager = ReconnectionManager.getInstanceFor(privateChatConnection); manager.enableAutomaticReconnection(); manager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY); manager.setFixedDelay(15); ProviderManager.addExtensionProvider(Displayed.ELEMENT, Displayed.NAMESPACE, new Displayed.Provider()); DisplayedManager.getInstanceFor(privateChatConnection).addDisplayedListener( (fromJid, toJid, receiptId, receipt) -> { messageService.get().processDisplayed(fromJid, toJid, receiptId, receipt); }); ProviderManager.addExtensionProvider(Received.ELEMENT, Received.NAMESPACE, new Received.Provider()); ReceivedManager.getInstanceFor(privateChatConnection).addReceivedListener( (fromJid, toJid, receiptId, receipt) -> { messageService.get().processReceived(fromJid, toJid, receiptId, receipt); }); }
public XMPPTCPConnection createManagedConnection(XMPPTCPConnectionConfiguration configuration) { XMPPTCPConnection connection = new XMPPTCPConnection(configuration); ManagedXmppConnection managedConnection = new ManagedXmppConnection(connection); for (NewManagedConnectionListener newManagedConnectionListener : mNewConnectionListeners) { newManagedConnectionListener.newConnection(managedConnection); } synchronized (managedConnection) { mManagedConnections.put(connection, managedConnection); } return connection; }
private void configSSLContext(XMPPTCPConnectionConfiguration.Builder builder, KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); builder.setCustomSSLContext(sslContext); }
private XMPPTCPConnectionConfiguration buildConfiguration() throws XmppStringprepException { XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder(); builder.setHost(HOST1); builder.setPort(PORT); builder.setCompressionEnabled(false); builder.setDebuggerEnabled(true); builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); builder.setSendPresence(true); if (Build.VERSION.SDK_INT >= 14) { builder.setKeystoreType("AndroidCAStore"); // config.setTruststorePassword(null); builder.setKeystorePath(null); } else { builder.setKeystoreType("BKS"); String str = System.getProperty("javax.net.ssl.trustStore"); if (str == null) { str = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security" + File.separator + "cacerts.bks"; } builder.setKeystorePath(str); } DomainBareJid serviceName = JidCreate.domainBareFrom(HOST); builder.setServiceName(serviceName); return builder.build(); }
public static AbstractXMPPConnection getConnection() { if ( XMPPConnectionManager.isConfigured == false ) { Log.w(LOGTAG, "Instating unconfigured connection" ); return null; } if ( XMPPConnectionManager.isConnected == false ) { // Send the configuration // TODO: Yes I know, this is restrictive, DNS must be working XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder(); configBuilder.setUsernameAndPassword( XMPPConnectionManager.xmppUserName, XMPPConnectionManager.xmppPassword); configBuilder.setServiceName( XMPPConnectionManager.xmppUserDomain ); configBuilder.setResource( "FlowsManager" ); XMPPConnectionManager.connection = new XMPPTCPConnection(configBuilder.build()); try { // Create a connection to the XMPP server. XMPPConnectionManager.connection.connect(); // Log into the server XMPPConnectionManager.connection.login(); } catch (Exception ex) { Log.w(LOGTAG, "XMPP Connection error " + ex); return null ; } XMPPConnectionManager.isConnected = true ; } return XMPPConnectionManager.connection ; }
private void createConnection() { Logger.debug(TAG, "creating new connection to " + mAccount.getHost() + ":" + mAccount.getPort()); XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder() .setServiceName(mAccount.getServiceName()) .setResource(mAccount.getResourceName()) .setHost(mAccount.getHost()) .setPort(mAccount.getPort()) .setUsernameAndPassword(mAccount.getXmppJid(), mAccount.getPassword()) .setConnectTimeout(XmppService.CONNECT_TIMEOUT); if (XmppService.CUSTOM_SSL_CONTEXT != null) { Logger.debug(TAG, "setting custom SSL context"); builder.setCustomSSLContext(XmppService.CUSTOM_SSL_CONTEXT); } if (XmppService.CUSTOM_HOSTNAME_VERIFIER != null) { Logger.debug(TAG, "setting custom hostname verifier"); builder.setHostnameVerifier(XmppService.CUSTOM_HOSTNAME_VERIFIER); } mConnection = new XMPPTCPConnection(builder.build()); mConnection.setUseStreamManagement(XmppService.USE_STREAM_MANAGEMENT); mConnection.setUseStreamManagementResumption(XmppService.USE_STREAM_MANAGEMENT); mConnection.setPreferredResumptionTime(XmppService.STREAM_MANAGEMENT_RESUMPTION_TIME); mConnection.addConnectionListener(this); }
public void setup() { this.configBuilder = XMPPTCPConnectionConfiguration.builder(); this.configBuilder.setUsernameAndPassword(XMPPConnectionHandler.username, XMPPConnectionHandler.password); this.configBuilder.setResource(XMPPConnectionHandler.resource); this.configBuilder.setServiceName(XMPPConnectionHandler.service); this.configBuilder.setHost(XMPPConnectionHandler.host); this.configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled); this.connection = new XMPPTCPConnection(this.configBuilder.build()); }
/** * Creates a new XMPP connection over TCP (optionally using proxies). * <p> * Note that XMPPTCPConnection constructors do not establish a connection to the server * and you must call {@link #connect()}. * </p> * * @param config the connection configuration. */ public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) { super(config); this.config = config; addConnectionListener(new AbstractConnectionListener() { @Override public void connectionClosedOnError(Exception e) { if (e instanceof XMPPException.StreamErrorException || e instanceof StreamManagementException) { dropSmState(); } } }); }
private XMPPConnection login(final Configuration config) throws IOException, XMPPException, SmackException, KeyManagementException, NoSuchAlgorithmException { final String serviceName = isNullOrEmpty(config.getString(CK_SERVICE_NAME)) ? config.getString(CK_HOSTNAME) : config.getString(CK_SERVICE_NAME); final XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder() .setHost(config.getString(CK_HOSTNAME)) .setPort(config.getInt(CK_PORT)) .setServiceName(serviceName) .setSendPresence(false); if (config.getBoolean(CK_ACCEPT_SELFSIGNED)) { TLSUtils.acceptAllCertificates(configBuilder); } final boolean requireSecurity = config.getBoolean(CK_REQUIRE_SECURITY); configBuilder.setSecurityMode(requireSecurity ? ConnectionConfiguration.SecurityMode.required : ConnectionConfiguration.SecurityMode.ifpossible); final XMPPTCPConnectionConfiguration connectionConfiguration = configBuilder.build(); if (LOG.isDebugEnabled()) { LOG.debug("Supported SASL authentications: {}", SASLAuthentication.getRegisterdSASLMechanisms()); LOG.debug("require_security: {}", requireSecurity); LOG.debug("Security mode: {}", connectionConfiguration.getSecurityMode()); LOG.debug("Socket factory: {}", connectionConfiguration.getSocketFactory()); LOG.debug("Keystore: {}", connectionConfiguration.getKeystorePath()); LOG.debug("Keystore type: {}", connectionConfiguration.getKeystoreType()); } final XMPPTCPConnection xmppConnection = new XMPPTCPConnection(connectionConfiguration); xmppConnection.connect(); xmppConnection.login(config.getString(CK_USERNAME), config.getString(CK_PASSWORD)); return xmppConnection; }
private static XMPPTCPConnectionConfiguration buildConfiguration(String resource, EndpointServer server, boolean secure, PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore, String legacyAuthToken) throws XmppStringprepException { XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder(); String host = server.getHost(); InetAddress inetAddress = null; if (host != null) { try { inetAddress = InetAddress.getByName(host); } catch (UnknownHostException e) { Log.w(TAG, "unable to resolve host " + host + ", will try again during connect", e); } } builder // connection parameters .setHostAddress(inetAddress) // try a last time through Smack .setHost(inetAddress != null ? null : host) .setPort(secure ? server.getSecurePort() : server.getPort()) .setXmppDomain(server.getNetwork()) .setResource(resource) // the dummy value is not actually used .setUsernameAndPassword(null, legacyAuthToken != null ? legacyAuthToken : "dummy") // for EXTERNAL .allowEmptyOrNullUsernames() // enable compression .setCompressionEnabled(true) // enable encryption .setSecurityMode(secure ? SecurityMode.disabled : SecurityMode.required) // we will send a custom presence .setSendPresence(false) // disable session initiation .setLegacySessionDisabled(true) // enable debugging .setDebuggerEnabled(Log.isDebug()); // setup SSL setupSSL(builder, secure, privateKey, bridgeCert, acceptAnyCertificate, trustStore); return builder.build(); }
public void connect() throws IOException, XMPPException, SmackException { Log.i(TAG, "connect()"); XMPPTCPConnectionConfiguration.XMPPTCPConnectionConfigurationBuilder builder = XMPPTCPConnectionConfiguration.builder(); builder.setServiceName(mServiceName); builder.setResource("SmackAndroidTestClient"); builder.setUsernameAndPassword(mUsername, mPassword); builder.setRosterLoadedAtLogin(true); mConnection = new XMPPTCPConnection(builder.build()); //Set ConnectionListener here to catch initial connect(); mConnection.addConnectionListener(this); mConnection.connect(); mConnection.login(); PingManager.setDefaultPingInterval(600); //Ping every 10 minutes PingManager pingManager = PingManager.getInstanceFor(mConnection); pingManager.registerPingFailedListener(this); setupSendMessageReceiver(); ChatManager.getInstanceFor(mConnection).addChatListener(this); mConnection.getRoster().addRosterListener(this); }
/** * Creates a new XMPP connection over TCP. * <p> * This is the simplest constructor for connecting to an XMPP server. Alternatively, * you can get fine-grained control over connection settings using the * {@link #XMPPTCPConnection(XMPPTCPConnectionConfiguration)} constructor. * </p> * @param username * @param password * @param serviceName * @throws XmppStringprepException */ public XMPPTCPConnection(CharSequence username, String password, String serviceName) throws XmppStringprepException { this(XMPPTCPConnectionConfiguration.builder().setUsernameAndPassword(username, password).setXmppDomain( JidCreate.domainBareFrom(serviceName)).build()); }