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