XmppConnection.java

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