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