XmppConnection.java

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