XmppConnection.java

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