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) throws XmlPullParserException, IOException {
 879		this.streamFeatures = tagReader.readElement(currentTag);
 880		final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS;
 881		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 882			sendStartTLS();
 883		} else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 884			if (isSecure) {
 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") && shouldAuthenticate && isSecure) {
 892			authenticate();
 893		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 894			if (Config.EXTENDED_SM_LOGGING) {
 895				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resuming after stanza #" + stanzasReceived);
 896			}
 897			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 898			this.mSmCatchupMessageCounter.set(0);
 899			this.mWaitingForSmCatchup.set(true);
 900			this.tagWriter.writeStanzaAsync(resume);
 901		} else if (needsBinding) {
 902			if (this.streamFeatures.hasChild("bind") && isSecure) {
 903				sendBindRequest();
 904			} else {
 905				throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 906			}
 907		}
 908	}
 909
 910	private void authenticate() throws IOException {
 911		final List<String> mechanisms = extractMechanisms(streamFeatures
 912				.findChild("mechanisms"));
 913		final Element auth = new Element("auth", Namespace.SASL);
 914		if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 915			saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 916		} else if (mechanisms.contains("SCRAM-SHA-256")) {
 917			saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 918		} else if (mechanisms.contains("SCRAM-SHA-1")) {
 919			saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 920		} else if (mechanisms.contains("PLAIN") && !account.getJid().getDomainpart().equals("nimbuzz.com")) {
 921			saslMechanism = new Plain(tagWriter, account);
 922		} else if (mechanisms.contains("DIGEST-MD5")) {
 923			saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 924		} else if (mechanisms.contains("ANONYMOUS")) {
 925			saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 926		}
 927		if (saslMechanism != null) {
 928			final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 929			if (pinnedMechanism > saslMechanism.getPriority()) {
 930				Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 931						" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 932						") than pinned priority (" + pinnedMechanism +
 933						"). Possible downgrade attack?");
 934				throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 935			}
 936			Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 937			auth.setAttribute("mechanism", saslMechanism.getMechanism());
 938			if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 939				auth.setContent(saslMechanism.getClientFirstMessage());
 940			}
 941			tagWriter.writeElement(auth);
 942		} else {
 943			throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 944		}
 945	}
 946
 947	private List<String> extractMechanisms(final Element stream) {
 948		final ArrayList<String> mechanisms = new ArrayList<>(stream
 949				.getChildren().size());
 950		for (final Element child : stream.getChildren()) {
 951			mechanisms.add(child.getContent());
 952		}
 953		return mechanisms;
 954	}
 955
 956	private void sendRegistryRequest() {
 957		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 958		register.query("jabber:iq:register");
 959		register.setTo(account.getServer());
 960		sendUnmodifiedIqPacket(register, new OnIqPacketReceived() {
 961
 962			@Override
 963			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 964				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 965					return;
 966				}
 967				if (packet.getType() == IqPacket.TYPE.ERROR) {
 968					throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 969				}
 970				final Element query = packet.query("jabber:iq:register");
 971				if (query.hasChild("username") && (query.hasChild("password"))) {
 972					final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
 973					final Element username = new Element("username").setContent(account.getUsername());
 974					final Element password = new Element("password").setContent(account.getPassword());
 975					register.query("jabber:iq:register").addChild(username);
 976					register.query().addChild(password);
 977					register.setFrom(account.getJid().toBareJid());
 978					sendUnmodifiedIqPacket(register, registrationResponseListener);
 979				} else if (query.hasChild("x", Namespace.DATA)) {
 980					final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 981					final Element blob = query.findChild("data", "urn:xmpp:bob");
 982					final String id = packet.getId();
 983					InputStream is;
 984					if (blob != null) {
 985						try {
 986							final String base64Blob = blob.getContent();
 987							final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 988							is = new ByteArrayInputStream(strBlob);
 989						} catch (Exception e) {
 990							is = null;
 991						}
 992					} else {
 993						try {
 994							Field field = data.getFieldByName("url");
 995							URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
 996							is = url != null ? url.openStream() : null;
 997						} catch (IOException e) {
 998							is = null;
 999						}
1000					}
1001
1002					if (is != null) {
1003						Bitmap captcha = BitmapFactory.decodeStream(is);
1004						try {
1005							if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
1006								return;
1007							}
1008						} catch (Exception e) {
1009							throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1010						}
1011					}
1012					throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1013				} else if (query.hasChild("instructions") || query.hasChild("x",Namespace.OOB)) {
1014					final String instructions = query.findChildContent("instructions");
1015					final Element oob = query.findChild("x", Namespace.OOB);
1016					final String url = oob == null ? null : oob.findChildContent("url");
1017					if (url != null) {
1018						setAccountCreationFailed(url);
1019					} else if (instructions != null) {
1020						Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1021						if (matcher.find()) {
1022							setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1023						}
1024					}
1025					throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1026				}
1027			}
1028		});
1029	}
1030
1031	private void setAccountCreationFailed(String url) {
1032		if (url != null) {
1033			try {
1034				this.redirectionUrl = new URL(url);
1035				if (this.redirectionUrl.getProtocol().equals("https")) {
1036					throw new StateChangingError(Account.State.REGISTRATION_WEB);
1037				}
1038			} catch (MalformedURLException e) {
1039				//fall through
1040			}
1041		}
1042		throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1043	}
1044
1045	public URL getRedirectionUrl() {
1046		return this.redirectionUrl;
1047	}
1048
1049	public void resetEverything() {
1050		resetAttemptCount(true);
1051		resetStreamId();
1052		clearIqCallbacks();
1053		this.stanzasSent = 0;
1054		mStanzaQueue.clear();
1055		this.redirectionUrl = null;
1056		synchronized (this.disco) {
1057			disco.clear();
1058		}
1059	}
1060
1061	private void sendBindRequest() {
1062		try {
1063			mXmppConnectionService.restoredFromDatabaseLatch.await();
1064		} catch (InterruptedException e) {
1065			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": interrupted while waiting for DB restore during bind");
1066			return;
1067		}
1068		needsBinding = false;
1069		clearIqCallbacks();
1070		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1071		iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(account.getResource());
1072		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
1073			@Override
1074			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1075				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1076					return;
1077				}
1078				final Element bind = packet.findChild("bind");
1079				if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1080					final Element jid = bind.findChild("jid");
1081					if (jid != null && jid.getContent() != null) {
1082						try {
1083							Jid assignedJid = Jid.fromString(jid.getContent());
1084							if (!account.getJid().getDomainpart().equals(assignedJid.getDomainpart())) {
1085								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server tried to re-assign domain to "+assignedJid.getDomainpart());
1086								throw new StateChangingError(Account.State.BIND_FAILURE);
1087							}
1088							if (account.setJid(assignedJid)) {
1089								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": bare jid changed during bind. updating database");
1090								mXmppConnectionService.databaseBackend.updateAccount(account);
1091							}
1092							if (streamFeatures.hasChild("session")
1093									&& !streamFeatures.findChild("session").hasChild("optional")) {
1094								sendStartSession();
1095							} else {
1096								sendPostBindInitialization();
1097							}
1098							return;
1099						} catch (final InvalidJidException e) {
1100							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1101						}
1102					} else {
1103						Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1104					}
1105				} else {
1106					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1107				}
1108				final Element error = packet.findChild("error");
1109				final String resource = account.getResource().split("\\.")[0];
1110				if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1111					account.setResource(resource + "." + nextRandomId());
1112				} else {
1113					account.setResource(resource);
1114				}
1115				throw new StateChangingError(Account.State.BIND_FAILURE);
1116			}
1117		});
1118	}
1119
1120	private void clearIqCallbacks() {
1121		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1122		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1123		synchronized (this.packetCallbacks) {
1124			if (this.packetCallbacks.size() == 0) {
1125				return;
1126			}
1127			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1128			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1129			while (iterator.hasNext()) {
1130				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1131				callbacks.add(entry.second);
1132				iterator.remove();
1133			}
1134		}
1135		for (OnIqPacketReceived callback : callbacks) {
1136			try {
1137				callback.onIqPacketReceived(account, failurePacket);
1138			} catch (StateChangingError error) {
1139				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1140				//ignore
1141			}
1142		}
1143		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1144	}
1145
1146	public void sendDiscoTimeout() {
1147		if (mWaitForDisco.compareAndSet(true, false)) {
1148			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": finalizing bind after disco timeout");
1149			finalizeBind();
1150		}
1151	}
1152
1153	private void sendStartSession() {
1154		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": sending legacy session to outdated server");
1155		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1156		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1157		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
1158			@Override
1159			public void onIqPacketReceived(Account account, IqPacket packet) {
1160				if (packet.getType() == IqPacket.TYPE.RESULT) {
1161					sendPostBindInitialization();
1162				} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1163					throw new StateChangingError(Account.State.SESSION_FAILURE);
1164				}
1165			}
1166		});
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		if (discoveryResult == null) {
1207			sendServiceDiscoveryInfo(account.getServer());
1208		} else {
1209			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server caps came from cache");
1210			disco.put(account.getServer(), discoveryResult);
1211		}
1212		sendServiceDiscoveryInfo(account.getJid().toBareJid());
1213		sendServiceDiscoveryItems(account.getServer());
1214
1215		if (!mWaitForDisco.get()) {
1216			finalizeBind();
1217		}
1218		this.lastSessionStarted = SystemClock.elapsedRealtime();
1219	}
1220
1221	private void sendServiceDiscoveryInfo(final Jid jid) {
1222		mPendingServiceDiscoveries.incrementAndGet();
1223		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1224		iq.setTo(jid);
1225		iq.query("http://jabber.org/protocol/disco#info");
1226		this.sendIqPacket(iq, new OnIqPacketReceived() {
1227
1228			@Override
1229			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1230				if (packet.getType() == IqPacket.TYPE.RESULT) {
1231					boolean advancedStreamFeaturesLoaded;
1232					synchronized (XmppConnection.this.disco) {
1233						ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1234						if (jid.equals(account.getServer())) {
1235							mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1236						}
1237						disco.put(jid, result);
1238						advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1239								&& disco.containsKey(account.getJid().toBareJid());
1240					}
1241					if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1242						enableAdvancedStreamFeatures();
1243					}
1244				} else {
1245					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1246				}
1247				if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1248					if (mPendingServiceDiscoveries.decrementAndGet() == 0
1249							&& mWaitForDisco.compareAndSet(true, false)) {
1250						finalizeBind();
1251					}
1252				}
1253			}
1254		});
1255	}
1256
1257	private void finalizeBind() {
1258		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1259		if (bindListener != null) {
1260			bindListener.onBind(account);
1261		}
1262		changeStatus(Account.State.ONLINE);
1263	}
1264
1265	private void enableAdvancedStreamFeatures() {
1266		if (getFeatures().carbons() && !features.carbonsEnabled) {
1267			sendEnableCarbons();
1268		}
1269		if (getFeatures().blocking() && !features.blockListRequested) {
1270			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1271			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1272		}
1273		for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1274			listener.onAdvancedStreamFeaturesAvailable(account);
1275		}
1276	}
1277
1278	private void sendServiceDiscoveryItems(final Jid server) {
1279		mPendingServiceDiscoveries.incrementAndGet();
1280		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1281		iq.setTo(server.toDomainJid());
1282		iq.query("http://jabber.org/protocol/disco#items");
1283		this.sendIqPacket(iq, new OnIqPacketReceived() {
1284
1285			@Override
1286			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1287				if (packet.getType() == IqPacket.TYPE.RESULT) {
1288					HashSet<Jid> items = new HashSet<Jid>();
1289					final List<Element> elements = packet.query().getChildren();
1290					for (final Element element : elements) {
1291						if (element.getName().equals("item")) {
1292							final Jid jid = element.getAttributeAsJid("jid");
1293							if (jid != null && !jid.equals(account.getServer())) {
1294								items.add(jid);
1295							}
1296						}
1297					}
1298					for (Jid jid : items) {
1299						sendServiceDiscoveryInfo(jid);
1300					}
1301				} else {
1302					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1303				}
1304				if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1305					if (mPendingServiceDiscoveries.decrementAndGet() == 0
1306							&& mWaitForDisco.compareAndSet(true, false)) {
1307						finalizeBind();
1308					}
1309				}
1310			}
1311		});
1312	}
1313
1314	private void sendEnableCarbons() {
1315		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1316		iq.addChild("enable", "urn:xmpp:carbons:2");
1317		this.sendIqPacket(iq, new OnIqPacketReceived() {
1318
1319			@Override
1320			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1321				if (!packet.hasChild("error")) {
1322					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1323							+ ": successfully enabled carbons");
1324					features.carbonsEnabled = true;
1325				} else {
1326					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1327							+ ": error enableing carbons " + packet.toString());
1328				}
1329			}
1330		});
1331	}
1332
1333	private void processStreamError(final Tag currentTag)
1334			throws XmlPullParserException, IOException {
1335		final Element streamError = tagReader.readElement(currentTag);
1336		if (streamError == null) {
1337			return;
1338		}
1339		if (streamError.hasChild("conflict")) {
1340			final String resource = account.getResource().split("\\.")[0];
1341			account.setResource(resource + "." + nextRandomId());
1342			Log.d(Config.LOGTAG,
1343					account.getJid().toBareJid() + ": switching resource due to conflict ("
1344							+ account.getResource() + ")");
1345			throw new IOException();
1346		} else if (streamError.hasChild("host-unknown")) {
1347			throw new StateChangingException(Account.State.HOST_UNKNOWN);
1348		} else if (streamError.hasChild("policy-violation")) {
1349			throw new StateChangingException(Account.State.POLICY_VIOLATION);
1350		} else {
1351			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": stream error " + streamError.toString());
1352			throw new StateChangingException(Account.State.STREAM_ERROR);
1353		}
1354	}
1355
1356	private void sendStartStream() throws IOException {
1357		final Tag stream = Tag.start("stream:stream");
1358		stream.setAttribute("to", account.getServer().toString());
1359		stream.setAttribute("version", "1.0");
1360		stream.setAttribute("xml:lang", "en");
1361		stream.setAttribute("xmlns", "jabber:client");
1362		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1363		tagWriter.writeTag(stream);
1364	}
1365
1366	private String nextRandomId() {
1367		return CryptoHelper.random(50, mXmppConnectionService.getRNG());
1368	}
1369
1370	public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1371		packet.setFrom(account.getJid());
1372		return this.sendUnmodifiedIqPacket(packet, callback);
1373	}
1374
1375	public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1376		if (packet.getId() == null) {
1377			packet.setAttribute("id", nextRandomId());
1378		}
1379		if (callback != null) {
1380			synchronized (this.packetCallbacks) {
1381				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1382			}
1383		}
1384		this.sendPacket(packet);
1385		return packet.getId();
1386	}
1387
1388	public void sendMessagePacket(final MessagePacket packet) {
1389		this.sendPacket(packet);
1390	}
1391
1392	public void sendPresencePacket(final PresencePacket packet) {
1393		this.sendPacket(packet);
1394	}
1395
1396	private synchronized void sendPacket(final AbstractStanza packet) {
1397		if (stanzasSent == Integer.MAX_VALUE) {
1398			resetStreamId();
1399			disconnect(true);
1400			return;
1401		}
1402		synchronized (this.mStanzaQueue) {
1403			tagWriter.writeStanzaAsync(packet);
1404			if (packet instanceof AbstractAcknowledgeableStanza) {
1405				AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1406
1407				if (this.mStanzaQueue.size() != 0) {
1408					int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1409					if (currentHighestKey != stanzasSent) {
1410						throw new AssertionError("Stanza count messed up");
1411					}
1412				}
1413
1414				++stanzasSent;
1415				this.mStanzaQueue.append(stanzasSent, stanza);
1416				if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1417					if (Config.EXTENDED_SM_LOGGING) {
1418						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1419					}
1420					tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1421				}
1422			}
1423		}
1424	}
1425
1426	public void sendPing() {
1427		if (!r()) {
1428			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1429			iq.setFrom(account.getJid());
1430			iq.addChild("ping", "urn:xmpp:ping");
1431			this.sendIqPacket(iq, null);
1432		}
1433		this.lastPingSent = SystemClock.elapsedRealtime();
1434	}
1435
1436	public void setOnMessagePacketReceivedListener(
1437			final OnMessagePacketReceived listener) {
1438		this.messageListener = listener;
1439	}
1440
1441	public void setOnUnregisteredIqPacketReceivedListener(
1442			final OnIqPacketReceived listener) {
1443		this.unregisteredIqListener = listener;
1444	}
1445
1446	public void setOnPresencePacketReceivedListener(
1447			final OnPresencePacketReceived listener) {
1448		this.presenceListener = listener;
1449	}
1450
1451	public void setOnJinglePacketReceivedListener(
1452			final OnJinglePacketReceived listener) {
1453		this.jingleListener = listener;
1454	}
1455
1456	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1457		this.statusListener = listener;
1458	}
1459
1460	public void setOnBindListener(final OnBindListener listener) {
1461		this.bindListener = listener;
1462	}
1463
1464	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1465		this.acknowledgedListener = listener;
1466	}
1467
1468	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1469		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1470			this.advancedStreamFeaturesLoadedListeners.add(listener);
1471		}
1472	}
1473
1474	private void forceCloseSocket() {
1475		if (socket != null) {
1476			try {
1477				socket.close();
1478			} catch (IOException e) {
1479				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception " + e.getMessage() + " during force close");
1480			}
1481		} else {
1482			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": socket was null during force close");
1483		}
1484	}
1485
1486	public void interrupt() {
1487		if (this.mThread != null) {
1488			this.mThread.interrupt();
1489		}
1490	}
1491
1492	public void disconnect(final boolean force) {
1493		interrupt();
1494		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force=" + Boolean.toString(force));
1495		if (force) {
1496			forceCloseSocket();
1497		} else {
1498			final TagWriter currentTagWriter = this.tagWriter;
1499			if (currentTagWriter.isActive()) {
1500				currentTagWriter.finish();
1501				final Socket currentSocket = this.socket;
1502				final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1503				try {
1504					currentTagWriter.await(1,TimeUnit.SECONDS);
1505					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closing stream");
1506					currentTagWriter.writeTag(Tag.end("stream:stream"));
1507					if (streamCountDownLatch != null) {
1508							if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1509							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote ended stream");
1510						} else {
1511							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote has not closed socket. force closing");
1512						}
1513					}
1514				} catch (InterruptedException e) {
1515					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": interrupted while gracefully closing stream");
1516				} catch (final IOException e) {
1517					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1518				} finally {
1519					FileBackend.close(currentSocket);
1520				}
1521			} else {
1522				forceCloseSocket();
1523			}
1524		}
1525	}
1526
1527	public void resetStreamId() {
1528		this.streamId = null;
1529	}
1530
1531	private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1532		synchronized (this.disco) {
1533			final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1534			for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1535				if (cursor.getValue().getFeatures().contains(feature)) {
1536					items.add(cursor);
1537				}
1538			}
1539			return items;
1540		}
1541	}
1542
1543	public Jid findDiscoItemByFeature(final String feature) {
1544		final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1545		if (items.size() >= 1) {
1546			return items.get(0).getKey();
1547		}
1548		return null;
1549	}
1550
1551	public boolean r() {
1552		if (getFeatures().sm()) {
1553			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1554			return true;
1555		} else {
1556			return false;
1557		}
1558	}
1559
1560	public String getMucServer() {
1561		synchronized (this.disco) {
1562			for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1563				final ServiceDiscoveryResult value = cursor.getValue();
1564				if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1565						&& !value.getFeatures().contains("jabber:iq:gateway")
1566						&& !value.hasIdentity("conference", "irc")) {
1567					return cursor.getKey().toString();
1568				}
1569			}
1570		}
1571		return null;
1572	}
1573
1574	public int getTimeToNextAttempt() {
1575		final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1576		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1577		return interval - secondsSinceLast;
1578	}
1579
1580	public int getAttempt() {
1581		return this.attempt;
1582	}
1583
1584	public Features getFeatures() {
1585		return this.features;
1586	}
1587
1588	public long getLastSessionEstablished() {
1589		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1590		return System.currentTimeMillis() - diff;
1591	}
1592
1593	public long getLastConnect() {
1594		return this.lastConnect;
1595	}
1596
1597	public long getLastPingSent() {
1598		return this.lastPingSent;
1599	}
1600
1601	public long getLastDiscoStarted() {
1602		return this.lastDiscoStarted;
1603	}
1604
1605	public long getLastPacketReceived() {
1606		return this.lastPacketReceived;
1607	}
1608
1609	public void sendActive() {
1610		this.sendPacket(new ActivePacket());
1611	}
1612
1613	public void sendInactive() {
1614		this.sendPacket(new InactivePacket());
1615	}
1616
1617	public void resetAttemptCount(boolean resetConnectTime) {
1618		this.attempt = 0;
1619		if (resetConnectTime) {
1620			this.lastConnect = 0;
1621		}
1622	}
1623
1624	public void setInteractive(boolean interactive) {
1625		this.mInteractive = interactive;
1626	}
1627
1628	public Identity getServerIdentity() {
1629		synchronized (this.disco) {
1630			ServiceDiscoveryResult result = disco.get(account.getJid().toDomainJid());
1631			if (result == null) {
1632				return Identity.UNKNOWN;
1633			}
1634			for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1635				if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1636					switch (id.getName()) {
1637						case "Prosody":
1638							return Identity.PROSODY;
1639						case "ejabberd":
1640							return Identity.EJABBERD;
1641						case "Slack-XMPP":
1642							return Identity.SLACK;
1643					}
1644				}
1645			}
1646		}
1647		return Identity.UNKNOWN;
1648	}
1649
1650	private class StateChangingError extends Error {
1651		private final Account.State state;
1652
1653		public StateChangingError(Account.State state) {
1654			this.state = state;
1655		}
1656	}
1657
1658	private class StateChangingException extends IOException {
1659		private final Account.State state;
1660
1661		public StateChangingException(Account.State state) {
1662			this.state = state;
1663		}
1664	}
1665
1666	public enum Identity {
1667		FACEBOOK,
1668		SLACK,
1669		EJABBERD,
1670		PROSODY,
1671		NIMBUZZ,
1672		UNKNOWN
1673	}
1674
1675	public class Features {
1676		XmppConnection connection;
1677		private boolean carbonsEnabled = false;
1678		private boolean encryptionEnabled = false;
1679		private boolean blockListRequested = false;
1680
1681		public Features(final XmppConnection connection) {
1682			this.connection = connection;
1683		}
1684
1685		private boolean hasDiscoFeature(final Jid server, final String feature) {
1686			synchronized (XmppConnection.this.disco) {
1687				return connection.disco.containsKey(server) &&
1688						connection.disco.get(server).getFeatures().contains(feature);
1689			}
1690		}
1691
1692		public boolean carbons() {
1693			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1694		}
1695
1696		public boolean blocking() {
1697			return hasDiscoFeature(account.getServer(), Namespace.BLOCKING);
1698		}
1699
1700		public boolean spamReporting() {
1701			return hasDiscoFeature(account.getServer(), "urn:xmpp:reporting:reason:spam:0");
1702		}
1703
1704		public boolean flexibleOfflineMessageRetrieval() {
1705			return hasDiscoFeature(account.getServer(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1706		}
1707
1708		public boolean register() {
1709			return hasDiscoFeature(account.getServer(), Namespace.REGISTER);
1710		}
1711
1712		public boolean sm() {
1713			return streamId != null
1714					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1715		}
1716
1717		public boolean csi() {
1718			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1719		}
1720
1721		public boolean pep() {
1722			synchronized (XmppConnection.this.disco) {
1723				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1724				return info != null && info.hasIdentity("pubsub", "pep");
1725			}
1726		}
1727
1728		public boolean pepPersistent() {
1729			synchronized (XmppConnection.this.disco) {
1730				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1731				return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1732			}
1733		}
1734
1735		public boolean pepPublishOptions() {
1736			return hasDiscoFeature(account.getJid().toBareJid(),Namespace.PUBSUB_PUBLISH_OPTIONS);
1737		}
1738
1739		public boolean pepOmemoWhitelisted() {
1740			return hasDiscoFeature(account.getJid().toBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1741		}
1742
1743		public boolean mam() {
1744			return hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1745					|| hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1746		}
1747
1748		public boolean mamLegacy() {
1749			return !hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1750					&& hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1751		}
1752
1753		public boolean push() {
1754			return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1755					|| hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1756		}
1757
1758		public boolean rosterVersioning() {
1759			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1760		}
1761
1762		public void setBlockListRequested(boolean value) {
1763			this.blockListRequested = value;
1764		}
1765
1766		public boolean httpUpload(long filesize) {
1767			if (Config.DISABLE_HTTP_UPLOAD) {
1768				return false;
1769			} else {
1770				List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1771				if (items.size() > 0) {
1772					try {
1773						long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1774						if (filesize <= maxsize) {
1775							return true;
1776						} else {
1777							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1778							return false;
1779						}
1780					} catch (Exception e) {
1781						return true;
1782					}
1783				} else {
1784					return false;
1785				}
1786			}
1787		}
1788
1789		public long getMaxHttpUploadSize() {
1790			List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1791			if (items.size() > 0) {
1792				try {
1793					return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1794				} catch (Exception e) {
1795					return -1;
1796				}
1797			} else {
1798				return -1;
1799			}
1800		}
1801
1802		public boolean stanzaIds() {
1803			return hasDiscoFeature(account.getJid().toBareJid(), Namespace.STANZA_IDS);
1804		}
1805	}
1806
1807	private IqGenerator getIqGenerator() {
1808		return mXmppConnectionService.getIqGenerator();
1809	}
1810}