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