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