XmppConnection.java

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