XmppConnection.java

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