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