XmppConnection.java

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