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