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