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