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