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