XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.graphics.Bitmap;
   4import android.graphics.BitmapFactory;
   5import android.os.SystemClock;
   6import android.security.KeyChain;
   7import android.util.Base64;
   8import android.util.Log;
   9import android.util.Pair;
  10import android.util.SparseArray;
  11
  12import org.xmlpull.v1.XmlPullParserException;
  13
  14import java.io.ByteArrayInputStream;
  15import java.io.IOException;
  16import java.io.InputStream;
  17import java.net.ConnectException;
  18import java.net.IDN;
  19import java.net.InetAddress;
  20import java.net.InetSocketAddress;
  21import java.net.MalformedURLException;
  22import java.net.Socket;
  23import java.net.URL;
  24import java.net.UnknownHostException;
  25import java.security.KeyManagementException;
  26import java.security.NoSuchAlgorithmException;
  27import java.security.Principal;
  28import java.security.PrivateKey;
  29import java.security.cert.X509Certificate;
  30import java.util.ArrayList;
  31import java.util.Arrays;
  32import java.util.HashMap;
  33import java.util.HashSet;
  34import java.util.Hashtable;
  35import java.util.Iterator;
  36import java.util.List;
  37import java.util.Map.Entry;
  38import java.util.concurrent.CountDownLatch;
  39import java.util.concurrent.TimeUnit;
  40import java.util.concurrent.atomic.AtomicBoolean;
  41import java.util.concurrent.atomic.AtomicInteger;
  42import java.util.regex.Matcher;
  43
  44import javax.net.ssl.KeyManager;
  45import javax.net.ssl.SSLContext;
  46import javax.net.ssl.SSLSession;
  47import javax.net.ssl.SSLSocket;
  48import javax.net.ssl.SSLSocketFactory;
  49import javax.net.ssl.X509KeyManager;
  50import javax.net.ssl.X509TrustManager;
  51
  52import de.duenndns.ssl.DomainHostnameVerifier;
  53import de.duenndns.ssl.MemorizingTrustManager;
  54import eu.siacs.conversations.Config;
  55import eu.siacs.conversations.crypto.XmppDomainVerifier;
  56import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  57import eu.siacs.conversations.crypto.sasl.Anonymous;
  58import eu.siacs.conversations.crypto.sasl.DigestMd5;
  59import eu.siacs.conversations.crypto.sasl.External;
  60import eu.siacs.conversations.crypto.sasl.Plain;
  61import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  62import eu.siacs.conversations.crypto.sasl.ScramSha1;
  63import eu.siacs.conversations.crypto.sasl.ScramSha256;
  64import eu.siacs.conversations.entities.Account;
  65import eu.siacs.conversations.entities.Message;
  66import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  67import eu.siacs.conversations.generator.IqGenerator;
  68import eu.siacs.conversations.persistance.FileBackend;
  69import eu.siacs.conversations.services.NotificationService;
  70import eu.siacs.conversations.services.XmppConnectionService;
  71import eu.siacs.conversations.utils.CryptoHelper;
  72import eu.siacs.conversations.utils.IP;
  73import eu.siacs.conversations.utils.Patterns;
  74import eu.siacs.conversations.utils.Resolver;
  75import eu.siacs.conversations.utils.SSLSocketHelper;
  76import eu.siacs.conversations.utils.SocksSocketFactory;
  77import eu.siacs.conversations.xml.Element;
  78import eu.siacs.conversations.xml.Tag;
  79import eu.siacs.conversations.xml.TagWriter;
  80import eu.siacs.conversations.xml.XmlReader;
  81import eu.siacs.conversations.xml.Namespace;
  82import eu.siacs.conversations.xmpp.forms.Data;
  83import eu.siacs.conversations.xmpp.forms.Field;
  84import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  85import eu.siacs.conversations.xmpp.jid.Jid;
  86import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  87import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  88import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  89import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  90import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  91import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  92import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  93import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  94import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  95import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  96import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  97import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
  98import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
  99
 100public class XmppConnection implements Runnable {
 101
 102	private static final int PACKET_IQ = 0;
 103	private static final int PACKET_MESSAGE = 1;
 104	private static final int PACKET_PRESENCE = 2;
 105	protected final Account account;
 106	private Socket socket;
 107	private XmlReader tagReader;
 108	private TagWriter tagWriter = new TagWriter();
 109	private final Features features = new Features(this);
 110	private boolean needsBinding = true;
 111	private boolean shouldAuthenticate = true;
 112	private boolean inSmacksSession = false;
 113	private Element streamFeatures;
 114	private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 115
 116	private String streamId = null;
 117	private int smVersion = 3;
 118	private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 119
 120	private int stanzasReceived = 0;
 121	private int stanzasSent = 0;
 122	private long lastPacketReceived = 0;
 123	private long lastPingSent = 0;
 124	private long lastConnect = 0;
 125	private long lastSessionStarted = 0;
 126	private long lastDiscoStarted = 0;
 127	private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 128	private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 129	private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 130	private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 131	private boolean mInteractive = false;
 132	private int attempt = 0;
 133	private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 134	private OnPresencePacketReceived presenceListener = null;
 135	private OnJinglePacketReceived jingleListener = null;
 136	private OnIqPacketReceived unregisteredIqListener = null;
 137	private OnMessagePacketReceived messageListener = null;
 138	private OnStatusChanged statusListener = null;
 139	private OnBindListener bindListener = null;
 140	private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
 141	private OnMessageAcknowledged acknowledgedListener = null;
 142	private final XmppConnectionService mXmppConnectionService;
 143
 144	private SaslMechanism saslMechanism;
 145	private URL redirectionUrl = null;
 146	private String verifiedHostname = null;
 147	private Thread mThread;
 148	private CountDownLatch mStreamCountDownLatch;
 149
 150	private class MyKeyManager implements X509KeyManager {
 151		@Override
 152		public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
 153			return account.getPrivateKeyAlias();
 154		}
 155
 156		@Override
 157		public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
 158			return null;
 159		}
 160
 161		@Override
 162		public X509Certificate[] getCertificateChain(String alias) {
 163			Log.d(Config.LOGTAG, "getting certificate chain");
 164			try {
 165				return KeyChain.getCertificateChain(mXmppConnectionService, alias);
 166			} catch (Exception e) {
 167				Log.d(Config.LOGTAG, e.getMessage());
 168				return new X509Certificate[0];
 169			}
 170		}
 171
 172		@Override
 173		public String[] getClientAliases(String s, Principal[] principals) {
 174			final String alias = account.getPrivateKeyAlias();
 175			return alias != null ? new String[]{alias} : new String[0];
 176		}
 177
 178		@Override
 179		public String[] getServerAliases(String s, Principal[] principals) {
 180			return new String[0];
 181		}
 182
 183		@Override
 184		public PrivateKey getPrivateKey(String alias) {
 185			try {
 186				return KeyChain.getPrivateKey(mXmppConnectionService, alias);
 187			} catch (Exception e) {
 188				return null;
 189			}
 190		}
 191	}
 192
 193	public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
 194		@Override
 195		public void onIqPacketReceived(Account account, IqPacket packet) {
 196			if (packet.getType() == IqPacket.TYPE.RESULT) {
 197				account.setOption(Account.OPTION_REGISTER, false);
 198				throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 199			} else {
 200				final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 201						"The password is too weak",
 202						"Please use a longer password.");
 203				Element error = packet.findChild("error");
 204				Account.State state = Account.State.REGISTRATION_FAILED;
 205				if (error != null) {
 206					if (error.hasChild("conflict")) {
 207						state = Account.State.REGISTRATION_CONFLICT;
 208					} else if (error.hasChild("resource-constraint")
 209							&& "wait".equals(error.getAttribute("type"))) {
 210						state = Account.State.REGISTRATION_PLEASE_WAIT;
 211					} else if (error.hasChild("not-acceptable")
 212							&& PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 213						state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 214					}
 215				}
 216				throw new StateChangingError(state);
 217			}
 218		}
 219	};
 220
 221	public XmppConnection(final Account account, final XmppConnectionService service) {
 222		this.account = account;
 223		final String tag = account.getJid().toBareJid().toPreppedString();
 224		mXmppConnectionService = service;
 225	}
 226
 227	protected void changeStatus(final Account.State nextStatus) {
 228		synchronized (this) {
 229			if (Thread.currentThread().isInterrupted()) {
 230				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
 231				return;
 232			}
 233			if (account.getStatus() != nextStatus) {
 234				if ((nextStatus == Account.State.OFFLINE)
 235						&& (account.getStatus() != Account.State.CONNECTING)
 236						&& (account.getStatus() != Account.State.ONLINE)
 237						&& (account.getStatus() != Account.State.DISABLED)) {
 238					return;
 239				}
 240				if (nextStatus == Account.State.ONLINE) {
 241					this.attempt = 0;
 242				}
 243				account.setStatus(nextStatus);
 244			} else {
 245				return;
 246			}
 247		}
 248		if (statusListener != null) {
 249			statusListener.onStatusChanged(account);
 250		}
 251	}
 252
 253	public void prepareNewConnection() {
 254		this.lastConnect = SystemClock.elapsedRealtime();
 255		this.lastPingSent = SystemClock.elapsedRealtime();
 256		this.lastDiscoStarted = Long.MAX_VALUE;
 257		this.mWaitingForSmCatchup.set(false);
 258		this.changeStatus(Account.State.CONNECTING);
 259	}
 260
 261	public boolean isWaitingForSmCatchup() {
 262		return mWaitingForSmCatchup.get();
 263	}
 264
 265	public void incrementSmCatchupMessageCounter() {
 266		this.mSmCatchupMessageCounter.incrementAndGet();
 267	}
 268
 269	protected void connect() {
 270		if (mXmppConnectionService.areMessagesInitialized()) {
 271			mXmppConnectionService.resetSendingToWaiting(account);
 272		}
 273		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
 274		features.encryptionEnabled = false;
 275		inSmacksSession = false;
 276		this.attempt++;
 277		this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
 278		try {
 279			Socket localSocket;
 280			shouldAuthenticate = needsBinding = !account.isOptionSet(Account.OPTION_REGISTER);
 281			this.changeStatus(Account.State.CONNECTING);
 282			final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 283			final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 284			if (useTor) {
 285				String destination;
 286				if (account.getHostname().isEmpty()) {
 287					destination = account.getServer().toString();
 288				} else {
 289					destination = account.getHostname();
 290					this.verifiedHostname = destination;
 291				}
 292				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": connect to " + destination + " via Tor");
 293				localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
 294				try {
 295					startXmpp(localSocket);
 296				} catch (InterruptedException e) {
 297					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream");
 298					return;
 299				} catch (Exception e) {
 300					throw new IOException(e.getMessage());
 301				}
 302			} else if (extended && !account.getHostname().isEmpty()) {
 303
 304				this.verifiedHostname = account.getHostname();
 305
 306				try {
 307					InetSocketAddress address = new InetSocketAddress(this.verifiedHostname, account.getPort());
 308					features.encryptionEnabled = address.getPort() == 5223;
 309					if (features.encryptionEnabled) {
 310						try {
 311							final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 312							localSocket = tlsFactoryVerifier.factory.createSocket();
 313							localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
 314							final SSLSession session = ((SSLSocket) localSocket).getSession();
 315							final String domain = account.getJid().getDomainpart();
 316							if (!tlsFactoryVerifier.verifier.verify(domain, this.verifiedHostname, session)) {
 317								Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
 318								throw new StateChangingException(Account.State.TLS_ERROR);
 319							}
 320						} catch (KeyManagementException e) {
 321							throw new StateChangingException(Account.State.TLS_ERROR);
 322						}
 323					} else {
 324						localSocket = new Socket();
 325						localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
 326					}
 327				} catch (IOException | IllegalArgumentException e) {
 328					throw new UnknownHostException();
 329				}
 330				try {
 331					startXmpp(localSocket);
 332				} catch (InterruptedException e) {
 333					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream");
 334					return;
 335				} catch (Exception e) {
 336					throw new IOException(e.getMessage());
 337				}
 338			} else if (IP.matches(account.getServer().toString())) {
 339				localSocket = new Socket();
 340				try {
 341					localSocket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
 342				} catch (IOException e) {
 343					throw new UnknownHostException();
 344				}
 345				try {
 346					startXmpp(localSocket);
 347				} catch (InterruptedException e) {
 348					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": thread was interrupted before beginning stream");
 349					return;
 350				} catch (Exception e) {
 351					throw new IOException(e.getMessage());
 352				}
 353			} else {
 354				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			} else {
 439				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": not force closing socket because thread was interrupted");
 440			}
 441		}
 442	}
 443
 444	/**
 445	 * Starts xmpp protocol, call after connecting to socket
 446	 *
 447	 * @return true if server returns with valid xmpp, false otherwise
 448	 */
 449	private boolean startXmpp(Socket socket) throws Exception {
 450		if (Thread.currentThread().isInterrupted()) {
 451			throw new InterruptedException();
 452		}
 453		this.socket = socket;
 454		tagReader = new XmlReader();
 455		if (tagWriter != null) {
 456			tagWriter.forceClose();
 457		}
 458		tagWriter = new TagWriter();
 459		tagWriter.setOutputStream(socket.getOutputStream());
 460		tagReader.setInputStream(socket.getInputStream());
 461		tagWriter.beginDocument();
 462		sendStartStream();
 463		final Tag tag = tagReader.readTag();
 464		return tag != null && tag.isStart("stream");
 465	}
 466
 467	private static class TlsFactoryVerifier {
 468		private final SSLSocketFactory factory;
 469		private final DomainHostnameVerifier verifier;
 470
 471		public TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
 472			this.factory = factory;
 473			this.verifier = verifier;
 474			if (factory == null || verifier == null) {
 475				throw new IOException("could not setup ssl");
 476			}
 477		}
 478	}
 479
 480	private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
 481		final SSLContext sc = SSLSocketHelper.getSSLContext();
 482		MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 483		KeyManager[] keyManager;
 484		if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
 485			keyManager = new KeyManager[]{new MyKeyManager()};
 486		} else {
 487			keyManager = null;
 488		}
 489		String domain = account.getJid().getDomainpart();
 490		sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 491		final SSLSocketFactory factory = sc.getSocketFactory();
 492		final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
 493		return new TlsFactoryVerifier(factory, verifier);
 494	}
 495
 496	@Override
 497	public void run() {
 498		synchronized (this) {
 499			this.mThread = Thread.currentThread();
 500			if (this.mThread.isInterrupted()) {
 501				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": aborting connect because thread was interrupted");
 502				return;
 503			}
 504			forceCloseSocket();
 505		}
 506		connect();
 507	}
 508
 509	private void processStream() throws XmlPullParserException, IOException, NoSuchAlgorithmException {
 510		final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 511		this.mStreamCountDownLatch = streamCountDownLatch;
 512		Tag nextTag = tagReader.readTag();
 513		while (nextTag != null && !nextTag.isEnd("stream")) {
 514			if (nextTag.isStart("error")) {
 515				processStreamError(nextTag);
 516			} else if (nextTag.isStart("features")) {
 517				processStreamFeatures(nextTag);
 518			} else if (nextTag.isStart("proceed")) {
 519				switchOverToTls(nextTag);
 520			} else if (nextTag.isStart("success")) {
 521				final String challenge = tagReader.readElement(nextTag).getContent();
 522				try {
 523					saslMechanism.getResponse(challenge);
 524				} catch (final SaslMechanism.AuthenticationException e) {
 525					Log.e(Config.LOGTAG, String.valueOf(e));
 526					throw new StateChangingException(Account.State.UNAUTHORIZED);
 527				}
 528				Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
 529				account.setKey(Account.PINNED_MECHANISM_KEY,
 530						String.valueOf(saslMechanism.getPriority()));
 531				tagReader.reset();
 532				sendStartStream();
 533				final Tag tag = tagReader.readTag();
 534				if (tag != null && tag.isStart("stream")) {
 535					processStream();
 536				} else {
 537					throw new IOException("server didn't restart stream after successful auth");
 538				}
 539				break;
 540			} else if (nextTag.isStart("failure")) {
 541				final Element failure = tagReader.readElement(nextTag);
 542				if (Namespace.SASL.equals(failure.getNamespace())) {
 543					final String text = failure.findChildContent("text");
 544					if (failure.hasChild("account-disabled") && text != null) {
 545						Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 546						if (matcher.find()) {
 547							try {
 548								URL url = new URL(text.substring(matcher.start(), matcher.end()));
 549								if (url.getProtocol().equals("https")) {
 550									this.redirectionUrl = url;
 551									throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 552								}
 553							} catch (MalformedURLException e) {
 554								throw new StateChangingException(Account.State.UNAUTHORIZED);
 555							}
 556						}
 557					}
 558					throw new StateChangingException(Account.State.UNAUTHORIZED);
 559				} else if (Namespace.TLS.equals(failure.getNamespace())) {
 560					throw new StateChangingException(Account.State.TLS_ERROR);
 561				} else {
 562					throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 563				}
 564			} else if (nextTag.isStart("challenge")) {
 565				final String challenge = tagReader.readElement(nextTag).getContent();
 566				final Element response = new Element("response", Namespace.SASL);
 567				try {
 568					response.setContent(saslMechanism.getResponse(challenge));
 569				} catch (final SaslMechanism.AuthenticationException e) {
 570					// TODO: Send auth abort tag.
 571					Log.e(Config.LOGTAG, e.toString());
 572				}
 573				tagWriter.writeElement(response);
 574			} else if (nextTag.isStart("enabled")) {
 575				final Element enabled = tagReader.readElement(nextTag);
 576				if ("true".equals(enabled.getAttribute("resume"))) {
 577					this.streamId = enabled.getAttribute("id");
 578					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 579							+ ": stream management(" + smVersion
 580							+ ") enabled (resumable)");
 581				} else {
 582					Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 583							+ ": stream management(" + smVersion + ") enabled");
 584				}
 585				this.stanzasReceived = 0;
 586				this.inSmacksSession = true;
 587				final RequestPacket r = new RequestPacket(smVersion);
 588				tagWriter.writeStanzaAsync(r);
 589			} else if (nextTag.isStart("resumed")) {
 590				this.inSmacksSession = true;
 591				this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 592				lastPacketReceived = SystemClock.elapsedRealtime();
 593				final Element resumed = tagReader.readElement(nextTag);
 594				final String h = resumed.getAttribute("h");
 595				try {
 596					ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 597					synchronized (this.mStanzaQueue) {
 598						final int serverCount = Integer.parseInt(h);
 599						if (serverCount != stanzasSent) {
 600							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 601									+ ": session resumed with lost packages");
 602							stanzasSent = serverCount;
 603						} else {
 604							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
 605						}
 606						acknowledgeStanzaUpTo(serverCount);
 607						for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 608							failedStanzas.add(mStanzaQueue.valueAt(i));
 609						}
 610						mStanzaQueue.clear();
 611					}
 612					Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 613					for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 614						if (packet instanceof MessagePacket) {
 615							MessagePacket message = (MessagePacket) packet;
 616							mXmppConnectionService.markMessage(account,
 617									message.getTo().toBareJid(),
 618									message.getId(),
 619									Message.STATUS_UNSEND);
 620						}
 621						sendPacket(packet);
 622					}
 623				} catch (final NumberFormatException ignored) {
 624				}
 625				Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
 626				changeStatus(Account.State.ONLINE);
 627			} else if (nextTag.isStart("r")) {
 628				tagReader.readElement(nextTag);
 629				if (Config.EXTENDED_SM_LOGGING) {
 630					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 631				}
 632				final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 633				tagWriter.writeStanzaAsync(ack);
 634			} else if (nextTag.isStart("a")) {
 635				boolean accountUiNeedsRefresh = false;
 636				synchronized (NotificationService.CATCHUP_LOCK) {
 637					if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 638						int count = mSmCatchupMessageCounter.get();
 639						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": SM catchup complete (" + count + ")");
 640						accountUiNeedsRefresh = true;
 641						if (count > 0) {
 642							mXmppConnectionService.getNotificationService().finishBacklog(true, account);
 643						}
 644					}
 645				}
 646				if (accountUiNeedsRefresh) {
 647					mXmppConnectionService.updateAccountUi();
 648				}
 649				final Element ack = tagReader.readElement(nextTag);
 650				lastPacketReceived = SystemClock.elapsedRealtime();
 651				try {
 652					synchronized (this.mStanzaQueue) {
 653						final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 654						acknowledgeStanzaUpTo(serverSequence);
 655					}
 656				} catch (NumberFormatException | NullPointerException e) {
 657					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server send ack without sequence number");
 658				}
 659			} else if (nextTag.isStart("failed")) {
 660				Element failed = tagReader.readElement(nextTag);
 661				try {
 662					final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 663					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
 664					synchronized (this.mStanzaQueue) {
 665						acknowledgeStanzaUpTo(serverCount);
 666					}
 667				} catch (NumberFormatException | NullPointerException e) {
 668					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed");
 669				}
 670				resetStreamId();
 671				sendBindRequest();
 672			} else if (nextTag.isStart("iq")) {
 673				processIq(nextTag);
 674			} else if (nextTag.isStart("message")) {
 675				processMessage(nextTag);
 676			} else if (nextTag.isStart("presence")) {
 677				processPresence(nextTag);
 678			}
 679			nextTag = tagReader.readTag();
 680		}
 681		if (nextTag != null && nextTag.isEnd("stream")) {
 682			streamCountDownLatch.countDown();
 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		if (this.mThread != null) {
1464			this.mThread.interrupt();
1465		}
1466	}
1467
1468	public void disconnect(final boolean force) {
1469		interrupt();
1470		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force=" + Boolean.toString(force));
1471		if (force) {
1472			forceCloseSocket();
1473		} else {
1474			final TagWriter currentTagWriter = this.tagWriter;
1475			if (currentTagWriter.isActive()) {
1476				currentTagWriter.finish();
1477				final Socket currentSocket = this.socket;
1478				final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1479				try {
1480					currentTagWriter.await(1,TimeUnit.SECONDS);
1481					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closing stream");
1482					currentTagWriter.writeTag(Tag.end("stream:stream"));
1483					if (streamCountDownLatch != null) {
1484							if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1485							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote ended stream");
1486						} else {
1487							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": remote has not closed socket. force closing");
1488						}
1489					}
1490				} catch (InterruptedException e) {
1491					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": interrupted while gracefully closing stream");
1492				} catch (final IOException e) {
1493					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1494				} finally {
1495					FileBackend.close(currentSocket);
1496				}
1497			} else {
1498				forceCloseSocket();
1499			}
1500		}
1501	}
1502
1503	public void resetStreamId() {
1504		this.streamId = null;
1505	}
1506
1507	private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1508		synchronized (this.disco) {
1509			final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1510			for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1511				if (cursor.getValue().getFeatures().contains(feature)) {
1512					items.add(cursor);
1513				}
1514			}
1515			return items;
1516		}
1517	}
1518
1519	public Jid findDiscoItemByFeature(final String feature) {
1520		final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1521		if (items.size() >= 1) {
1522			return items.get(0).getKey();
1523		}
1524		return null;
1525	}
1526
1527	public boolean r() {
1528		if (getFeatures().sm()) {
1529			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1530			return true;
1531		} else {
1532			return false;
1533		}
1534	}
1535
1536	public String getMucServer() {
1537		synchronized (this.disco) {
1538			for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1539				final ServiceDiscoveryResult value = cursor.getValue();
1540				if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1541						&& !value.getFeatures().contains("jabber:iq:gateway")
1542						&& !value.hasIdentity("conference", "irc")) {
1543					return cursor.getKey().toString();
1544				}
1545			}
1546		}
1547		return null;
1548	}
1549
1550	public int getTimeToNextAttempt() {
1551		final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1552		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1553		return interval - secondsSinceLast;
1554	}
1555
1556	public int getAttempt() {
1557		return this.attempt;
1558	}
1559
1560	public Features getFeatures() {
1561		return this.features;
1562	}
1563
1564	public long getLastSessionEstablished() {
1565		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1566		return System.currentTimeMillis() - diff;
1567	}
1568
1569	public long getLastConnect() {
1570		return this.lastConnect;
1571	}
1572
1573	public long getLastPingSent() {
1574		return this.lastPingSent;
1575	}
1576
1577	public long getLastDiscoStarted() {
1578		return this.lastDiscoStarted;
1579	}
1580
1581	public long getLastPacketReceived() {
1582		return this.lastPacketReceived;
1583	}
1584
1585	public void sendActive() {
1586		this.sendPacket(new ActivePacket());
1587	}
1588
1589	public void sendInactive() {
1590		this.sendPacket(new InactivePacket());
1591	}
1592
1593	public void resetAttemptCount(boolean resetConnectTime) {
1594		this.attempt = 0;
1595		if (resetConnectTime) {
1596			this.lastConnect = 0;
1597		}
1598	}
1599
1600	public void setInteractive(boolean interactive) {
1601		this.mInteractive = interactive;
1602	}
1603
1604	public Identity getServerIdentity() {
1605		synchronized (this.disco) {
1606			ServiceDiscoveryResult result = disco.get(account.getJid().toDomainJid());
1607			if (result == null) {
1608				return Identity.UNKNOWN;
1609			}
1610			for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1611				if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1612					switch (id.getName()) {
1613						case "Prosody":
1614							return Identity.PROSODY;
1615						case "ejabberd":
1616							return Identity.EJABBERD;
1617						case "Slack-XMPP":
1618							return Identity.SLACK;
1619					}
1620				}
1621			}
1622		}
1623		return Identity.UNKNOWN;
1624	}
1625
1626	private class StateChangingError extends Error {
1627		private final Account.State state;
1628
1629		public StateChangingError(Account.State state) {
1630			this.state = state;
1631		}
1632	}
1633
1634	private class StateChangingException extends IOException {
1635		private final Account.State state;
1636
1637		public StateChangingException(Account.State state) {
1638			this.state = state;
1639		}
1640	}
1641
1642	public enum Identity {
1643		FACEBOOK,
1644		SLACK,
1645		EJABBERD,
1646		PROSODY,
1647		NIMBUZZ,
1648		UNKNOWN
1649	}
1650
1651	public class Features {
1652		XmppConnection connection;
1653		private boolean carbonsEnabled = false;
1654		private boolean encryptionEnabled = false;
1655		private boolean blockListRequested = false;
1656
1657		public Features(final XmppConnection connection) {
1658			this.connection = connection;
1659		}
1660
1661		private boolean hasDiscoFeature(final Jid server, final String feature) {
1662			synchronized (XmppConnection.this.disco) {
1663				return connection.disco.containsKey(server) &&
1664						connection.disco.get(server).getFeatures().contains(feature);
1665			}
1666		}
1667
1668		public boolean carbons() {
1669			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1670		}
1671
1672		public boolean blocking() {
1673			return hasDiscoFeature(account.getServer(), Namespace.BLOCKING);
1674		}
1675
1676		public boolean spamReporting() {
1677			return hasDiscoFeature(account.getServer(), "urn:xmpp:reporting:reason:spam:0");
1678		}
1679
1680		public boolean flexibleOfflineMessageRetrieval() {
1681			return hasDiscoFeature(account.getServer(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1682		}
1683
1684		public boolean register() {
1685			return hasDiscoFeature(account.getServer(), Namespace.REGISTER);
1686		}
1687
1688		public boolean sm() {
1689			return streamId != null
1690					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1691		}
1692
1693		public boolean csi() {
1694			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1695		}
1696
1697		public boolean pep() {
1698			synchronized (XmppConnection.this.disco) {
1699				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1700				return info != null && info.hasIdentity("pubsub", "pep");
1701			}
1702		}
1703
1704		public boolean pepPersistent() {
1705			synchronized (XmppConnection.this.disco) {
1706				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1707				return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1708			}
1709		}
1710
1711		public boolean pepPublishOptions() {
1712			return hasDiscoFeature(account.getJid().toBareJid(),Namespace.PUBSUB_PUBLISH_OPTIONS);
1713		}
1714
1715		public boolean pepOmemoWhitelisted() {
1716			return hasDiscoFeature(account.getJid().toBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1717		}
1718
1719		public boolean mam() {
1720			return hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1721					|| hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1722		}
1723
1724		public boolean mamLegacy() {
1725			return !hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1726					&& hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1727		}
1728
1729		public boolean push() {
1730			return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1731					|| hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1732		}
1733
1734		public boolean rosterVersioning() {
1735			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1736		}
1737
1738		public void setBlockListRequested(boolean value) {
1739			this.blockListRequested = value;
1740		}
1741
1742		public boolean httpUpload(long filesize) {
1743			if (Config.DISABLE_HTTP_UPLOAD) {
1744				return false;
1745			} else {
1746				List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1747				if (items.size() > 0) {
1748					try {
1749						long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1750						if (filesize <= maxsize) {
1751							return true;
1752						} else {
1753							Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1754							return false;
1755						}
1756					} catch (Exception e) {
1757						return true;
1758					}
1759				} else {
1760					return false;
1761				}
1762			}
1763		}
1764
1765		public long getMaxHttpUploadSize() {
1766			List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1767			if (items.size() > 0) {
1768				try {
1769					return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1770				} catch (Exception e) {
1771					return -1;
1772				}
1773			} else {
1774				return -1;
1775			}
1776		}
1777
1778		public boolean stanzaIds() {
1779			return hasDiscoFeature(account.getJid().toBareJid(), Namespace.STANZA_IDS);
1780		}
1781	}
1782
1783	private IqGenerator getIqGenerator() {
1784		return mXmppConnectionService.getIqGenerator();
1785	}
1786}