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