XmppConnection.java

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