conversations-classic/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java

1831 lines
67 KiB
Java
Raw Normal View History

2014-02-28 17:46:01 +00:00
package eu.siacs.conversations.xmpp;
import android.content.Context;
2015-10-11 11:11:50 +00:00
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
2014-11-03 09:03:45 +00:00
import android.os.SystemClock;
import android.security.KeyChain;
2015-10-11 11:11:50 +00:00
import android.util.Base64;
2014-11-03 09:03:45 +00:00
import android.util.Log;
import android.util.Pair;
2014-11-03 09:03:45 +00:00
import android.util.SparseArray;
import org.xmlpull.v1.XmlPullParserException;
2015-10-11 11:11:50 +00:00
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.IDN;
import java.net.InetAddress;
2014-10-27 20:48:25 +00:00
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
2015-10-11 11:11:50 +00:00
import java.net.URL;
2017-01-12 20:26:58 +00:00
import java.net.UnknownHostException;
2014-03-06 19:03:35 +00:00
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
2014-03-15 03:59:18 +00:00
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
2015-08-06 12:54:37 +00:00
import java.util.Iterator;
2014-02-09 13:10:52 +00:00
import java.util.List;
import java.util.Map.Entry;
2018-03-18 09:30:15 +00:00
import java.util.Set;
2018-01-20 20:57:09 +00:00
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import javax.net.ssl.KeyManager;
2014-03-06 19:03:35 +00:00
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509KeyManager;
2014-03-06 19:03:35 +00:00
import javax.net.ssl.X509TrustManager;
2014-08-31 14:28:21 +00:00
import eu.siacs.conversations.Config;
2018-02-27 19:33:21 +00:00
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.DomainHostnameVerifier;
import eu.siacs.conversations.crypto.XmppDomainVerifier;
import eu.siacs.conversations.crypto.axolotl.AxolotlService;
2016-08-07 14:46:01 +00:00
import eu.siacs.conversations.crypto.sasl.Anonymous;
2014-11-12 15:15:38 +00:00
import eu.siacs.conversations.crypto.sasl.DigestMd5;
import eu.siacs.conversations.crypto.sasl.External;
2014-11-12 15:15:38 +00:00
import eu.siacs.conversations.crypto.sasl.Plain;
import eu.siacs.conversations.crypto.sasl.SaslMechanism;
import eu.siacs.conversations.crypto.sasl.ScramSha1;
2017-01-12 20:26:58 +00:00
import eu.siacs.conversations.crypto.sasl.ScramSha256;
2014-02-28 17:46:01 +00:00
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.entities.ServiceDiscoveryResult;
import eu.siacs.conversations.generator.IqGenerator;
import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.services.MemorizingTrustManager;
import eu.siacs.conversations.services.NotificationService;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
2017-06-21 21:28:01 +00:00
import eu.siacs.conversations.utils.IP;
import eu.siacs.conversations.utils.Patterns;
2017-06-21 21:28:01 +00:00
import eu.siacs.conversations.utils.Resolver;
import eu.siacs.conversations.utils.SSLSocketHelper;
import eu.siacs.conversations.utils.SocksSocketFactory;
2014-02-28 17:46:01 +00:00
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Tag;
import eu.siacs.conversations.xml.TagWriter;
import eu.siacs.conversations.xml.XmlReader;
2017-03-01 12:01:46 +00:00
import eu.siacs.conversations.xml.Namespace;
2015-10-11 11:11:50 +00:00
import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.forms.Field;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
2015-08-13 16:25:10 +00:00
import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
2014-03-10 18:22:13 +00:00
import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
2014-08-26 15:43:44 +00:00
import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
2014-03-10 18:22:13 +00:00
import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
2018-03-05 17:30:40 +00:00
import rocks.xmpp.addr.Jid;
public class XmppConnection implements Runnable {
private static final int PACKET_IQ = 0;
private static final int PACKET_MESSAGE = 1;
private static final int PACKET_PRESENCE = 2;
2018-02-27 19:33:21 +00:00
public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) {
account.setOption(Account.OPTION_REGISTER, false);
throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
} else {
final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
"The password is too weak",
"Please use a longer password.");
Element error = packet.findChild("error");
Account.State state = Account.State.REGISTRATION_FAILED;
if (error != null) {
if (error.hasChild("conflict")) {
state = Account.State.REGISTRATION_CONFLICT;
} else if (error.hasChild("resource-constraint")
&& "wait".equals(error.getAttribute("type"))) {
state = Account.State.REGISTRATION_PLEASE_WAIT;
} else if (error.hasChild("not-acceptable")
&& PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
}
}
throw new StateChangingError(state);
}
}
};
protected final Account account;
2018-02-27 19:33:21 +00:00
private final Features features = new Features(this);
private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
2018-03-18 09:30:15 +00:00
private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
2018-02-27 19:33:21 +00:00
private final XmppConnectionService mXmppConnectionService;
private Socket socket;
private XmlReader tagReader;
2017-02-17 09:26:42 +00:00
private TagWriter tagWriter = new TagWriter();
private boolean shouldAuthenticate = true;
private boolean inSmacksSession = false;
private boolean isBound = false;
private Element streamFeatures;
2014-03-10 18:22:13 +00:00
private String streamId = null;
2014-04-05 10:08:35 +00:00
private int smVersion = 3;
2014-03-10 18:22:13 +00:00
private int stanzasReceived = 0;
private int stanzasSent = 0;
private long lastPacketReceived = 0;
private long lastPingSent = 0;
private long lastConnect = 0;
private long lastSessionStarted = 0;
2015-12-15 18:14:38 +00:00
private long lastDiscoStarted = 0;
private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
private boolean mInteractive = false;
2014-05-18 09:25:04 +00:00
private int attempt = 0;
2014-02-01 14:07:20 +00:00
private OnPresencePacketReceived presenceListener = null;
private OnJinglePacketReceived jingleListener = null;
2014-02-01 14:07:20 +00:00
private OnIqPacketReceived unregisteredIqListener = null;
private OnMessagePacketReceived messageListener = null;
private OnStatusChanged statusListener = null;
private OnBindListener bindListener = null;
2014-08-26 14:52:42 +00:00
private OnMessageAcknowledged acknowledgedListener = null;
private SaslMechanism saslMechanism;
private URL redirectionUrl = null;
private String verifiedHostname = null;
2018-01-20 20:57:09 +00:00
private Thread mThread;
private CountDownLatch mStreamCountDownLatch;
2014-11-12 15:15:38 +00:00
public XmppConnection(final Account account, final XmppConnectionService service) {
this.account = account;
2018-03-05 17:30:40 +00:00
final String tag = account.getJid().asBareJid().toString();
mXmppConnectionService = service;
}
2014-03-06 14:11:56 +00:00
protected void changeStatus(final Account.State nextStatus) {
synchronized (this) {
if (Thread.currentThread().isInterrupted()) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
2014-03-13 16:29:22 +00:00
return;
2014-05-18 09:25:04 +00:00
}
if (account.getStatus() != nextStatus) {
if ((nextStatus == Account.State.OFFLINE)
&& (account.getStatus() != Account.State.CONNECTING)
&& (account.getStatus() != Account.State.ONLINE)
&& (account.getStatus() != Account.State.DISABLED)) {
return;
}
if (nextStatus == Account.State.ONLINE) {
this.attempt = 0;
}
account.setStatus(nextStatus);
} else {
return;
2014-03-11 15:27:33 +00:00
}
2014-03-06 02:57:29 +00:00
}
if (statusListener != null) {
statusListener.onStatusChanged(account);
}
2014-03-06 02:57:29 +00:00
}
public void prepareNewConnection() {
this.lastConnect = SystemClock.elapsedRealtime();
this.lastPingSent = SystemClock.elapsedRealtime();
this.lastDiscoStarted = Long.MAX_VALUE;
this.mWaitingForSmCatchup.set(false);
this.changeStatus(Account.State.CONNECTING);
}
public boolean isWaitingForSmCatchup() {
return mWaitingForSmCatchup.get();
}
public void incrementSmCatchupMessageCounter() {
this.mSmCatchupMessageCounter.incrementAndGet();
}
protected void connect() {
if (mXmppConnectionService.areMessagesInitialized()) {
mXmppConnectionService.resetSendingToWaiting(account);
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
features.encryptionEnabled = false;
inSmacksSession = false;
isBound = false;
2014-05-18 09:25:04 +00:00
this.attempt++;
this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
try {
Socket localSocket;
shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
2014-11-15 16:09:02 +00:00
this.changeStatus(Account.State.CONNECTING);
2015-11-29 14:44:45 +00:00
final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
2015-11-29 14:44:45 +00:00
if (useTor) {
String destination;
if (account.getHostname().isEmpty()) {
destination = account.getServer().toString();
2015-11-29 14:44:45 +00:00
} else {
destination = account.getHostname();
this.verifiedHostname = destination;
2015-11-29 14:44:45 +00:00
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor");
localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
try {
startXmpp(localSocket);
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} else if (extended && !account.getHostname().isEmpty()) {
this.verifiedHostname = account.getHostname();
try {
InetSocketAddress address = new InetSocketAddress(this.verifiedHostname, account.getPort());
features.encryptionEnabled = address.getPort() == 5223;
if (features.encryptionEnabled) {
try {
final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
localSocket = tlsFactoryVerifier.factory.createSocket();
localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
final SSLSession session = ((SSLSocket) localSocket).getSession();
2018-03-05 17:30:40 +00:00
final String domain = account.getJid().getDomain();
if (!tlsFactoryVerifier.verifier.verify(domain, this.verifiedHostname, session)) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.TLS_ERROR);
}
} catch (KeyManagementException e) {
throw new StateChangingException(Account.State.TLS_ERROR);
}
} else {
localSocket = new Socket();
localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
}
} catch (IOException | IllegalArgumentException e) {
throw new UnknownHostException();
}
try {
startXmpp(localSocket);
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} else if (IP.matches(account.getServer())) {
localSocket = new Socket();
try {
localSocket.connect(new InetSocketAddress(account.getServer(), 5222), Config.SOCKET_TIMEOUT * 1000);
} catch (IOException e) {
throw new UnknownHostException();
}
try {
startXmpp(localSocket);
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return;
} catch (Exception e) {
throw new IOException(e.getMessage());
}
} else {
2018-03-05 17:30:40 +00:00
final String domain = account.getJid().getDomain();
List<Resolver.Result> results = Resolver.resolve(account.getJid().getDomain());
2018-01-21 19:41:30 +00:00
Resolver.Result storedBackupResult;
if (!Thread.currentThread().isInterrupted()) {
storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
if (storedBackupResult != null && !results.contains(storedBackupResult)) {
results.add(storedBackupResult);
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
2018-01-21 19:41:30 +00:00
}
} else {
storedBackupResult = null;
}
2017-06-21 21:28:01 +00:00
for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
final Resolver.Result result = iterator.next();
if (Thread.currentThread().isInterrupted()) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
return;
}
try {
// if tls is true, encryption is implied and must not be started
2017-06-21 21:28:01 +00:00
features.encryptionEnabled = result.isDirectTls();
verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
final InetSocketAddress addr;
2017-06-21 21:28:01 +00:00
if (result.getIp() != null) {
addr = new InetSocketAddress(result.getIp(), result.getPort());
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
2017-06-21 21:28:01 +00:00
+ ": using values from dns " + result.getHostname().toString()
2017-06-21 22:09:59 +00:00
+ "/" + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
} else {
addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": using values from dns "
2017-06-21 21:28:01 +00:00
+ result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
}
if (!features.encryptionEnabled) {
localSocket = new Socket();
localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
} else {
final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
localSocket = tlsFactoryVerifier.factory.createSocket();
if (localSocket == null) {
throw new IOException("could not initialize ssl socket");
}
SSLSocketHelper.setSecurity((SSLSocket) localSocket);
SSLSocketHelper.setSNIHost(tlsFactoryVerifier.factory, (SSLSocket) localSocket, account.getServer());
SSLSocketHelper.setAlpnProtocol(tlsFactoryVerifier.factory, (SSLSocket) localSocket, "xmpp-client");
localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
if (!tlsFactoryVerifier.verifier.verify(account.getServer(), verifiedHostname, ((SSLSocket) localSocket).getSession())) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
if (!iterator.hasNext()) {
throw new StateChangingException(Account.State.TLS_ERROR);
}
}
}
2016-11-19 11:20:31 +00:00
if (startXmpp(localSocket)) {
2018-01-21 19:41:30 +00:00
if (!result.equals(storedBackupResult)) {
mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
}
break; // successfully connected to server that speaks xmpp
2016-11-19 11:20:31 +00:00
} else {
localSocket.close();
}
2017-05-05 07:33:05 +00:00
} catch (final StateChangingException e) {
throw e;
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
return;
} catch (final Throwable e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
if (!iterator.hasNext()) {
throw new UnknownHostException();
}
2014-10-16 21:31:48 +00:00
}
}
}
processStream();
} catch (final SecurityException e) {
this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
} catch (final StateChangingException e) {
2017-05-05 07:33:05 +00:00
this.changeStatus(e.state);
} catch (final Resolver.NetworkIsUnreachableException e) {
this.changeStatus(Account.State.NETWORK_IS_UNREACHABLE);
} catch (final UnknownHostException | ConnectException e) {
this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
2014-11-15 16:09:02 +00:00
this.changeStatus(Account.State.OFFLINE);
this.attempt = Math.max(0, this.attempt - 1);
} finally {
if (!Thread.currentThread().isInterrupted()) {
forceCloseSocket();
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
}
}
}
/**
* Starts xmpp protocol, call after connecting to socket
*
* @return true if server returns with valid xmpp, false otherwise
*/
private boolean startXmpp(Socket socket) throws Exception {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException();
}
this.socket = socket;
2018-01-21 11:26:16 +00:00
tagReader = new XmlReader();
2017-02-17 09:26:42 +00:00
if (tagWriter != null) {
tagWriter.forceClose();
}
tagWriter = new TagWriter();
tagWriter.setOutputStream(socket.getOutputStream());
tagReader.setInputStream(socket.getInputStream());
tagWriter.beginDocument();
sendStartStream();
final Tag tag = tagReader.readTag();
return tag != null && tag.isStart("stream");
}
private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
final SSLContext sc = SSLSocketHelper.getSSLContext();
MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
KeyManager[] keyManager;
if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
keyManager = new KeyManager[]{new MyKeyManager()};
} else {
keyManager = null;
}
2018-03-05 17:30:40 +00:00
String domain = account.getJid().getDomain();
2016-12-05 20:52:44 +00:00
sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
final SSLSocketFactory factory = sc.getSocketFactory();
final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
return new TlsFactoryVerifier(factory, verifier);
}
@Override
public void run() {
synchronized (this) {
2018-01-20 20:57:09 +00:00
this.mThread = Thread.currentThread();
if (this.mThread.isInterrupted()) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
return;
}
forceCloseSocket();
}
connect();
}
2015-10-13 21:34:09 +00:00
private void processStream() throws XmlPullParserException, IOException, NoSuchAlgorithmException {
2018-01-20 20:57:09 +00:00
final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
this.mStreamCountDownLatch = streamCountDownLatch;
Tag nextTag = tagReader.readTag();
while (nextTag != null && !nextTag.isEnd("stream")) {
if (nextTag.isStart("error")) {
processStreamError(nextTag);
} else if (nextTag.isStart("features")) {
processStreamFeatures(nextTag);
} else if (nextTag.isStart("proceed")) {
switchOverToTls(nextTag);
} else if (nextTag.isStart("success")) {
final String challenge = tagReader.readElement(nextTag).getContent();
try {
saslMechanism.getResponse(challenge);
} catch (final SaslMechanism.AuthenticationException e) {
Log.e(Config.LOGTAG, String.valueOf(e));
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.UNAUTHORIZED);
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
account.setKey(Account.PINNED_MECHANISM_KEY,
String.valueOf(saslMechanism.getPriority()));
tagReader.reset();
sendStartStream();
final Tag tag = tagReader.readTag();
if (tag != null && tag.isStart("stream")) {
processStream();
} else {
throw new IOException("server didn't restart stream after successful auth");
}
break;
} else if (nextTag.isStart("failure")) {
2016-08-16 08:39:59 +00:00
final Element failure = tagReader.readElement(nextTag);
if (Namespace.SASL.equals(failure.getNamespace())) {
final String text = failure.findChildContent("text");
if (failure.hasChild("account-disabled") && text != null) {
Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
if (matcher.find()) {
try {
URL url = new URL(text.substring(matcher.start(), matcher.end()));
if (url.getProtocol().equals("https")) {
this.redirectionUrl = url;
throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
}
} catch (MalformedURLException e) {
throw new StateChangingException(Account.State.UNAUTHORIZED);
}
}
}
throw new StateChangingException(Account.State.UNAUTHORIZED);
} else if (Namespace.TLS.equals(failure.getNamespace())) {
throw new StateChangingException(Account.State.TLS_ERROR);
2016-08-16 08:39:59 +00:00
} else {
throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
2016-08-16 08:39:59 +00:00
}
} else if (nextTag.isStart("challenge")) {
final String challenge = tagReader.readElement(nextTag).getContent();
final Element response = new Element("response", Namespace.SASL);
try {
response.setContent(saslMechanism.getResponse(challenge));
} catch (final SaslMechanism.AuthenticationException e) {
// TODO: Send auth abort tag.
Log.e(Config.LOGTAG, e.toString());
}
tagWriter.writeElement(response);
} else if (nextTag.isStart("enabled")) {
final Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) {
this.streamId = enabled.getAttribute("id");
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
2016-05-04 08:29:29 +00:00
+ ": stream management(" + smVersion
+ ") enabled (resumable)");
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
+ ": stream management(" + smVersion + ") enabled");
}
this.stanzasReceived = 0;
this.inSmacksSession = true;
final RequestPacket r = new RequestPacket(smVersion);
tagWriter.writeStanzaAsync(r);
} else if (nextTag.isStart("resumed")) {
this.inSmacksSession = true;
this.isBound = true;
this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
lastPacketReceived = SystemClock.elapsedRealtime();
final Element resumed = tagReader.readElement(nextTag);
final String h = resumed.getAttribute("h");
try {
ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
2016-06-14 08:17:37 +00:00
synchronized (this.mStanzaQueue) {
final int serverCount = Integer.parseInt(h);
2018-02-02 15:52:40 +00:00
if (serverCount < stanzasSent) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
2016-06-14 08:17:37 +00:00
+ ": session resumed with lost packages");
stanzasSent = serverCount;
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
2016-06-14 08:17:37 +00:00
}
acknowledgeStanzaUpTo(serverCount);
for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
failedStanzas.add(mStanzaQueue.valueAt(i));
}
mStanzaQueue.clear();
}
2016-06-14 08:17:37 +00:00
Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
for (AbstractAcknowledgeableStanza packet : failedStanzas) {
if (packet instanceof MessagePacket) {
MessagePacket message = (MessagePacket) packet;
mXmppConnectionService.markMessage(account,
2018-03-05 17:30:40 +00:00
message.getTo().asBareJid(),
message.getId(),
Message.STATUS_UNSEND);
}
sendPacket(packet);
}
} catch (final NumberFormatException ignored) {
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
changeStatus(Account.State.ONLINE);
} else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag);
if (Config.EXTENDED_SM_LOGGING) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
}
final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) {
boolean accountUiNeedsRefresh = false;
synchronized (NotificationService.CATCHUP_LOCK) {
if (mWaitingForSmCatchup.compareAndSet(true, false)) {
int count = mSmCatchupMessageCounter.get();
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (" + count + ")");
accountUiNeedsRefresh = true;
if (count > 0) {
mXmppConnectionService.getNotificationService().finishBacklog(true, account);
}
}
}
if (accountUiNeedsRefresh) {
mXmppConnectionService.updateAccountUi();
}
final Element ack = tagReader.readElement(nextTag);
lastPacketReceived = SystemClock.elapsedRealtime();
try {
2016-06-14 08:17:37 +00:00
synchronized (this.mStanzaQueue) {
final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
acknowledgeStanzaUpTo(serverSequence);
}
} catch (NumberFormatException | NullPointerException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
}
} else if (nextTag.isStart("failed")) {
Element failed = tagReader.readElement(nextTag);
try {
final int serverCount = Integer.parseInt(failed.getAttribute("h"));
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
2016-06-14 08:17:37 +00:00
synchronized (this.mStanzaQueue) {
acknowledgeStanzaUpTo(serverCount);
}
} catch (NumberFormatException | NullPointerException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
}
resetStreamId();
sendBindRequest();
} else if (nextTag.isStart("iq")) {
processIq(nextTag);
} else if (nextTag.isStart("message")) {
processMessage(nextTag);
} else if (nextTag.isStart("presence")) {
processPresence(nextTag);
}
nextTag = tagReader.readTag();
}
2018-01-20 20:57:09 +00:00
if (nextTag != null && nextTag.isEnd("stream")) {
streamCountDownLatch.countDown();
}
}
2015-08-06 18:48:55 +00:00
private void acknowledgeStanzaUpTo(int serverCount) {
2018-02-02 15:52:40 +00:00
if (serverCount > stanzasSent) {
Log.e(Config.LOGTAG,"server acknowledged more stanzas than we sent. serverCount="+serverCount+", ourCount="+stanzasSent);
}
2015-08-13 16:25:10 +00:00
for (int i = 0; i < mStanzaQueue.size(); ++i) {
if (serverCount >= mStanzaQueue.keyAt(i)) {
2015-08-06 18:48:55 +00:00
if (Config.EXTENDED_SM_LOGGING) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
2015-08-06 18:48:55 +00:00
}
2015-08-13 16:25:10 +00:00
AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
if (stanza instanceof MessagePacket && acknowledgedListener != null) {
MessagePacket packet = (MessagePacket) stanza;
acknowledgedListener.onMessageAcknowledged(account, packet.getId());
2015-08-06 18:48:55 +00:00
}
2015-08-13 16:25:10 +00:00
mStanzaQueue.removeAt(i);
2015-08-06 18:48:55 +00:00
i--;
}
}
}
private Element processPacket(final Tag currentTag, final int packetType)
throws XmlPullParserException, IOException {
Element element;
switch (packetType) {
2014-11-03 09:03:45 +00:00
case PACKET_IQ:
element = new IqPacket();
break;
case PACKET_MESSAGE:
element = new MessagePacket();
break;
case PACKET_PRESENCE:
element = new PresencePacket();
break;
default:
return null;
}
element.setAttributes(currentTag.getAttributes());
Tag nextTag = tagReader.readTag();
2014-08-31 14:28:21 +00:00
if (nextTag == null) {
2014-05-23 08:15:58 +00:00
throw new IOException("interrupted mid tag");
}
2014-02-09 13:10:52 +00:00
while (!nextTag.isEnd(element.getName())) {
if (!nextTag.isNo()) {
final Element child = tagReader.readElement(nextTag);
final String type = currentTag.getAttribute("type");
if (packetType == PACKET_IQ
&& "jingle".equals(child.getName())
&& ("set".equalsIgnoreCase(type) || "get"
.equalsIgnoreCase(type))) {
element = new JinglePacket();
element.setAttributes(currentTag.getAttributes());
}
element.addChild(child);
}
nextTag = tagReader.readTag();
2014-08-31 14:28:21 +00:00
if (nextTag == null) {
2014-05-23 08:15:58 +00:00
throw new IOException("interrupted mid tag");
}
}
if (stanzasReceived == Integer.MAX_VALUE) {
resetStreamId();
throw new IOException("time to restart the session. cant handle >2 billion pcks");
}
if (inSmacksSession) {
++stanzasReceived;
} else if (features.sm()) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG,account.getJid().asBareJid()+": not counting stanza("+element.getClass().getSimpleName()+"). Not in smacks session.");
}
lastPacketReceived = SystemClock.elapsedRealtime();
if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
Log.d(Config.LOGTAG, "[background stanza] " + element);
}
return element;
}
private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
2014-05-21 20:22:36 +00:00
if (packet.getId() == null) {
return; // an iq packet without id is definitely invalid
}
2014-05-21 20:22:36 +00:00
if (packet instanceof JinglePacket) {
if (this.jingleListener != null) {
this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
}
} else {
OnIqPacketReceived callback = null;
2015-08-16 10:12:22 +00:00
synchronized (this.packetCallbacks) {
if (packetCallbacks.containsKey(packet.getId())) {
final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
// Packets to the server should have responses from the server
if (packetCallbackDuple.first.toServer(account)) {
if (packet.fromServer(account)) {
callback = packetCallbackDuple.second;
2015-08-16 10:12:22 +00:00
packetCallbacks.remove(packet.getId());
} else {
2018-03-05 17:30:40 +00:00
Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
2015-08-16 10:12:22 +00:00
}
} else {
if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
callback = packetCallbackDuple.second;
2015-08-16 10:12:22 +00:00
packetCallbacks.remove(packet.getId());
} else {
2018-03-05 17:30:40 +00:00
Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
2015-08-16 10:12:22 +00:00
}
}
2015-08-16 10:12:22 +00:00
} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
callback = this.unregisteredIqListener;
}
}
if (callback != null) {
2017-05-05 07:33:05 +00:00
try {
callback.onIqPacketReceived(account, packet);
} catch (StateChangingError error) {
throw new StateChangingException(error.state);
}
}
}
}
2014-02-09 13:10:52 +00:00
private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
this.messageListener.onMessagePacketReceived(account, packet);
}
2014-02-09 13:10:52 +00:00
private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
this.presenceListener.onPresencePacketReceived(account, packet);
}
2014-03-10 18:22:13 +00:00
private void sendStartTLS() throws IOException {
final Tag startTLS = Tag.empty("starttls");
startTLS.setAttribute("xmlns", Namespace.TLS);
tagWriter.writeTag(startTLS);
}
2014-12-30 00:17:11 +00:00
private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
2014-12-30 13:16:25 +00:00
tagReader.readTag();
try {
final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
2014-12-30 13:16:25 +00:00
final InetAddress address = socket == null ? null : socket.getInetAddress();
2014-12-30 00:17:11 +00:00
if (address == null) {
2014-12-30 00:17:11 +00:00
throw new IOException("could not setup ssl");
}
2014-11-03 09:03:45 +00:00
final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
2014-12-30 00:17:11 +00:00
if (sslSocket == null) {
throw new IOException("could not initialize ssl socket");
}
SSLSocketHelper.setSecurity(sslSocket);
2015-01-17 18:40:15 +00:00
if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.TLS_ERROR);
2014-12-30 00:17:11 +00:00
}
tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream();
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
features.encryptionEnabled = true;
final Tag tag = tagReader.readTag();
if (tag != null && tag.isStart("stream")) {
2015-10-13 21:34:09 +00:00
processStream();
} else {
throw new IOException("server didn't restart stream after STARTTLS");
}
2014-12-30 00:17:11 +00:00
sslSocket.close();
2014-12-30 13:16:25 +00:00
} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.TLS_ERROR);
2014-12-30 13:16:25 +00:00
}
}
2018-02-18 20:54:03 +00:00
private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
this.streamFeatures = tagReader.readElement(currentTag);
2018-02-18 20:54:03 +00:00
final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS;
final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
sendStartTLS();
} else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
2018-02-18 20:54:03 +00:00
if (isSecure) {
sendRegistryRequest();
} else {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
}
} else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
2018-02-18 20:54:03 +00:00
} else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
authenticate();
2015-08-23 15:29:31 +00:00
} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
if (Config.EXTENDED_SM_LOGGING) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
}
final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
this.mSmCatchupMessageCounter.set(0);
this.mWaitingForSmCatchup.set(true);
2014-03-10 18:22:13 +00:00
this.tagWriter.writeStanzaAsync(resume);
} else if (needsBinding) {
2018-02-18 20:54:03 +00:00
if (this.streamFeatures.hasChild("bind") && isSecure) {
sendBindRequest();
} else {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
}
2014-03-10 18:22:13 +00:00
}
}
2014-02-09 13:10:52 +00:00
private void authenticate() throws IOException {
final List<String> mechanisms = extractMechanisms(streamFeatures
.findChild("mechanisms"));
final Element auth = new Element("auth", Namespace.SASL);
if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
2017-01-12 20:26:58 +00:00
} else if (mechanisms.contains("SCRAM-SHA-256")) {
saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
} else if (mechanisms.contains("SCRAM-SHA-1")) {
saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
2018-03-05 17:30:40 +00:00
} else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
saslMechanism = new Plain(tagWriter, account);
} else if (mechanisms.contains("DIGEST-MD5")) {
saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
2016-08-07 14:46:01 +00:00
} else if (mechanisms.contains("ANONYMOUS")) {
saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
}
if (saslMechanism != null) {
final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
if (pinnedMechanism > saslMechanism.getPriority()) {
Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
") than pinned priority (" + pinnedMechanism +
"). Possible downgrade attack?");
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
}
Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
auth.setAttribute("mechanism", saslMechanism.getMechanism());
if (!saslMechanism.getClientFirstMessage().isEmpty()) {
auth.setContent(saslMechanism.getClientFirstMessage());
}
tagWriter.writeElement(auth);
} else {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
}
}
private List<String> extractMechanisms(final Element stream) {
final ArrayList<String> mechanisms = new ArrayList<>(stream
2014-05-21 20:22:36 +00:00
.getChildren().size());
for (final Element child : stream.getChildren()) {
mechanisms.add(child.getContent());
}
return mechanisms;
}
private void sendRegistryRequest() {
2014-12-30 13:16:25 +00:00
final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
register.query("jabber:iq:register");
register.setTo(Jid.of(account.getServer()));
sendUnmodifiedIqPacket(register, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
return;
}
if (packet.getType() == IqPacket.TYPE.ERROR) {
throw new StateChangingError(Account.State.REGISTRATION_FAILED);
}
final Element query = packet.query("jabber:iq:register");
if (query.hasChild("username") && (query.hasChild("password"))) {
final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
final Element username = new Element("username").setContent(account.getUsername());
final Element password = new Element("password").setContent(account.getPassword());
register1.query("jabber:iq:register").addChild(username);
register1.query().addChild(password);
register1.setFrom(account.getJid().asBareJid());
sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
} else if (query.hasChild("x", Namespace.DATA)) {
final Data data = Data.parse(query.findChild("x", Namespace.DATA));
final Element blob = query.findChild("data", "urn:xmpp:bob");
final String id = packet.getId();
InputStream is;
if (blob != null) {
try {
final String base64Blob = blob.getContent();
final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
is = new ByteArrayInputStream(strBlob);
} catch (Exception e) {
is = null;
}
} else {
try {
Field field = data.getFieldByName("url");
URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
is = url != null ? url.openStream() : null;
} catch (IOException e) {
is = null;
2015-10-11 11:11:50 +00:00
}
}
2015-10-11 11:11:50 +00:00
if (is != null) {
Bitmap captcha = BitmapFactory.decodeStream(is);
try {
if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
return;
}
} catch (Exception e) {
throw new StateChangingError(Account.State.REGISTRATION_FAILED);
2015-10-11 11:11:50 +00:00
}
}
throw new StateChangingError(Account.State.REGISTRATION_FAILED);
} else if (query.hasChild("instructions") || query.hasChild("x",Namespace.OOB)) {
final String instructions = query.findChildContent("instructions");
final Element oob = query.findChild("x", Namespace.OOB);
final String url = oob == null ? null : oob.findChildContent("url");
if (url != null) {
setAccountCreationFailed(url);
} else if (instructions != null) {
Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
if (matcher.find()) {
setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
}
}
throw new StateChangingError(Account.State.REGISTRATION_FAILED);
}
},true);
}
private void setAccountCreationFailed(String url) {
if (url != null) {
try {
this.redirectionUrl = new URL(url);
if (this.redirectionUrl.getProtocol().equals("https")) {
throw new StateChangingError(Account.State.REGISTRATION_WEB);
}
} catch (MalformedURLException e) {
//fall through
}
}
throw new StateChangingError(Account.State.REGISTRATION_FAILED);
}
public URL getRedirectionUrl() {
return this.redirectionUrl;
2015-10-11 11:11:50 +00:00
}
public void resetEverything() {
2016-11-18 12:47:39 +00:00
resetAttemptCount(true);
resetStreamId();
clearIqCallbacks();
2018-02-02 15:52:40 +00:00
this.stanzasSent = 0;
mStanzaQueue.clear();
this.redirectionUrl = null;
synchronized (this.disco) {
disco.clear();
}
}
private void sendBindRequest() {
try {
mXmppConnectionService.restoredFromDatabaseLatch.await();
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG,account.getJid().asBareJid()+": interrupted while waiting for DB restore during bind");
return;
2015-02-12 17:53:00 +00:00
}
2015-08-06 12:54:37 +00:00
clearIqCallbacks();
2018-02-27 19:33:21 +00:00
if (account.getJid().isBareJid()) {
account.setResource(this.createNewResource());
} else {
fixResource(mXmppConnectionService, account);
2018-02-27 19:33:21 +00:00
}
2014-12-30 13:16:25 +00:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
2018-02-27 19:33:21 +00:00
this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
return;
}
final Element bind = packet.findChild("bind");
if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
isBound = true;
final Element jid = bind.findChild("jid");
if (jid != null && jid.getContent() != null) {
try {
2018-03-11 17:32:16 +00:00
Jid assignedJid = Jid.ofEscaped(jid.getContent());
2018-03-05 17:30:40 +00:00
if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
Log.d(Config.LOGTAG,account.getJid().asBareJid()+": server tried to re-assign domain to "+assignedJid.getDomain());
2018-02-27 19:33:21 +00:00
throw new StateChangingError(Account.State.BIND_FAILURE);
2014-07-26 13:44:32 +00:00
}
2018-02-27 19:33:21 +00:00
if (account.setJid(assignedJid)) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
2018-02-27 19:33:21 +00:00
mXmppConnectionService.databaseBackend.updateAccount(account);
}
if (streamFeatures.hasChild("session")
&& !streamFeatures.findChild("session").hasChild("optional")) {
sendStartSession();
} else {
sendPostBindInitialization();
}
return;
2018-03-05 17:30:40 +00:00
} catch (final IllegalArgumentException e) {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
2014-07-26 13:44:32 +00:00
}
} else {
2018-02-27 19:33:21 +00:00
Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
}
2018-02-27 19:33:21 +00:00
} else {
Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
2014-02-09 13:10:52 +00:00
}
2018-02-27 19:33:21 +00:00
final Element error = packet.findChild("error");
if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
account.setResource(createNewResource());
}
throw new StateChangingError(Account.State.BIND_FAILURE);
},true);
}
2015-08-06 12:54:37 +00:00
private void clearIqCallbacks() {
final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
2015-08-16 10:12:22 +00:00
synchronized (this.packetCallbacks) {
if (this.packetCallbacks.size() == 0) {
return;
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
2015-08-16 10:12:22 +00:00
while (iterator.hasNext()) {
Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
callbacks.add(entry.second);
2015-08-16 10:12:22 +00:00
iterator.remove();
}
2015-08-06 12:54:37 +00:00
}
for (OnIqPacketReceived callback : callbacks) {
try {
callback.onIqPacketReceived(account, failurePacket);
} catch (StateChangingError error) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
//ignore
}
2015-08-06 12:54:37 +00:00
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
2015-08-06 12:54:37 +00:00
}
2015-12-15 18:14:38 +00:00
public void sendDiscoTimeout() {
if (mWaitForDisco.compareAndSet(true, false)) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
finalizeBind();
2015-12-15 18:14:38 +00:00
}
}
private void sendStartSession() {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
2015-08-06 18:48:55 +00:00
startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) {
sendPostBindInitialization();
} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
throw new StateChangingError(Account.State.SESSION_FAILURE);
}
},true);
}
private void sendPostBindInitialization() {
smVersion = 0;
if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
smVersion = 3;
} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
smVersion = 2;
}
if (smVersion != 0) {
2016-06-14 08:17:37 +00:00
synchronized (this.mStanzaQueue) {
final EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable);
2016-06-14 08:17:37 +00:00
stanzasSent = 0;
mStanzaQueue.clear();
}
}
features.carbonsEnabled = false;
features.blockListRequested = false;
2015-10-19 21:03:19 +00:00
synchronized (this.disco) {
this.disco.clear();
}
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
mPendingServiceDiscoveries.set(0);
2018-03-05 17:30:40 +00:00
if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
mWaitForDisco.set(false);
} else {
mWaitForDisco.set(true);
}
2015-12-15 18:14:38 +00:00
lastDiscoStarted = SystemClock.elapsedRealtime();
mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2016-02-03 16:19:05 +00:00
Element caps = streamFeatures.findChild("c");
final String hash = caps == null ? null : caps.getAttribute("hash");
final String ver = caps == null ? null : caps.getAttribute("ver");
ServiceDiscoveryResult discoveryResult = null;
if (hash != null && ver != null) {
discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2016-02-03 16:19:05 +00:00
}
final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
if (requestDiscoItemsFirst) {
sendServiceDiscoveryItems(Jid.of(account.getServer()));
}
2016-02-03 16:19:05 +00:00
if (discoveryResult == null) {
sendServiceDiscoveryInfo(Jid.of(account.getServer()));
2016-02-03 16:19:05 +00:00
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
disco.put(Jid.of(account.getServer()), discoveryResult);
2016-02-03 16:19:05 +00:00
}
2018-03-05 17:30:40 +00:00
sendServiceDiscoveryInfo(account.getJid().asBareJid());
if (!requestDiscoItemsFirst) {
sendServiceDiscoveryItems(Jid.of(account.getServer()));
}
if (!mWaitForDisco.get()) {
finalizeBind();
}
2015-08-25 09:11:32 +00:00
this.lastSessionStarted = SystemClock.elapsedRealtime();
2014-02-09 13:10:52 +00:00
}
private void sendServiceDiscoveryInfo(final Jid jid) {
mPendingServiceDiscoveries.incrementAndGet();
2015-10-19 21:03:19 +00:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setTo(jid);
iq.query("http://jabber.org/protocol/disco#info");
this.sendIqPacket(iq, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) {
boolean advancedStreamFeaturesLoaded;
synchronized (XmppConnection.this.disco) {
ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
if (jid.equals(Jid.of(account.getServer()))) {
mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
2014-11-15 16:24:06 +00:00
}
disco.put(jid, result);
advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
&& disco.containsKey(account.getJid().asBareJid());
2014-02-09 13:10:52 +00:00
}
if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
enableAdvancedStreamFeatures();
}
} else {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
}
if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
if (mPendingServiceDiscoveries.decrementAndGet() == 0
&& mWaitForDisco.compareAndSet(true, false)) {
finalizeBind();
}
2015-10-19 21:03:19 +00:00
}
});
2014-02-09 13:10:52 +00:00
}
2014-05-21 20:22:36 +00:00
private void finalizeBind() {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
if (bindListener != null) {
bindListener.onBind(account);
}
changeStatus(Account.State.ONLINE);
}
private void enableAdvancedStreamFeatures() {
if (getFeatures().carbons() && !features.carbonsEnabled) {
sendEnableCarbons();
}
if (getFeatures().blocking() && !features.blockListRequested) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
}
for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
listener.onAdvancedStreamFeaturesAvailable(account);
}
}
2014-05-21 20:22:36 +00:00
private void sendServiceDiscoveryItems(final Jid server) {
mPendingServiceDiscoveries.incrementAndGet();
2014-12-30 13:16:25 +00:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2018-03-05 17:30:40 +00:00
iq.setTo(Jid.ofDomain(server.getDomain()));
2014-03-15 03:59:18 +00:00
iq.query("http://jabber.org/protocol/disco#items");
this.sendIqPacket(iq, (account, packet) -> {
if (packet.getType() == IqPacket.TYPE.RESULT) {
HashSet<Jid> items = new HashSet<Jid>();
final List<Element> elements = packet.query().getChildren();
for (final Element element : elements) {
if (element.getName().equals("item")) {
final Jid jid = element.getAttributeAsJid("jid");
if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
items.add(jid);
}
}
}
for (Jid jid : items) {
sendServiceDiscoveryInfo(jid);
}
} else {
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
}
if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
if (mPendingServiceDiscoveries.decrementAndGet() == 0
&& mWaitForDisco.compareAndSet(true, false)) {
finalizeBind();
}
2014-03-15 03:59:18 +00:00
}
});
}
2014-03-06 14:11:56 +00:00
2014-02-09 13:10:52 +00:00
private void sendEnableCarbons() {
2014-12-30 13:16:25 +00:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2014-05-21 20:22:36 +00:00
iq.addChild("enable", "urn:xmpp:carbons:2");
2014-02-09 13:10:52 +00:00
this.sendIqPacket(iq, new OnIqPacketReceived() {
2014-03-06 14:11:56 +00:00
2014-02-09 13:10:52 +00:00
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
2014-02-09 13:10:52 +00:00
if (!packet.hasChild("error")) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid()
2014-03-06 14:11:56 +00:00
+ ": successfully enabled carbons");
features.carbonsEnabled = true;
2014-02-09 13:10:52 +00:00
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid()
2014-03-06 14:11:56 +00:00
+ ": error enableing carbons " + packet.toString());
2014-02-09 13:10:52 +00:00
}
}
});
}
2018-02-27 19:33:21 +00:00
private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
final Element streamError = tagReader.readElement(currentTag);
if (streamError == null) {
return;
}
if (streamError.hasChild("conflict")) {
2018-02-27 19:33:21 +00:00
account.setResource(createNewResource());
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
throw new IOException();
} else if (streamError.hasChild("host-unknown")) {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.HOST_UNKNOWN);
} else if (streamError.hasChild("policy-violation")) {
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.POLICY_VIOLATION);
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
2017-05-05 07:33:05 +00:00
throw new StateChangingException(Account.State.STREAM_ERROR);
2014-09-03 12:57:40 +00:00
}
}
2014-03-10 18:22:13 +00:00
private void sendStartStream() throws IOException {
final Tag stream = Tag.start("stream:stream");
stream.setAttribute("to", account.getServer());
stream.setAttribute("version", "1.0");
stream.setAttribute("xml:lang", "en");
stream.setAttribute("xmlns", "jabber:client");
stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
tagWriter.writeTag(stream);
}
2018-02-27 19:33:21 +00:00
private String createNewResource() {
return mXmppConnectionService.getString(R.string.app_name)+'.'+nextRandomId(true);
}
private static void fixResource(Context context, Account account) {
String resource = account.getResource();
int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
int randomPartLength = 4; // 3 bytes
if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
if (validBase64(resource.substring(fixedPartLength,fixedPartLength + randomPartLength))) {
account.setResource(resource.substring(0,fixedPartLength + randomPartLength));
}
}
}
private static boolean validBase64(String input) {
try {
return Base64.decode(input, Base64.URL_SAFE).length == 3;
} catch (Throwable throwable) {
return false;
}
}
private String nextRandomId() {
2018-02-27 19:33:21 +00:00
return nextRandomId(false);
}
private String nextRandomId(boolean s) {
return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
}
2014-02-09 13:10:52 +00:00
2015-12-15 18:14:38 +00:00
public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
packet.setFrom(account.getJid());
return this.sendUnmodifiedIqPacket(packet, callback, false);
}
2014-05-21 20:22:36 +00:00
public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2014-05-21 20:22:36 +00:00
if (packet.getId() == null) {
packet.setAttribute("id", nextRandomId());
}
if (callback != null) {
2015-08-16 10:12:22 +00:00
synchronized (this.packetCallbacks) {
packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
}
}
this.sendPacket(packet,force);
2015-12-15 18:14:38 +00:00
return packet.getId();
}
2014-02-09 13:10:52 +00:00
public void sendMessagePacket(final MessagePacket packet) {
this.sendPacket(packet);
2014-03-03 04:01:02 +00:00
}
2014-03-06 14:11:56 +00:00
public void sendPresencePacket(final PresencePacket packet) {
this.sendPacket(packet);
2014-03-03 04:01:02 +00:00
}
2014-08-31 14:28:21 +00:00
private synchronized void sendPacket(final AbstractStanza packet) {
sendPacket(packet,false);
}
private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
if (stanzasSent == Integer.MAX_VALUE) {
resetStreamId();
disconnect(true);
return;
}
synchronized (this.mStanzaQueue) {
if (force || isBound) {
tagWriter.writeStanzaAsync(packet);
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG,account.getJid().asBareJid()+" do not write stanza to unbound stream "+packet.toString());
}
if (packet instanceof AbstractAcknowledgeableStanza) {
AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
2018-02-02 15:52:40 +00:00
if (this.mStanzaQueue.size() != 0) {
int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
if (currentHighestKey != stanzasSent) {
throw new AssertionError("Stanza count messed up");
}
}
2016-06-14 08:17:37 +00:00
++stanzasSent;
this.mStanzaQueue.append(stanzasSent, stanza);
if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
if (Config.EXTENDED_SM_LOGGING) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
}
tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
2015-08-13 16:25:10 +00:00
}
}
2014-03-03 04:01:02 +00:00
}
2014-02-01 14:07:20 +00:00
}
2014-05-21 20:22:36 +00:00
2014-03-11 14:44:22 +00:00
public void sendPing() {
if (!r()) {
2014-12-30 13:16:25 +00:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setFrom(account.getJid());
2014-05-21 20:22:36 +00:00
iq.addChild("ping", "urn:xmpp:ping");
2014-03-11 14:44:22 +00:00
this.sendIqPacket(iq, null);
}
this.lastPingSent = SystemClock.elapsedRealtime();
2014-03-11 14:44:22 +00:00
}
2014-02-09 13:10:52 +00:00
public void setOnMessagePacketReceivedListener(
final OnMessagePacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.messageListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnUnregisteredIqPacketReceivedListener(
final OnIqPacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.unregisteredIqListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnPresencePacketReceivedListener(
final OnPresencePacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.presenceListener = listener;
}
2014-05-21 20:22:36 +00:00
public void setOnJinglePacketReceivedListener(
final OnJinglePacketReceived listener) {
this.jingleListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnStatusChangedListener(final OnStatusChanged listener) {
this.statusListener = listener;
}
2014-05-21 20:22:36 +00:00
public void setOnBindListener(final OnBindListener listener) {
this.bindListener = listener;
}
2014-08-31 14:28:21 +00:00
public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2014-08-26 14:52:42 +00:00
this.acknowledgedListener = listener;
}
public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
2018-03-18 09:30:15 +00:00
this.advancedStreamFeaturesLoadedListeners.add(listener);
2014-12-05 00:54:16 +00:00
}
private void forceCloseSocket() {
if (socket != null) {
try {
2014-03-10 18:22:13 +00:00
socket.close();
} catch (IOException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception " + e.getMessage() + " during force close");
2014-04-03 13:08:53 +00:00
}
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": socket was null during force close");
}
}
public void interrupt() {
2018-01-20 20:57:09 +00:00
if (this.mThread != null) {
this.mThread.interrupt();
}
}
public void disconnect(final boolean force) {
interrupt();
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + Boolean.toString(force));
if (force) {
forceCloseSocket();
} else {
2018-01-20 20:57:09 +00:00
final TagWriter currentTagWriter = this.tagWriter;
if (currentTagWriter.isActive()) {
currentTagWriter.finish();
final Socket currentSocket = this.socket;
final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
try {
currentTagWriter.await(1,TimeUnit.SECONDS);
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2018-01-20 20:57:09 +00:00
currentTagWriter.writeTag(Tag.end("stream:stream"));
if (streamCountDownLatch != null) {
if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
2018-01-20 20:57:09 +00:00
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
2018-01-20 20:57:09 +00:00
}
}
2018-01-20 20:57:09 +00:00
} catch (InterruptedException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG,account.getJid().asBareJid()+": interrupted while gracefully closing stream");
} catch (final IOException e) {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
} finally {
FileBackend.close(currentSocket);
2014-05-21 20:22:36 +00:00
}
} else {
forceCloseSocket();
}
2014-03-10 18:22:13 +00:00
}
}
2014-05-21 20:22:36 +00:00
private void resetStreamId() {
this.streamId = null;
}
private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2015-10-19 21:03:19 +00:00
synchronized (this.disco) {
final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
if (cursor.getValue().getFeatures().contains(feature)) {
items.add(cursor);
2015-10-19 21:03:19 +00:00
}
2014-05-21 20:22:36 +00:00
}
2015-10-19 21:03:19 +00:00
return items;
2014-05-21 20:22:36 +00:00
}
}
2014-08-31 14:28:21 +00:00
public Jid findDiscoItemByFeature(final String feature) {
final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2014-08-31 14:28:21 +00:00
if (items.size() >= 1) {
return items.get(0).getKey();
}
return null;
2014-03-13 16:29:22 +00:00
}
2014-03-10 18:22:13 +00:00
public boolean r() {
if (getFeatures().sm()) {
this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
return true;
} else {
return false;
}
2014-03-10 18:22:13 +00:00
}
2014-08-31 14:28:21 +00:00
2014-03-15 03:59:18 +00:00
public String getMucServer() {
2015-10-19 21:03:19 +00:00
synchronized (this.disco) {
for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
final ServiceDiscoveryResult value = cursor.getValue();
if (value.getFeatures().contains("http://jabber.org/protocol/muc")
&& !value.getFeatures().contains("jabber:iq:gateway")
&& !value.hasIdentity("conference", "irc")) {
2015-10-19 21:03:19 +00:00
return cursor.getKey().toString();
}
}
}
return null;
2014-03-15 03:59:18 +00:00
}
2014-05-21 20:22:36 +00:00
2014-05-18 09:25:04 +00:00
public int getTimeToNextAttempt() {
final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2014-05-18 09:25:04 +00:00
return interval - secondsSinceLast;
}
2014-05-21 20:22:36 +00:00
2014-05-18 09:25:04 +00:00
public int getAttempt() {
return this.attempt;
}
2014-08-31 14:28:21 +00:00
public Features getFeatures() {
return this.features;
}
2014-08-31 14:28:21 +00:00
public long getLastSessionEstablished() {
2015-08-25 09:11:32 +00:00
final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
return System.currentTimeMillis() - diff;
}
public long getLastConnect() {
return this.lastConnect;
}
public long getLastPingSent() {
return this.lastPingSent;
}
2015-12-15 18:14:38 +00:00
public long getLastDiscoStarted() {
return this.lastDiscoStarted;
}
public long getLastPacketReceived() {
return this.lastPacketReceived;
}
public void sendActive() {
this.sendPacket(new ActivePacket());
}
public void sendInactive() {
this.sendPacket(new InactivePacket());
}
public void resetAttemptCount(boolean resetConnectTime) {
2015-02-10 16:13:34 +00:00
this.attempt = 0;
if (resetConnectTime) {
this.lastConnect = 0;
}
2015-02-10 16:13:34 +00:00
}
public void setInteractive(boolean interactive) {
this.mInteractive = interactive;
}
public Identity getServerIdentity() {
synchronized (this.disco) {
2018-03-05 17:30:40 +00:00
ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
if (result == null) {
return Identity.UNKNOWN;
}
for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
switch (id.getName()) {
case "Prosody":
return Identity.PROSODY;
case "ejabberd":
return Identity.EJABBERD;
case "Slack-XMPP":
return Identity.SLACK;
}
}
}
}
return Identity.UNKNOWN;
}
2018-02-27 19:33:21 +00:00
private IqGenerator getIqGenerator() {
return mXmppConnectionService.getIqGenerator();
}
public enum Identity {
FACEBOOK,
SLACK,
EJABBERD,
PROSODY,
NIMBUZZ,
UNKNOWN
}
private static class TlsFactoryVerifier {
private final SSLSocketFactory factory;
private final DomainHostnameVerifier verifier;
TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
2018-02-27 19:33:21 +00:00
this.factory = factory;
this.verifier = verifier;
if (factory == null || verifier == null) {
throw new IOException("could not setup ssl");
}
}
}
private class MyKeyManager implements X509KeyManager {
@Override
public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
return account.getPrivateKeyAlias();
}
@Override
public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
return null;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
Log.d(Config.LOGTAG, "getting certificate chain");
try {
return KeyChain.getCertificateChain(mXmppConnectionService, alias);
} catch (Exception e) {
Log.d(Config.LOGTAG, e.getMessage());
return new X509Certificate[0];
}
}
@Override
public String[] getClientAliases(String s, Principal[] principals) {
final String alias = account.getPrivateKeyAlias();
return alias != null ? new String[]{alias} : new String[0];
}
@Override
public String[] getServerAliases(String s, Principal[] principals) {
return new String[0];
}
@Override
public PrivateKey getPrivateKey(String alias) {
try {
return KeyChain.getPrivateKey(mXmppConnectionService, alias);
} catch (Exception e) {
return null;
}
}
}
2017-05-05 07:33:05 +00:00
private class StateChangingError extends Error {
private final Account.State state;
2016-08-16 08:39:59 +00:00
2017-05-05 07:33:05 +00:00
public StateChangingError(Account.State state) {
this.state = state;
}
2016-08-16 08:39:59 +00:00
}
2017-05-05 07:33:05 +00:00
private class StateChangingException extends IOException {
private final Account.State state;
2017-05-05 07:33:05 +00:00
public StateChangingException(Account.State state) {
this.state = state;
}
}
public class Features {
XmppConnection connection;
private boolean carbonsEnabled = false;
private boolean encryptionEnabled = false;
private boolean blockListRequested = false;
2014-08-31 14:28:21 +00:00
public Features(final XmppConnection connection) {
this.connection = connection;
}
2014-08-31 14:28:21 +00:00
private boolean hasDiscoFeature(final Jid server, final String feature) {
2015-10-19 21:03:19 +00:00
synchronized (XmppConnection.this.disco) {
return connection.disco.containsKey(server) &&
connection.disco.get(server).getFeatures().contains(feature);
2015-10-19 21:03:19 +00:00
}
}
2014-08-31 14:28:21 +00:00
public boolean carbons() {
return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
}
2014-08-31 14:28:21 +00:00
public boolean blocking() {
return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
}
public boolean spamReporting() {
return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
}
public boolean flexibleOfflineMessageRetrieval() {
return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
}
public boolean register() {
return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
}
public boolean sm() {
return streamId != null
|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
}
2014-08-31 14:28:21 +00:00
2014-08-26 15:43:44 +00:00
public boolean csi() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
2014-08-26 15:43:44 +00:00
}
2014-08-31 14:28:21 +00:00
public boolean pep() {
2015-10-19 21:03:19 +00:00
synchronized (XmppConnection.this.disco) {
2018-03-05 17:30:40 +00:00
ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
return info != null && info.hasIdentity("pubsub", "pep");
}
}
public boolean pepPersistent() {
synchronized (XmppConnection.this.disco) {
2018-03-05 17:30:40 +00:00
ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
}
}
2014-08-31 14:28:21 +00:00
public boolean pepPublishOptions() {
2018-03-05 17:30:40 +00:00
return hasDiscoFeature(account.getJid().asBareJid(),Namespace.PUBSUB_PUBLISH_OPTIONS);
}
public boolean pepOmemoWhitelisted() {
2018-03-05 17:30:40 +00:00
return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
}
public boolean mam() {
2018-03-05 17:30:40 +00:00
return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM)
|| hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM_LEGACY);
2017-02-15 15:42:35 +00:00
}
public boolean mamLegacy() {
2018-03-05 17:30:40 +00:00
return !hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM)
&& hasDiscoFeature(account.getJid().asBareJid(), Namespace.MAM_LEGACY);
}
public boolean push() {
2018-03-05 17:30:40 +00:00
return hasDiscoFeature(account.getJid().asBareJid(), "urn:xmpp:push:0")
|| hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:push:0");
}
public boolean rosterVersioning() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
}
2014-08-31 14:28:21 +00:00
public void setBlockListRequested(boolean value) {
this.blockListRequested = value;
}
public boolean httpUpload(long filesize) {
if (Config.DISABLE_HTTP_UPLOAD) {
return false;
} else {
2017-03-01 12:01:46 +00:00
List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
if (items.size() > 0) {
try {
2017-03-01 12:01:46 +00:00
long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
if (filesize <= maxsize) {
return true;
} else {
2018-03-05 17:30:40 +00:00
Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
return false;
}
} catch (Exception e) {
return true;
}
} else {
return false;
}
}
}
public long getMaxHttpUploadSize() {
2017-03-01 12:01:46 +00:00
List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
if (items.size() > 0) {
try {
return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
} catch (Exception e) {
return -1;
}
} else {
return -1;
}
}
2016-10-31 11:07:08 +00:00
public boolean stanzaIds() {
2018-03-05 17:30:40 +00:00
return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2016-10-31 11:07:08 +00:00
}
}
}