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