XmppConnection.java

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