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