use of org.jivesoftware.smackx.carbons.CarbonManager in project Spark by igniterealtime.
the class LoginUIPanel method login.
/**
* Login to the specified server using username, password, and workgroup.
* Handles error representation as well as logging.
*
* @return true if login was successful, false otherwise
*/
private boolean login() {
localPref = SettingsManager.getLocalPreferences();
localPref.setLoginAsInvisible(cbLoginInvisible.isSelected());
localPref.setLoginAnonymously(cbAnonymous.isSelected());
if (localPref.isDebuggerEnabled()) {
SmackConfiguration.DEBUG = true;
}
SmackConfiguration.setDefaultReplyTimeout(localPref.getTimeOut() * 1000);
try {
// TODO: SPARK-2140 - add support to Spark for stream management. Challenges expected around reconnection logic!
XMPPTCPConnection.setUseStreamManagementDefault(false);
connection = new XMPPTCPConnection(retrieveConnectionConfiguration());
connection.setParsingExceptionCallback(new ExceptionLoggingCallback());
// If we want to launch the Smack debugger, we have to check if we are on the dispatch thread, because Smack will create an UI.
if (localPref.isDebuggerEnabled() && !EventQueue.isDispatchThread()) {
// Exception handling should be no different from the regular flow.
final Exception[] exception = new Exception[1];
EventQueue.invokeAndWait(() -> {
try {
connection.connect();
} catch (IOException | SmackException | XMPPException | InterruptedException e) {
exception[0] = e;
}
});
if (exception[0] != null) {
throw exception[0];
}
} else {
connection.connect();
}
if (localPref.isLoginAnonymously() && !localPref.isSSOEnabled()) {
// ConnectionConfiguration.performSaslAnonymousAuthentication() used earlier in connection configuration builder,
// so now we can just login()
connection.login();
} else {
String resource = localPref.getResource();
if (Default.getBoolean(Default.USE_HOSTNAME_AS_RESOURCE) || localPref.isUseHostnameAsResource()) {
try {
resource = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
Log.warning("Cannot set hostname as resource - unable to retrieve hostname.", e);
}
} else if (Default.getBoolean(Default.USE_VERSION_AS_RESOURCE) || localPref.isUseVersionAsResource()) {
resource = JiveInfo.getName() + " " + JiveInfo.getVersion();
}
Resourcepart resourcepart = Resourcepart.from(modifyWildcards(resource).trim());
connection.login(getLoginUsername(), getLoginPassword(), resourcepart);
}
final SessionManager sessionManager = SparkManager.getSessionManager();
sessionManager.setServerAddress(connection.getXMPPServiceDomain());
sessionManager.initializeSession(connection, getLoginUsername(), getLoginPassword());
sessionManager.setJID(connection.getUser());
final ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(connection);
reconnectionManager.setFixedDelay(localPref.getReconnectDelay());
reconnectionManager.setReconnectionPolicy(ReconnectionManager.ReconnectionPolicy.FIXED_DELAY);
reconnectionManager.enableAutomaticReconnection();
final CarbonManager carbonManager = CarbonManager.getInstanceFor(connection);
if (carbonManager.isSupportedByServer()) {
carbonManager.enableCarbons();
}
} catch (Exception xee) {
Log.error("Exception in Login:", xee);
final String errorMessage;
if (localPref.isSSOEnabled()) {
errorMessage = Res.getString("title.advanced.connection.sso.unable");
} else if (xee.getMessage() != null && xee.getMessage().contains("not-authorized")) {
errorMessage = Res.getString("message.invalid.username.password");
} else if (xee.getMessage() != null && (xee.getMessage().contains("java.net.UnknownHostException:") || xee.getMessage().contains("Network is unreachable") || xee.getMessage().contains("java.net.ConnectException: Connection refused:"))) {
errorMessage = Res.getString("message.server.unavailable");
} else if (xee.getMessage() != null && xee.getMessage().contains("Hostname verification of certificate failed")) {
errorMessage = Res.getString("message.cert.hostname.verification.failed");
} else if (xee.getMessage() != null && xee.getMessage().contains("unable to find valid certification path to requested target")) {
errorMessage = Res.getString("message.cert.verification.failed");
} else if (xee.getMessage() != null && xee.getMessage().contains("StanzaError: conflict")) {
errorMessage = Res.getString("label.conflict.error");
} else if (xee instanceof SmackException) {
errorMessage = xee.getLocalizedMessage();
} else {
errorMessage = Res.getString("message.unrecoverable.error");
}
EventQueue.invokeLater(() -> {
lblProgress.setVisible(false);
// Show error dialog
UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
if (!loginDialog.isVisible()) {
loginDialog.setVisible(true);
}
if (loginDialog.isVisible()) {
if (xee.getMessage() != null && xee.getMessage().contains("Self Signed certificate")) {
// Handle specific case: if server certificate is self-signed, but self-signed certs are not allowed, show a popup allowing the user to override.
// Prompt user if they'd like to add the failed chain to the trust store.
final Object[] options = { Res.getString("yes"), Res.getString("no") };
final int userChoice = JOptionPane.showOptionDialog(this, Res.getString("dialog.certificate.ask.allow.self-signed"), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (userChoice == JOptionPane.YES_OPTION) {
// Toggle the preference.
localPref.setAcceptSelfSigned(true);
SettingsManager.saveSettings();
// Attempt to login again.
validateLogin();
}
} else {
final X509Certificate[] lastFailedChain = SparkTrustManager.getLastFailedChain();
final SparkTrustManager sparkTrustManager = (SparkTrustManager) SparkTrustManager.getTrustManagerList()[0];
// Handle specific case: if path validation failed because of an unrecognized CA, show popup allowing the user to add the certificate.
if (lastFailedChain != null && ((xee.getMessage() != null && xee.getMessage().contains("Certificate not in the TrustStore")) || !sparkTrustManager.containsTrustAnchorFor(lastFailedChain))) {
// Prompt user if they'd like to add the failed chain to the trust store.
final CertificateModel certModel = new CertificateModel(lastFailedChain[0]);
final Object[] options = { Res.getString("yes"), Res.getString("no") };
final int userChoice = JOptionPane.showOptionDialog(this, new UnrecognizedServerCertificatePanel(certModel), Res.getString("title.certificate"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]);
if (userChoice == JOptionPane.YES_OPTION) {
// Add the certificate chain to the truststore.
sparkTrustManager.addChain(lastFailedChain);
// Attempt to login again.
validateLogin();
}
} else {
// For anything else, show a generic error dialog.
MessageDialog.showErrorDialog(loginDialog, errorMessage, xee);
}
}
}
});
setEnabled(true);
return false;
}
// Since the connection and workgroup are valid. Add a ConnectionListener
connection.addConnectionListener(SparkManager.getSessionManager());
// Initialize chat state notification mechanism in smack
ChatStateManager.getInstance(SparkManager.getConnection());
// Persist information
localPref.setLastUsername(getLoginUsername());
// Check to see if the password should be saved or cleared from file.
if (cbSavePassword.isSelected()) {
try {
localPref.setPasswordForUser(getBareJid(), getPassword());
} catch (Exception e) {
Log.error("Error encrypting password.", e);
}
} else {
try {
// clearPasswordForUser(getBareJid());
localPref.clearPasswordForAllUsers();
} catch (Exception e) {
Log.debug("Unable to clear saved password..." + e);
}
}
localPref.setSavePassword(cbSavePassword.isSelected());
localPref.setAutoLogin(cbAutoLogin.isSelected());
localPref.setServer(tfDomain.getText());
SettingsManager.saveSettings();
return true;
}
use of org.jivesoftware.smackx.carbons.CarbonManager in project Smack by igniterealtime.
the class OmemoManager method resumeStanzaAndPEPListeners.
/**
* Register stanza listeners needed for OMEMO.
* This method is called automatically in the constructor and should only be used to restore the previous state
* after {@link #stopStanzaAndPEPListeners()} was called.
*/
public void resumeStanzaAndPEPListeners() {
CarbonManager carbonManager = CarbonManager.getInstanceFor(connection());
// Remove listeners to avoid them getting added twice
connection().removeAsyncStanzaListener(this::internalOmemoMessageStanzaListener);
carbonManager.removeCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
// Add listeners
pepManager.addPepEventListener(OmemoConstants.PEP_NODE_DEVICE_LIST, OmemoDeviceListElement.class, pepOmemoDeviceListEventListener);
connection().addAsyncStanzaListener(this::internalOmemoMessageStanzaListener, OmemoManager::isOmemoMessage);
carbonManager.addCarbonCopyReceivedListener(this::internalOmemoCarbonCopyListener);
}
Aggregations