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