XmppConnection.java

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