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