XmppConnection.java

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