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