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