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