XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.graphics.Bitmap;
   5import android.graphics.BitmapFactory;
   6import android.os.SystemClock;
   7import android.security.KeyChain;
   8import android.support.annotation.NonNull;
   9import android.util.Base64;
  10import android.util.Log;
  11import android.util.Pair;
  12import android.util.SparseArray;
  13
  14import org.xmlpull.v1.XmlPullParserException;
  15
  16import java.io.ByteArrayInputStream;
  17import java.io.IOException;
  18import java.io.InputStream;
  19import java.net.ConnectException;
  20import java.net.IDN;
  21import java.net.InetAddress;
  22import java.net.InetSocketAddress;
  23import java.net.MalformedURLException;
  24import java.net.Socket;
  25import java.net.URL;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.security.Principal;
  30import java.security.PrivateKey;
  31import java.security.cert.X509Certificate;
  32import java.util.ArrayList;
  33import java.util.Arrays;
  34import java.util.Collections;
  35import java.util.HashMap;
  36import java.util.HashSet;
  37import java.util.Hashtable;
  38import java.util.Iterator;
  39import java.util.List;
  40import java.util.Map.Entry;
  41import java.util.Set;
  42import java.util.concurrent.CountDownLatch;
  43import java.util.concurrent.TimeUnit;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47
  48import javax.net.ssl.KeyManager;
  49import javax.net.ssl.SSLContext;
  50import javax.net.ssl.SSLSession;
  51import javax.net.ssl.SSLSocket;
  52import javax.net.ssl.SSLSocketFactory;
  53import javax.net.ssl.X509KeyManager;
  54import javax.net.ssl.X509TrustManager;
  55
  56import eu.siacs.conversations.Config;
  57import eu.siacs.conversations.R;
  58import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  59import eu.siacs.conversations.crypto.XmppDomainVerifier;
  60import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  61import eu.siacs.conversations.crypto.sasl.Anonymous;
  62import eu.siacs.conversations.crypto.sasl.DigestMd5;
  63import eu.siacs.conversations.crypto.sasl.External;
  64import eu.siacs.conversations.crypto.sasl.Plain;
  65import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  66import eu.siacs.conversations.crypto.sasl.ScramSha1;
  67import eu.siacs.conversations.crypto.sasl.ScramSha256;
  68import eu.siacs.conversations.entities.Account;
  69import eu.siacs.conversations.entities.Message;
  70import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  71import eu.siacs.conversations.generator.IqGenerator;
  72import eu.siacs.conversations.persistance.FileBackend;
  73import eu.siacs.conversations.services.MemorizingTrustManager;
  74import eu.siacs.conversations.services.MessageArchiveService;
  75import eu.siacs.conversations.services.NotificationService;
  76import eu.siacs.conversations.services.XmppConnectionService;
  77import eu.siacs.conversations.utils.CryptoHelper;
  78import eu.siacs.conversations.utils.IP;
  79import eu.siacs.conversations.utils.Patterns;
  80import eu.siacs.conversations.utils.Resolver;
  81import eu.siacs.conversations.utils.SSLSocketHelper;
  82import eu.siacs.conversations.utils.SocksSocketFactory;
  83import eu.siacs.conversations.xml.Element;
  84import eu.siacs.conversations.xml.Tag;
  85import eu.siacs.conversations.xml.TagWriter;
  86import eu.siacs.conversations.xml.XmlReader;
  87import eu.siacs.conversations.xml.Namespace;
  88import eu.siacs.conversations.xmpp.forms.Data;
  89import eu.siacs.conversations.xmpp.forms.Field;
  90import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  91import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  92import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  93import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  94import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  95import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  96import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  97import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  98import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  99import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
 100import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 101import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 102import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 103import rocks.xmpp.addr.Jid;
 104
 105public class XmppConnection implements Runnable {
 106
 107	private static final int PACKET_IQ = 0;
 108	private static final int PACKET_MESSAGE = 1;
 109	private static final int PACKET_PRESENCE = 2;
 110	public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
 111		@Override
 112		public void onIqPacketReceived(Account account, IqPacket packet) {
 113			if (packet.getType() == IqPacket.TYPE.RESULT) {
 114				account.setOption(Account.OPTION_REGISTER, false);
 115				throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 116			} else {
 117				final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 118						"The password is too weak",
 119						"Please use a longer password.");
 120				Element error = packet.findChild("error");
 121				Account.State state = Account.State.REGISTRATION_FAILED;
 122				if (error != null) {
 123					if (error.hasChild("conflict")) {
 124						state = Account.State.REGISTRATION_CONFLICT;
 125					} else if (error.hasChild("resource-constraint")
 126							&& "wait".equals(error.getAttribute("type"))) {
 127						state = Account.State.REGISTRATION_PLEASE_WAIT;
 128					} else if (error.hasChild("not-acceptable")
 129							&& PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 130						state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 131					}
 132				}
 133				throw new StateChangingError(state);
 134			}
 135		}
 136	};
 137	protected final Account account;
 138	private final Features features = new Features(this);
 139	private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 140	private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 141	private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 142	private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
 143	private final XmppConnectionService mXmppConnectionService;
 144	private Socket socket;
 145	private XmlReader tagReader;
 146	private TagWriter tagWriter = new TagWriter();
 147	private boolean shouldAuthenticate = true;
 148	private boolean inSmacksSession = false;
 149	private boolean isBound = false;
 150	private Element streamFeatures;
 151	private String streamId = null;
 152	private int smVersion = 3;
 153	private int stanzasReceived = 0;
 154	private int stanzasSent = 0;
 155	private long lastPacketReceived = 0;
 156	private long lastPingSent = 0;
 157	private long lastConnect = 0;
 158	private long lastSessionStarted = 0;
 159	private long lastDiscoStarted = 0;
 160	private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 161	private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 162	private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 163	private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 164	private boolean mInteractive = false;
 165	private int attempt = 0;
 166	private OnPresencePacketReceived presenceListener = null;
 167	private OnJinglePacketReceived jingleListener = null;
 168	private OnIqPacketReceived unregisteredIqListener = null;
 169	private OnMessagePacketReceived messageListener = null;
 170	private OnStatusChanged statusListener = null;
 171	private OnBindListener bindListener = null;
 172	private OnMessageAcknowledged acknowledgedListener = null;
 173	private SaslMechanism saslMechanism;
 174	private URL redirectionUrl = null;
 175	private String verifiedHostname = null;
 176	private Thread mThread;
 177	private CountDownLatch mStreamCountDownLatch;
 178
 179	public XmppConnection(final Account account, final XmppConnectionService service) {
 180		this.account = account;
 181		final String tag = account.getJid().asBareJid().toString();
 182		mXmppConnectionService = service;
 183	}
 184
 185	private static void fixResource(Context context, Account account) {
 186		String resource = account.getResource();
 187		int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
 188		int randomPartLength = 4; // 3 bytes
 189		if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 190			if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 191				account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 192			}
 193		}
 194	}
 195
 196	private static boolean validBase64(String input) {
 197		try {
 198			return Base64.decode(input, Base64.URL_SAFE).length == 3;
 199		} catch (Throwable throwable) {
 200			return false;
 201		}
 202	}
 203
 204	protected void changeStatus(final Account.State nextStatus) {
 205		synchronized (this) {
 206			if (Thread.currentThread().isInterrupted()) {
 207				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
 208				return;
 209			}
 210			if (account.getStatus() != nextStatus) {
 211				if ((nextStatus == Account.State.OFFLINE)
 212						&& (account.getStatus() != Account.State.CONNECTING)
 213						&& (account.getStatus() != Account.State.ONLINE)
 214						&& (account.getStatus() != Account.State.DISABLED)) {
 215					return;
 216				}
 217				if (nextStatus == Account.State.ONLINE) {
 218					this.attempt = 0;
 219				}
 220				account.setStatus(nextStatus);
 221			} else {
 222				return;
 223			}
 224		}
 225		if (statusListener != null) {
 226			statusListener.onStatusChanged(account);
 227		}
 228	}
 229
 230	public void prepareNewConnection() {
 231		this.lastConnect = SystemClock.elapsedRealtime();
 232		this.lastPingSent = SystemClock.elapsedRealtime();
 233		this.lastDiscoStarted = Long.MAX_VALUE;
 234		this.mWaitingForSmCatchup.set(false);
 235		this.changeStatus(Account.State.CONNECTING);
 236	}
 237
 238	public boolean isWaitingForSmCatchup() {
 239		return mWaitingForSmCatchup.get();
 240	}
 241
 242	public void incrementSmCatchupMessageCounter() {
 243		this.mSmCatchupMessageCounter.incrementAndGet();
 244	}
 245
 246	protected void connect() {
 247		if (mXmppConnectionService.areMessagesInitialized()) {
 248			mXmppConnectionService.resetSendingToWaiting(account);
 249		}
 250		Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 251		features.encryptionEnabled = false;
 252		inSmacksSession = false;
 253		isBound = false;
 254		this.attempt++;
 255		this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
 256		try {
 257			Socket localSocket;
 258			shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 259			this.changeStatus(Account.State.CONNECTING);
 260			final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 261			final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 262			if (useTor) {
 263				String destination;
 264				if (account.getHostname().isEmpty()) {
 265					destination = account.getServer();
 266				} else {
 267					destination = account.getHostname();
 268					this.verifiedHostname = destination;
 269				}
 270				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor");
 271				localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
 272				try {
 273					startXmpp(localSocket);
 274				} catch (InterruptedException e) {
 275					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 276					return;
 277				} catch (Exception e) {
 278					throw new IOException(e.getMessage());
 279				}
 280			} else if (extended && !account.getHostname().isEmpty()) {
 281
 282				this.verifiedHostname = account.getHostname();
 283
 284				try {
 285					InetSocketAddress address = new InetSocketAddress(this.verifiedHostname, account.getPort());
 286					features.encryptionEnabled = address.getPort() == 5223;
 287					if (features.encryptionEnabled) {
 288						try {
 289							final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 290							localSocket = tlsFactoryVerifier.factory.createSocket();
 291							localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
 292							final SSLSession session = ((SSLSocket) localSocket).getSession();
 293							final String domain = account.getJid().getDomain();
 294							if (!tlsFactoryVerifier.verifier.verify(domain, this.verifiedHostname, session)) {
 295								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 296								throw new StateChangingException(Account.State.TLS_ERROR);
 297							}
 298						} catch (KeyManagementException e) {
 299							throw new StateChangingException(Account.State.TLS_ERROR);
 300						}
 301					} else {
 302						localSocket = new Socket();
 303						localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
 304					}
 305				} catch (IOException | IllegalArgumentException e) {
 306					throw new UnknownHostException();
 307				}
 308				try {
 309					startXmpp(localSocket);
 310				} catch (InterruptedException e) {
 311					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 312					return;
 313				} catch (Exception e) {
 314					throw new IOException(e.getMessage());
 315				}
 316			} else if (IP.matches(account.getServer())) {
 317				localSocket = new Socket();
 318				try {
 319					localSocket.connect(new InetSocketAddress(account.getServer(), 5222), Config.SOCKET_TIMEOUT * 1000);
 320				} catch (IOException e) {
 321					throw new UnknownHostException();
 322				}
 323				try {
 324					startXmpp(localSocket);
 325				} catch (InterruptedException e) {
 326					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 327					return;
 328				} catch (Exception e) {
 329					throw new IOException(e.getMessage());
 330				}
 331			} else {
 332				final String domain = account.getJid().getDomain();
 333				List<Resolver.Result> results = Resolver.resolve(account.getJid().getDomain());
 334				Resolver.Result storedBackupResult;
 335				if (!Thread.currentThread().isInterrupted()) {
 336					storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
 337					if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 338						results.add(storedBackupResult);
 339						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
 340					}
 341				} else {
 342					storedBackupResult = null;
 343				}
 344				for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
 345					final Resolver.Result result = iterator.next();
 346					if (Thread.currentThread().isInterrupted()) {
 347						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 348						return;
 349					}
 350					try {
 351						// if tls is true, encryption is implied and must not be started
 352						features.encryptionEnabled = result.isDirectTls();
 353						verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
 354						final InetSocketAddress addr;
 355						if (result.getIp() != null) {
 356							addr = new InetSocketAddress(result.getIp(), result.getPort());
 357							Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 358									+ ": using values from dns " + result.getHostname().toString()
 359									+ "/" + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 360						} else {
 361							addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
 362							Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 363									+ ": using values from dns "
 364									+ result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 365						}
 366
 367						if (!features.encryptionEnabled) {
 368							localSocket = new Socket();
 369							localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 370						} else {
 371							final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 372							localSocket = tlsFactoryVerifier.factory.createSocket();
 373
 374							if (localSocket == null) {
 375								throw new IOException("could not initialize ssl socket");
 376							}
 377
 378							SSLSocketHelper.setSecurity((SSLSocket) localSocket);
 379							SSLSocketHelper.setSNIHost(tlsFactoryVerifier.factory, (SSLSocket) localSocket, account.getServer());
 380							SSLSocketHelper.setAlpnProtocol(tlsFactoryVerifier.factory, (SSLSocket) localSocket, "xmpp-client");
 381
 382							localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 383
 384							if (!tlsFactoryVerifier.verifier.verify(account.getServer(), verifiedHostname, ((SSLSocket) localSocket).getSession())) {
 385								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 386								if (!iterator.hasNext()) {
 387									throw new StateChangingException(Account.State.TLS_ERROR);
 388								}
 389							}
 390						}
 391						if (startXmpp(localSocket)) {
 392							if (!result.equals(storedBackupResult)) {
 393								mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
 394							}
 395							break; // successfully connected to server that speaks xmpp
 396						} else {
 397							localSocket.close();
 398						}
 399					} catch (final StateChangingException e) {
 400						throw e;
 401					} catch (InterruptedException e) {
 402						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 403						return;
 404					} catch (final Throwable e) {
 405						Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
 406						if (!iterator.hasNext()) {
 407							throw new UnknownHostException();
 408						}
 409					}
 410				}
 411			}
 412			processStream();
 413		} catch (final SecurityException e) {
 414			this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 415		} catch (final StateChangingException e) {
 416			this.changeStatus(e.state);
 417		} catch (final Resolver.NetworkIsUnreachableException e) {
 418			this.changeStatus(Account.State.NETWORK_IS_UNREACHABLE);
 419		} catch (final UnknownHostException | ConnectException e) {
 420			this.changeStatus(Account.State.SERVER_NOT_FOUND);
 421		} catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 422			this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 423		} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
 424			Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 425			this.changeStatus(Account.State.OFFLINE);
 426			this.attempt = Math.max(0, this.attempt - 1);
 427		} finally {
 428			if (!Thread.currentThread().isInterrupted()) {
 429				forceCloseSocket();
 430			} else {
 431				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
 432			}
 433		}
 434	}
 435
 436	/**
 437	 * Starts xmpp protocol, call after connecting to socket
 438	 *
 439	 * @return true if server returns with valid xmpp, false otherwise
 440	 */
 441	private boolean startXmpp(Socket socket) throws Exception {
 442		if (Thread.currentThread().isInterrupted()) {
 443			throw new InterruptedException();
 444		}
 445		this.socket = socket;
 446		tagReader = new XmlReader();
 447		if (tagWriter != null) {
 448			tagWriter.forceClose();
 449		}
 450		tagWriter = new TagWriter();
 451		tagWriter.setOutputStream(socket.getOutputStream());
 452		tagReader.setInputStream(socket.getInputStream());
 453		tagWriter.beginDocument();
 454		sendStartStream();
 455		final Tag tag = tagReader.readTag();
 456		return tag != null && tag.isStart("stream");
 457	}
 458
 459	private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
 460		final SSLContext sc = SSLSocketHelper.getSSLContext();
 461		MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 462		KeyManager[] keyManager;
 463		if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
 464			keyManager = new KeyManager[]{new MyKeyManager()};
 465		} else {
 466			keyManager = null;
 467		}
 468		String domain = account.getJid().getDomain();
 469		sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 470		final SSLSocketFactory factory = sc.getSocketFactory();
 471		final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
 472		return new TlsFactoryVerifier(factory, verifier);
 473	}
 474
 475	@Override
 476	public void run() {
 477		synchronized (this) {
 478			this.mThread = Thread.currentThread();
 479			if (this.mThread.isInterrupted()) {
 480				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
 481				return;
 482			}
 483			forceCloseSocket();
 484		}
 485		connect();
 486	}
 487
 488	private void processStream() throws XmlPullParserException, IOException, NoSuchAlgorithmException {
 489		final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 490		this.mStreamCountDownLatch = streamCountDownLatch;
 491		Tag nextTag = tagReader.readTag();
 492		while (nextTag != null && !nextTag.isEnd("stream")) {
 493			if (nextTag.isStart("error")) {
 494				processStreamError(nextTag);
 495			} else if (nextTag.isStart("features")) {
 496				processStreamFeatures(nextTag);
 497			} else if (nextTag.isStart("proceed")) {
 498				switchOverToTls(nextTag);
 499			} else if (nextTag.isStart("success")) {
 500				final String challenge = tagReader.readElement(nextTag).getContent();
 501				try {
 502					saslMechanism.getResponse(challenge);
 503				} catch (final SaslMechanism.AuthenticationException e) {
 504					Log.e(Config.LOGTAG, String.valueOf(e));
 505					throw new StateChangingException(Account.State.UNAUTHORIZED);
 506				}
 507				Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
 508				account.setKey(Account.PINNED_MECHANISM_KEY,
 509						String.valueOf(saslMechanism.getPriority()));
 510				tagReader.reset();
 511				sendStartStream();
 512				final Tag tag = tagReader.readTag();
 513				if (tag != null && tag.isStart("stream")) {
 514					processStream();
 515				} else {
 516					throw new IOException("server didn't restart stream after successful auth");
 517				}
 518				break;
 519			} else if (nextTag.isStart("failure")) {
 520				final Element failure = tagReader.readElement(nextTag);
 521				if (Namespace.SASL.equals(failure.getNamespace())) {
 522					final String text = failure.findChildContent("text");
 523					if (failure.hasChild("account-disabled") && text != null) {
 524						Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 525						if (matcher.find()) {
 526							try {
 527								URL url = new URL(text.substring(matcher.start(), matcher.end()));
 528								if (url.getProtocol().equals("https")) {
 529									this.redirectionUrl = url;
 530									throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 531								}
 532							} catch (MalformedURLException e) {
 533								throw new StateChangingException(Account.State.UNAUTHORIZED);
 534							}
 535						}
 536					}
 537					throw new StateChangingException(Account.State.UNAUTHORIZED);
 538				} else if (Namespace.TLS.equals(failure.getNamespace())) {
 539					throw new StateChangingException(Account.State.TLS_ERROR);
 540				} else {
 541					throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 542				}
 543			} else if (nextTag.isStart("challenge")) {
 544				final String challenge = tagReader.readElement(nextTag).getContent();
 545				final Element response = new Element("response", Namespace.SASL);
 546				try {
 547					response.setContent(saslMechanism.getResponse(challenge));
 548				} catch (final SaslMechanism.AuthenticationException e) {
 549					// TODO: Send auth abort tag.
 550					Log.e(Config.LOGTAG, e.toString());
 551				}
 552				tagWriter.writeElement(response);
 553			} else if (nextTag.isStart("enabled")) {
 554				final Element enabled = tagReader.readElement(nextTag);
 555				if ("true".equals(enabled.getAttribute("resume"))) {
 556					this.streamId = enabled.getAttribute("id");
 557					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 558							+ ": stream management(" + smVersion
 559							+ ") enabled (resumable)");
 560				} else {
 561					Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 562							+ ": stream management(" + smVersion + ") enabled");
 563				}
 564				this.stanzasReceived = 0;
 565				this.inSmacksSession = true;
 566				final RequestPacket r = new RequestPacket(smVersion);
 567				tagWriter.writeStanzaAsync(r);
 568			} else if (nextTag.isStart("resumed")) {
 569				this.inSmacksSession = true;
 570				this.isBound = true;
 571				this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 572				lastPacketReceived = SystemClock.elapsedRealtime();
 573				final Element resumed = tagReader.readElement(nextTag);
 574				final String h = resumed.getAttribute("h");
 575				try {
 576					ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 577					final boolean acknowledgedMessages;
 578					synchronized (this.mStanzaQueue) {
 579						final int serverCount = Integer.parseInt(h);
 580						if (serverCount < stanzasSent) {
 581							Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 582									+ ": session resumed with lost packages");
 583							stanzasSent = serverCount;
 584						} else {
 585							Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
 586						}
 587						acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 588						for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 589							failedStanzas.add(mStanzaQueue.valueAt(i));
 590						}
 591						mStanzaQueue.clear();
 592					}
 593					if (acknowledgedMessages) {
 594						mXmppConnectionService.updateConversationUi();
 595					}
 596					Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 597					for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 598						if (packet instanceof MessagePacket) {
 599							MessagePacket message = (MessagePacket) packet;
 600							mXmppConnectionService.markMessage(account,
 601									message.getTo().asBareJid(),
 602									message.getId(),
 603									Message.STATUS_UNSEND);
 604						}
 605						sendPacket(packet);
 606					}
 607				} catch (final NumberFormatException ignored) {
 608				}
 609				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
 610				changeStatus(Account.State.ONLINE);
 611			} else if (nextTag.isStart("r")) {
 612				tagReader.readElement(nextTag);
 613				if (Config.EXTENDED_SM_LOGGING) {
 614					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 615				}
 616				final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 617				tagWriter.writeStanzaAsync(ack);
 618			} else if (nextTag.isStart("a")) {
 619				boolean accountUiNeedsRefresh = false;
 620				synchronized (NotificationService.CATCHUP_LOCK) {
 621					if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 622						int count = mSmCatchupMessageCounter.get();
 623						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (" + count + ")");
 624						accountUiNeedsRefresh = true;
 625						if (count > 0) {
 626							mXmppConnectionService.getNotificationService().finishBacklog(true, account);
 627						}
 628					}
 629				}
 630				if (accountUiNeedsRefresh) {
 631					mXmppConnectionService.updateAccountUi();
 632				}
 633				final Element ack = tagReader.readElement(nextTag);
 634				lastPacketReceived = SystemClock.elapsedRealtime();
 635				try {
 636					final boolean acknowledgedMessages;
 637					synchronized (this.mStanzaQueue) {
 638						final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 639						acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 640					}
 641					if (acknowledgedMessages) {
 642						mXmppConnectionService.updateConversationUi();
 643					}
 644				} catch (NumberFormatException | NullPointerException e) {
 645					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
 646				}
 647			} else if (nextTag.isStart("failed")) {
 648				Element failed = tagReader.readElement(nextTag);
 649				try {
 650					final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 651					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
 652					final boolean acknowledgedMessages;
 653					synchronized (this.mStanzaQueue) {
 654						acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 655					}
 656					if (acknowledgedMessages) {
 657						mXmppConnectionService.updateConversationUi();
 658					}
 659				} catch (NumberFormatException | NullPointerException e) {
 660					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 661				}
 662				resetStreamId();
 663				sendBindRequest();
 664			} else if (nextTag.isStart("iq")) {
 665				processIq(nextTag);
 666			} else if (nextTag.isStart("message")) {
 667				processMessage(nextTag);
 668			} else if (nextTag.isStart("presence")) {
 669				processPresence(nextTag);
 670			}
 671			nextTag = tagReader.readTag();
 672		}
 673		if (nextTag != null && nextTag.isEnd("stream")) {
 674			streamCountDownLatch.countDown();
 675		}
 676	}
 677
 678	private boolean acknowledgeStanzaUpTo(int serverCount) {
 679		if (serverCount > stanzasSent) {
 680			Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 681		}
 682		boolean acknowledgedMessages = false;
 683		for (int i = 0; i < mStanzaQueue.size(); ++i) {
 684			if (serverCount >= mStanzaQueue.keyAt(i)) {
 685				if (Config.EXTENDED_SM_LOGGING) {
 686					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 687				}
 688				AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 689				if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 690					MessagePacket packet = (MessagePacket) stanza;
 691					acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 692				}
 693				mStanzaQueue.removeAt(i);
 694				i--;
 695			}
 696		}
 697		return acknowledgedMessages;
 698	}
 699
 700	private @NonNull
 701	Element processPacket(final Tag currentTag, final int packetType) throws XmlPullParserException, IOException {
 702		Element element;
 703		switch (packetType) {
 704			case PACKET_IQ:
 705				element = new IqPacket();
 706				break;
 707			case PACKET_MESSAGE:
 708				element = new MessagePacket();
 709				break;
 710			case PACKET_PRESENCE:
 711				element = new PresencePacket();
 712				break;
 713			default:
 714				throw new AssertionError("Should never encounter invalid type");
 715		}
 716		element.setAttributes(currentTag.getAttributes());
 717		Tag nextTag = tagReader.readTag();
 718		if (nextTag == null) {
 719			throw new IOException("interrupted mid tag");
 720		}
 721		while (!nextTag.isEnd(element.getName())) {
 722			if (!nextTag.isNo()) {
 723				final Element child = tagReader.readElement(nextTag);
 724				final String type = currentTag.getAttribute("type");
 725				if (packetType == PACKET_IQ
 726						&& "jingle".equals(child.getName())
 727						&& ("set".equalsIgnoreCase(type) || "get"
 728						.equalsIgnoreCase(type))) {
 729					element = new JinglePacket();
 730					element.setAttributes(currentTag.getAttributes());
 731				}
 732				element.addChild(child);
 733			}
 734			nextTag = tagReader.readTag();
 735			if (nextTag == null) {
 736				throw new IOException("interrupted mid tag");
 737			}
 738		}
 739		if (stanzasReceived == Integer.MAX_VALUE) {
 740			resetStreamId();
 741			throw new IOException("time to restart the session. cant handle >2 billion pcks");
 742		}
 743		if (inSmacksSession) {
 744			++stanzasReceived;
 745		} else if (features.sm()) {
 746			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 747		}
 748		lastPacketReceived = SystemClock.elapsedRealtime();
 749		if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 750			Log.d(Config.LOGTAG, "[background stanza] " + element);
 751		}
 752		return element;
 753	}
 754
 755	private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 756		final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 757		if (!packet.valid()) {
 758			Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 759			return;
 760		}
 761		if (packet instanceof JinglePacket) {
 762			if (this.jingleListener != null) {
 763				this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 764			}
 765		} else {
 766			OnIqPacketReceived callback = null;
 767			synchronized (this.packetCallbacks) {
 768				if (packetCallbacks.containsKey(packet.getId())) {
 769					final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 770					// Packets to the server should have responses from the server
 771					if (packetCallbackDuple.first.toServer(account)) {
 772						if (packet.fromServer(account)) {
 773							callback = packetCallbackDuple.second;
 774							packetCallbacks.remove(packet.getId());
 775						} else {
 776							Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 777						}
 778					} else {
 779						if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 780							callback = packetCallbackDuple.second;
 781							packetCallbacks.remove(packet.getId());
 782						} else {
 783							Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 784						}
 785					}
 786				} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 787					callback = this.unregisteredIqListener;
 788				}
 789			}
 790			if (callback != null) {
 791				try {
 792					callback.onIqPacketReceived(account, packet);
 793				} catch (StateChangingError error) {
 794					throw new StateChangingException(error.state);
 795				}
 796			}
 797		}
 798	}
 799
 800	private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 801		final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 802		if (!packet.valid()) {
 803			Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 804			return;
 805		}
 806		this.messageListener.onMessagePacketReceived(account, packet);
 807	}
 808
 809	private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 810		PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 811		if (!packet.valid()) {
 812			Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 813			return;
 814		}
 815		this.presenceListener.onPresencePacketReceived(account, packet);
 816	}
 817
 818	private void sendStartTLS() throws IOException {
 819		final Tag startTLS = Tag.empty("starttls");
 820		startTLS.setAttribute("xmlns", Namespace.TLS);
 821		tagWriter.writeTag(startTLS);
 822	}
 823
 824	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
 825		tagReader.readTag();
 826		try {
 827			final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 828			final InetAddress address = socket == null ? null : socket.getInetAddress();
 829
 830			if (address == null) {
 831				throw new IOException("could not setup ssl");
 832			}
 833
 834			final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 835
 836			if (sslSocket == null) {
 837				throw new IOException("could not initialize ssl socket");
 838			}
 839
 840			SSLSocketHelper.setSecurity(sslSocket);
 841
 842			if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 843				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 844				throw new StateChangingException(Account.State.TLS_ERROR);
 845			}
 846			tagReader.setInputStream(sslSocket.getInputStream());
 847			tagWriter.setOutputStream(sslSocket.getOutputStream());
 848			sendStartStream();
 849			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 850			features.encryptionEnabled = true;
 851			final Tag tag = tagReader.readTag();
 852			if (tag != null && tag.isStart("stream")) {
 853				processStream();
 854			} else {
 855				throw new IOException("server didn't restart stream after STARTTLS");
 856			}
 857			sslSocket.close();
 858		} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 859			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 860			throw new StateChangingException(Account.State.TLS_ERROR);
 861		}
 862	}
 863
 864	private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
 865		this.streamFeatures = tagReader.readElement(currentTag);
 866		final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS;
 867		final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 868		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 869			sendStartTLS();
 870		} else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 871			if (isSecure) {
 872				sendRegistryRequest();
 873			} else {
 874				throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 875			}
 876		} else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 877			throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 878		} else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 879			authenticate();
 880		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 881			if (Config.EXTENDED_SM_LOGGING) {
 882				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 883			}
 884			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 885			this.mSmCatchupMessageCounter.set(0);
 886			this.mWaitingForSmCatchup.set(true);
 887			this.tagWriter.writeStanzaAsync(resume);
 888		} else if (needsBinding) {
 889			if (this.streamFeatures.hasChild("bind") && isSecure) {
 890				sendBindRequest();
 891			} else {
 892				throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 893			}
 894		}
 895	}
 896
 897	private void authenticate() throws IOException {
 898		final List<String> mechanisms = extractMechanisms(streamFeatures
 899				.findChild("mechanisms"));
 900		final Element auth = new Element("auth", Namespace.SASL);
 901		if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 902			saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 903		} else if (mechanisms.contains("SCRAM-SHA-256")) {
 904			saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 905		} else if (mechanisms.contains("SCRAM-SHA-1")) {
 906			saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 907		} else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
 908			saslMechanism = new Plain(tagWriter, account);
 909		} else if (mechanisms.contains("DIGEST-MD5")) {
 910			saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 911		} else if (mechanisms.contains("ANONYMOUS")) {
 912			saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 913		}
 914		if (saslMechanism != null) {
 915			final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 916			if (pinnedMechanism > saslMechanism.getPriority()) {
 917				Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 918						" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 919						") than pinned priority (" + pinnedMechanism +
 920						"). Possible downgrade attack?");
 921				throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 922			}
 923			Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 924			auth.setAttribute("mechanism", saslMechanism.getMechanism());
 925			if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 926				auth.setContent(saslMechanism.getClientFirstMessage());
 927			}
 928			tagWriter.writeElement(auth);
 929		} else {
 930			throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 931		}
 932	}
 933
 934	private List<String> extractMechanisms(final Element stream) {
 935		final ArrayList<String> mechanisms = new ArrayList<>(stream
 936				.getChildren().size());
 937		for (final Element child : stream.getChildren()) {
 938			mechanisms.add(child.getContent());
 939		}
 940		return mechanisms;
 941	}
 942
 943	private void sendRegistryRequest() {
 944		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 945		register.query("jabber:iq:register");
 946		register.setTo(Jid.of(account.getServer()));
 947		sendUnmodifiedIqPacket(register, (account, packet) -> {
 948			if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 949				return;
 950			}
 951			if (packet.getType() == IqPacket.TYPE.ERROR) {
 952				throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 953			}
 954			final Element query = packet.query("jabber:iq:register");
 955			if (query.hasChild("username") && (query.hasChild("password"))) {
 956				final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 957				final Element username = new Element("username").setContent(account.getUsername());
 958				final Element password = new Element("password").setContent(account.getPassword());
 959				register1.query("jabber:iq:register").addChild(username);
 960				register1.query().addChild(password);
 961				register1.setFrom(account.getJid().asBareJid());
 962				sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 963			} else if (query.hasChild("x", Namespace.DATA)) {
 964				final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 965				final Element blob = query.findChild("data", "urn:xmpp:bob");
 966				final String id = packet.getId();
 967				InputStream is;
 968				if (blob != null) {
 969					try {
 970						final String base64Blob = blob.getContent();
 971						final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 972						is = new ByteArrayInputStream(strBlob);
 973					} catch (Exception e) {
 974						is = null;
 975					}
 976				} else {
 977					try {
 978						Field field = data.getFieldByName("url");
 979						URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
 980						is = url != null ? url.openStream() : null;
 981					} catch (IOException e) {
 982						is = null;
 983					}
 984				}
 985
 986				if (is != null) {
 987					Bitmap captcha = BitmapFactory.decodeStream(is);
 988					try {
 989						if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
 990							return;
 991						}
 992					} catch (Exception e) {
 993						throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 994					}
 995				}
 996				throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 997			} else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
 998				final String instructions = query.findChildContent("instructions");
 999				final Element oob = query.findChild("x", Namespace.OOB);
1000				final String url = oob == null ? null : oob.findChildContent("url");
1001				if (url != null) {
1002					setAccountCreationFailed(url);
1003				} else if (instructions != null) {
1004					Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1005					if (matcher.find()) {
1006						setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1007					}
1008				}
1009				throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1010			}
1011		}, true);
1012	}
1013
1014	private void setAccountCreationFailed(String url) {
1015		if (url != null) {
1016			try {
1017				this.redirectionUrl = new URL(url);
1018				if (this.redirectionUrl.getProtocol().equals("https")) {
1019					throw new StateChangingError(Account.State.REGISTRATION_WEB);
1020				}
1021			} catch (MalformedURLException e) {
1022				//fall through
1023			}
1024		}
1025		throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1026	}
1027
1028	public URL getRedirectionUrl() {
1029		return this.redirectionUrl;
1030	}
1031
1032	public void resetEverything() {
1033		resetAttemptCount(true);
1034		resetStreamId();
1035		clearIqCallbacks();
1036		this.stanzasSent = 0;
1037		mStanzaQueue.clear();
1038		this.redirectionUrl = null;
1039		synchronized (this.disco) {
1040			disco.clear();
1041		}
1042	}
1043
1044	private void sendBindRequest() {
1045		try {
1046			mXmppConnectionService.restoredFromDatabaseLatch.await();
1047		} catch (InterruptedException e) {
1048			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1049			return;
1050		}
1051		clearIqCallbacks();
1052		if (account.getJid().isBareJid()) {
1053			account.setResource(this.createNewResource());
1054		} else {
1055			fixResource(mXmppConnectionService, account);
1056		}
1057		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1058		final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1059		iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1060		this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1061			if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1062				return;
1063			}
1064			final Element bind = packet.findChild("bind");
1065			if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1066				isBound = true;
1067				final Element jid = bind.findChild("jid");
1068				if (jid != null && jid.getContent() != null) {
1069					try {
1070						Jid assignedJid = Jid.ofEscaped(jid.getContent());
1071						if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1072							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1073							throw new StateChangingError(Account.State.BIND_FAILURE);
1074						}
1075						if (account.setJid(assignedJid)) {
1076							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1077							mXmppConnectionService.databaseBackend.updateAccount(account);
1078						}
1079						if (streamFeatures.hasChild("session")
1080								&& !streamFeatures.findChild("session").hasChild("optional")) {
1081							sendStartSession();
1082						} else {
1083							sendPostBindInitialization();
1084						}
1085						return;
1086					} catch (final IllegalArgumentException e) {
1087						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1088					}
1089				} else {
1090					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1091				}
1092			} else {
1093				Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1094			}
1095			final Element error = packet.findChild("error");
1096			if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1097				account.setResource(createNewResource());
1098			}
1099			throw new StateChangingError(Account.State.BIND_FAILURE);
1100		}, true);
1101	}
1102
1103	private void clearIqCallbacks() {
1104		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1105		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1106		synchronized (this.packetCallbacks) {
1107			if (this.packetCallbacks.size() == 0) {
1108				return;
1109			}
1110			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1111			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1112			while (iterator.hasNext()) {
1113				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1114				callbacks.add(entry.second);
1115				iterator.remove();
1116			}
1117		}
1118		for (OnIqPacketReceived callback : callbacks) {
1119			try {
1120				callback.onIqPacketReceived(account, failurePacket);
1121			} catch (StateChangingError error) {
1122				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1123				//ignore
1124			}
1125		}
1126		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1127	}
1128
1129	public void sendDiscoTimeout() {
1130		if (mWaitForDisco.compareAndSet(true, false)) {
1131			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1132			finalizeBind();
1133		}
1134	}
1135
1136	private void sendStartSession() {
1137		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1138		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1139		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1140		this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1141			if (packet.getType() == IqPacket.TYPE.RESULT) {
1142				sendPostBindInitialization();
1143			} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1144				throw new StateChangingError(Account.State.SESSION_FAILURE);
1145			}
1146		}, true);
1147	}
1148
1149	private void sendPostBindInitialization() {
1150		smVersion = 0;
1151		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1152			smVersion = 3;
1153		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1154			smVersion = 2;
1155		}
1156		if (smVersion != 0) {
1157			synchronized (this.mStanzaQueue) {
1158				final EnablePacket enable = new EnablePacket(smVersion);
1159				tagWriter.writeStanzaAsync(enable);
1160				stanzasSent = 0;
1161				mStanzaQueue.clear();
1162			}
1163		}
1164		features.carbonsEnabled = false;
1165		features.blockListRequested = false;
1166		synchronized (this.disco) {
1167			this.disco.clear();
1168		}
1169		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1170		mPendingServiceDiscoveries.set(0);
1171		if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
1172			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1173			mWaitForDisco.set(false);
1174		} else {
1175			mWaitForDisco.set(true);
1176		}
1177		lastDiscoStarted = SystemClock.elapsedRealtime();
1178		mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1179		Element caps = streamFeatures.findChild("c");
1180		final String hash = caps == null ? null : caps.getAttribute("hash");
1181		final String ver = caps == null ? null : caps.getAttribute("ver");
1182		ServiceDiscoveryResult discoveryResult = null;
1183		if (hash != null && ver != null) {
1184			discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1185		}
1186		final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1187		if (requestDiscoItemsFirst) {
1188			sendServiceDiscoveryItems(Jid.of(account.getServer()));
1189		}
1190		if (discoveryResult == null) {
1191			sendServiceDiscoveryInfo(Jid.of(account.getServer()));
1192		} else {
1193			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1194			disco.put(Jid.of(account.getServer()), discoveryResult);
1195		}
1196		sendServiceDiscoveryInfo(account.getJid().asBareJid());
1197		if (!requestDiscoItemsFirst) {
1198			sendServiceDiscoveryItems(Jid.of(account.getServer()));
1199		}
1200
1201		if (!mWaitForDisco.get()) {
1202			finalizeBind();
1203		}
1204		this.lastSessionStarted = SystemClock.elapsedRealtime();
1205	}
1206
1207	private void sendServiceDiscoveryInfo(final Jid jid) {
1208		mPendingServiceDiscoveries.incrementAndGet();
1209		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1210		iq.setTo(jid);
1211		iq.query("http://jabber.org/protocol/disco#info");
1212		this.sendIqPacket(iq, (account, packet) -> {
1213			if (packet.getType() == IqPacket.TYPE.RESULT) {
1214				boolean advancedStreamFeaturesLoaded;
1215				synchronized (XmppConnection.this.disco) {
1216					ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1217					if (jid.equals(Jid.of(account.getServer()))) {
1218						mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1219					}
1220					disco.put(jid, result);
1221					advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
1222							&& disco.containsKey(account.getJid().asBareJid());
1223				}
1224				if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
1225					enableAdvancedStreamFeatures();
1226				}
1227			} else {
1228				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1229			}
1230			if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1231				if (mPendingServiceDiscoveries.decrementAndGet() == 0
1232						&& mWaitForDisco.compareAndSet(true, false)) {
1233					finalizeBind();
1234				}
1235			}
1236		});
1237	}
1238
1239	private void finalizeBind() {
1240		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1241		if (bindListener != null) {
1242			bindListener.onBind(account);
1243		}
1244		changeStatus(Account.State.ONLINE);
1245	}
1246
1247	private void enableAdvancedStreamFeatures() {
1248		if (getFeatures().carbons() && !features.carbonsEnabled) {
1249			sendEnableCarbons();
1250		}
1251		if (getFeatures().blocking() && !features.blockListRequested) {
1252			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1253			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1254		}
1255		for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1256			listener.onAdvancedStreamFeaturesAvailable(account);
1257		}
1258	}
1259
1260	private void sendServiceDiscoveryItems(final Jid server) {
1261		mPendingServiceDiscoveries.incrementAndGet();
1262		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1263		iq.setTo(Jid.ofDomain(server.getDomain()));
1264		iq.query("http://jabber.org/protocol/disco#items");
1265		this.sendIqPacket(iq, (account, packet) -> {
1266			if (packet.getType() == IqPacket.TYPE.RESULT) {
1267				HashSet<Jid> items = new HashSet<Jid>();
1268				final List<Element> elements = packet.query().getChildren();
1269				for (final Element element : elements) {
1270					if (element.getName().equals("item")) {
1271						final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1272						if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
1273							items.add(jid);
1274						}
1275					}
1276				}
1277				for (Jid jid : items) {
1278					sendServiceDiscoveryInfo(jid);
1279				}
1280			} else {
1281				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1282			}
1283			if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1284				if (mPendingServiceDiscoveries.decrementAndGet() == 0
1285						&& mWaitForDisco.compareAndSet(true, false)) {
1286					finalizeBind();
1287				}
1288			}
1289		});
1290	}
1291
1292	private void sendEnableCarbons() {
1293		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1294		iq.addChild("enable", "urn:xmpp:carbons:2");
1295		this.sendIqPacket(iq, new OnIqPacketReceived() {
1296
1297			@Override
1298			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1299				if (!packet.hasChild("error")) {
1300					Log.d(Config.LOGTAG, account.getJid().asBareJid()
1301							+ ": successfully enabled carbons");
1302					features.carbonsEnabled = true;
1303				} else {
1304					Log.d(Config.LOGTAG, account.getJid().asBareJid()
1305							+ ": error enableing carbons " + packet.toString());
1306				}
1307			}
1308		});
1309	}
1310
1311	private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1312		final Element streamError = tagReader.readElement(currentTag);
1313		if (streamError == null) {
1314			return;
1315		}
1316		if (streamError.hasChild("conflict")) {
1317			account.setResource(createNewResource());
1318			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1319			throw new IOException();
1320		} else if (streamError.hasChild("host-unknown")) {
1321			throw new StateChangingException(Account.State.HOST_UNKNOWN);
1322		} else if (streamError.hasChild("policy-violation")) {
1323			throw new StateChangingException(Account.State.POLICY_VIOLATION);
1324		} else {
1325			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1326			throw new StateChangingException(Account.State.STREAM_ERROR);
1327		}
1328	}
1329
1330	private void sendStartStream() throws IOException {
1331		final Tag stream = Tag.start("stream:stream");
1332		stream.setAttribute("to", account.getServer());
1333		stream.setAttribute("version", "1.0");
1334		stream.setAttribute("xml:lang", "en");
1335		stream.setAttribute("xmlns", "jabber:client");
1336		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1337		tagWriter.writeTag(stream);
1338	}
1339
1340	private String createNewResource() {
1341		return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1342	}
1343
1344	private String nextRandomId() {
1345		return nextRandomId(false);
1346	}
1347
1348	private String nextRandomId(boolean s) {
1349		return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1350	}
1351
1352	public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1353		packet.setFrom(account.getJid());
1354		return this.sendUnmodifiedIqPacket(packet, callback, false);
1355	}
1356
1357	public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1358		if (packet.getId() == null) {
1359			packet.setAttribute("id", nextRandomId());
1360		}
1361		if (callback != null) {
1362			synchronized (this.packetCallbacks) {
1363				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1364			}
1365		}
1366		this.sendPacket(packet, force);
1367		return packet.getId();
1368	}
1369
1370	public void sendMessagePacket(final MessagePacket packet) {
1371		this.sendPacket(packet);
1372	}
1373
1374	public void sendPresencePacket(final PresencePacket packet) {
1375		this.sendPacket(packet);
1376	}
1377
1378	private synchronized void sendPacket(final AbstractStanza packet) {
1379		sendPacket(packet, false);
1380	}
1381
1382	private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1383		if (stanzasSent == Integer.MAX_VALUE) {
1384			resetStreamId();
1385			disconnect(true);
1386			return;
1387		}
1388		synchronized (this.mStanzaQueue) {
1389			if (force || isBound) {
1390				tagWriter.writeStanzaAsync(packet);
1391			} else {
1392				Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1393			}
1394			if (packet instanceof AbstractAcknowledgeableStanza) {
1395				AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1396
1397				if (this.mStanzaQueue.size() != 0) {
1398					int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1399					if (currentHighestKey != stanzasSent) {
1400						throw new AssertionError("Stanza count messed up");
1401					}
1402				}
1403
1404				++stanzasSent;
1405				this.mStanzaQueue.append(stanzasSent, stanza);
1406				if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1407					if (Config.EXTENDED_SM_LOGGING) {
1408						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1409					}
1410					tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1411				}
1412			}
1413		}
1414	}
1415
1416	public void sendPing() {
1417		if (!r()) {
1418			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1419			iq.setFrom(account.getJid());
1420			iq.addChild("ping", "urn:xmpp:ping");
1421			this.sendIqPacket(iq, null);
1422		}
1423		this.lastPingSent = SystemClock.elapsedRealtime();
1424	}
1425
1426	public void setOnMessagePacketReceivedListener(
1427			final OnMessagePacketReceived listener) {
1428		this.messageListener = listener;
1429	}
1430
1431	public void setOnUnregisteredIqPacketReceivedListener(
1432			final OnIqPacketReceived listener) {
1433		this.unregisteredIqListener = listener;
1434	}
1435
1436	public void setOnPresencePacketReceivedListener(
1437			final OnPresencePacketReceived listener) {
1438		this.presenceListener = listener;
1439	}
1440
1441	public void setOnJinglePacketReceivedListener(
1442			final OnJinglePacketReceived listener) {
1443		this.jingleListener = listener;
1444	}
1445
1446	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1447		this.statusListener = listener;
1448	}
1449
1450	public void setOnBindListener(final OnBindListener listener) {
1451		this.bindListener = listener;
1452	}
1453
1454	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1455		this.acknowledgedListener = listener;
1456	}
1457
1458	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1459		this.advancedStreamFeaturesLoadedListeners.add(listener);
1460	}
1461
1462	private void forceCloseSocket() {
1463		if (socket != null) {
1464			try {
1465				socket.close();
1466			} catch (IOException e) {
1467				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception " + e.getMessage() + " during force close");
1468			}
1469		} else {
1470			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": socket was null during force close");
1471		}
1472	}
1473
1474	public void interrupt() {
1475		if (this.mThread != null) {
1476			this.mThread.interrupt();
1477		}
1478	}
1479
1480	public void disconnect(final boolean force) {
1481		interrupt();
1482		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + Boolean.toString(force));
1483		if (force) {
1484			forceCloseSocket();
1485		} else {
1486			final TagWriter currentTagWriter = this.tagWriter;
1487			if (currentTagWriter.isActive()) {
1488				currentTagWriter.finish();
1489				final Socket currentSocket = this.socket;
1490				final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1491				try {
1492					currentTagWriter.await(1, TimeUnit.SECONDS);
1493					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1494					currentTagWriter.writeTag(Tag.end("stream:stream"));
1495					if (streamCountDownLatch != null) {
1496						if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1497							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1498						} else {
1499							Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1500						}
1501					}
1502				} catch (InterruptedException e) {
1503					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1504				} catch (final IOException e) {
1505					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1506				} finally {
1507					FileBackend.close(currentSocket);
1508				}
1509			} else {
1510				forceCloseSocket();
1511			}
1512		}
1513	}
1514
1515	private void resetStreamId() {
1516		this.streamId = null;
1517	}
1518
1519	private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1520		synchronized (this.disco) {
1521			final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1522			for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1523				if (cursor.getValue().getFeatures().contains(feature)) {
1524					items.add(cursor);
1525				}
1526			}
1527			return items;
1528		}
1529	}
1530
1531	public Jid findDiscoItemByFeature(final String feature) {
1532		final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1533		if (items.size() >= 1) {
1534			return items.get(0).getKey();
1535		}
1536		return null;
1537	}
1538
1539	public boolean r() {
1540		if (getFeatures().sm()) {
1541			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1542			return true;
1543		} else {
1544			return false;
1545		}
1546	}
1547
1548	public List<String> getMucServersWithholdAccount() {
1549		List<String> servers = getMucServers();
1550		servers.remove(account.getServer());
1551		return servers;
1552	}
1553
1554	public List<String> getMucServers() {
1555		List<String> servers = new ArrayList<>();
1556		synchronized (this.disco) {
1557			for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1558				final ServiceDiscoveryResult value = cursor.getValue();
1559				if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1560						&& value.hasIdentity("conference", "text")
1561						&& !value.getFeatures().contains("jabber:iq:gateway")
1562						&& !value.hasIdentity("conference", "irc")) {
1563					servers.add(cursor.getKey().toString());
1564				}
1565			}
1566		}
1567		return servers;
1568	}
1569
1570	public String getMucServer() {
1571		List<String> servers = getMucServers();
1572		return servers.size() > 0 ? servers.get(0) : null;
1573	}
1574
1575	public int getTimeToNextAttempt() {
1576		final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1577		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1578		return interval - secondsSinceLast;
1579	}
1580
1581	public int getAttempt() {
1582		return this.attempt;
1583	}
1584
1585	public Features getFeatures() {
1586		return this.features;
1587	}
1588
1589	public long getLastSessionEstablished() {
1590		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1591		return System.currentTimeMillis() - diff;
1592	}
1593
1594	public long getLastConnect() {
1595		return this.lastConnect;
1596	}
1597
1598	public long getLastPingSent() {
1599		return this.lastPingSent;
1600	}
1601
1602	public long getLastDiscoStarted() {
1603		return this.lastDiscoStarted;
1604	}
1605
1606	public long getLastPacketReceived() {
1607		return this.lastPacketReceived;
1608	}
1609
1610	public void sendActive() {
1611		this.sendPacket(new ActivePacket());
1612	}
1613
1614	public void sendInactive() {
1615		this.sendPacket(new InactivePacket());
1616	}
1617
1618	public void resetAttemptCount(boolean resetConnectTime) {
1619		this.attempt = 0;
1620		if (resetConnectTime) {
1621			this.lastConnect = 0;
1622		}
1623	}
1624
1625	public void setInteractive(boolean interactive) {
1626		this.mInteractive = interactive;
1627	}
1628
1629	public Identity getServerIdentity() {
1630		synchronized (this.disco) {
1631			ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
1632			if (result == null) {
1633				return Identity.UNKNOWN;
1634			}
1635			for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1636				if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1637					switch (id.getName()) {
1638						case "Prosody":
1639							return Identity.PROSODY;
1640						case "ejabberd":
1641							return Identity.EJABBERD;
1642						case "Slack-XMPP":
1643							return Identity.SLACK;
1644					}
1645				}
1646			}
1647		}
1648		return Identity.UNKNOWN;
1649	}
1650
1651	private IqGenerator getIqGenerator() {
1652		return mXmppConnectionService.getIqGenerator();
1653	}
1654
1655	public enum Identity {
1656		FACEBOOK,
1657		SLACK,
1658		EJABBERD,
1659		PROSODY,
1660		NIMBUZZ,
1661		UNKNOWN
1662	}
1663
1664	private static class TlsFactoryVerifier {
1665		private final SSLSocketFactory factory;
1666		private final DomainHostnameVerifier verifier;
1667
1668		TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1669			this.factory = factory;
1670			this.verifier = verifier;
1671			if (factory == null || verifier == null) {
1672				throw new IOException("could not setup ssl");
1673			}
1674		}
1675	}
1676
1677	private class MyKeyManager implements X509KeyManager {
1678		@Override
1679		public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1680			return account.getPrivateKeyAlias();
1681		}
1682
1683		@Override
1684		public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1685			return null;
1686		}
1687
1688		@Override
1689		public X509Certificate[] getCertificateChain(String alias) {
1690			Log.d(Config.LOGTAG, "getting certificate chain");
1691			try {
1692				return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1693			} catch (Exception e) {
1694				Log.d(Config.LOGTAG, e.getMessage());
1695				return new X509Certificate[0];
1696			}
1697		}
1698
1699		@Override
1700		public String[] getClientAliases(String s, Principal[] principals) {
1701			final String alias = account.getPrivateKeyAlias();
1702			return alias != null ? new String[]{alias} : new String[0];
1703		}
1704
1705		@Override
1706		public String[] getServerAliases(String s, Principal[] principals) {
1707			return new String[0];
1708		}
1709
1710		@Override
1711		public PrivateKey getPrivateKey(String alias) {
1712			try {
1713				return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1714			} catch (Exception e) {
1715				return null;
1716			}
1717		}
1718	}
1719
1720	private class StateChangingError extends Error {
1721		private final Account.State state;
1722
1723		public StateChangingError(Account.State state) {
1724			this.state = state;
1725		}
1726	}
1727
1728	private class StateChangingException extends IOException {
1729		private final Account.State state;
1730
1731		public StateChangingException(Account.State state) {
1732			this.state = state;
1733		}
1734	}
1735
1736	public class Features {
1737		XmppConnection connection;
1738		private boolean carbonsEnabled = false;
1739		private boolean encryptionEnabled = false;
1740		private boolean blockListRequested = false;
1741
1742		public Features(final XmppConnection connection) {
1743			this.connection = connection;
1744		}
1745
1746		private boolean hasDiscoFeature(final Jid server, final String feature) {
1747			synchronized (XmppConnection.this.disco) {
1748				return connection.disco.containsKey(server) &&
1749						connection.disco.get(server).getFeatures().contains(feature);
1750			}
1751		}
1752
1753		public boolean carbons() {
1754			return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
1755		}
1756
1757		public boolean bookmarksConversion() {
1758			return hasDiscoFeature(account.getJid().asBareJid(),Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1759		}
1760
1761		public boolean blocking() {
1762			return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
1763		}
1764
1765		public boolean spamReporting() {
1766			return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
1767		}
1768
1769		public boolean flexibleOfflineMessageRetrieval() {
1770			return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1771		}
1772
1773		public boolean register() {
1774			return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
1775		}
1776
1777		public boolean sm() {
1778			return streamId != null
1779					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1780		}
1781
1782		public boolean csi() {
1783			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1784		}
1785
1786		public boolean pep() {
1787			synchronized (XmppConnection.this.disco) {
1788				ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1789				return info != null && info.hasIdentity("pubsub", "pep");
1790			}
1791		}
1792
1793		public boolean pepPersistent() {
1794			synchronized (XmppConnection.this.disco) {
1795				ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1796				return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1797			}
1798		}
1799
1800		public boolean pepPublishOptions() {
1801			return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1802		}
1803
1804		public boolean pepOmemoWhitelisted() {
1805			return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1806		}
1807
1808		public boolean mam() {
1809			return MessageArchiveService.Version.has(getAccountFeatures());
1810		}
1811
1812		public List<String> getAccountFeatures() {
1813			ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1814			return result == null ? Collections.emptyList() : result.getFeatures();
1815		}
1816
1817		public boolean push() {
1818			return hasDiscoFeature(account.getJid().asBareJid(), "urn:xmpp:push:0")
1819					|| hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:push:0");
1820		}
1821
1822		public boolean rosterVersioning() {
1823			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1824		}
1825
1826		public void setBlockListRequested(boolean value) {
1827			this.blockListRequested = value;
1828		}
1829
1830		public boolean p1S3FileTransfer() {
1831			return hasDiscoFeature(Jid.of(account.getServer()),Namespace.P1_S3_FILE_TRANSFER);
1832		}
1833
1834		public boolean httpUpload(long filesize) {
1835			if (Config.DISABLE_HTTP_UPLOAD) {
1836				return false;
1837			} else {
1838				for(String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1839					List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1840					if (items.size() > 0) {
1841						try {
1842							long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1843							if (filesize <= maxsize) {
1844								return true;
1845							} else {
1846								Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1847								return false;
1848							}
1849						} catch (Exception e) {
1850							return true;
1851						}
1852					}
1853				}
1854				return false;
1855			}
1856		}
1857
1858		public boolean useLegacyHttpUpload() {
1859			return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1860		}
1861
1862		public long getMaxHttpUploadSize() {
1863			for(String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1864				List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1865				if (items.size() > 0) {
1866					try {
1867						return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1868					} catch (Exception e) {
1869						//ignored
1870					}
1871				}
1872			}
1873			return -1;
1874		}
1875
1876		public boolean stanzaIds() {
1877			return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1878		}
1879	}
1880}