XmppConnection.java

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