XmppConnection.java

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