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