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