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