XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.os.Bundle;
   4import android.os.Parcelable;
   5import android.os.PowerManager;
   6import android.os.PowerManager.WakeLock;
   7import android.os.SystemClock;
   8import android.util.Log;
   9import android.util.Pair;
  10import android.util.SparseArray;
  11
  12import org.apache.http.conn.ssl.StrictHostnameVerifier;
  13import org.json.JSONException;
  14import org.json.JSONObject;
  15import org.xmlpull.v1.XmlPullParserException;
  16
  17import java.io.IOException;
  18import java.io.InputStream;
  19import java.io.OutputStream;
  20import java.math.BigInteger;
  21import java.net.ConnectException;
  22import java.net.IDN;
  23import java.net.InetAddress;
  24import java.net.InetSocketAddress;
  25import java.net.Socket;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.util.ArrayList;
  30import java.util.Arrays;
  31import java.util.Collection;
  32import java.util.HashMap;
  33import java.util.Hashtable;
  34import java.util.Iterator;
  35import java.util.LinkedList;
  36import java.util.List;
  37import java.util.Map.Entry;
  38
  39import javax.net.ssl.HostnameVerifier;
  40import javax.net.ssl.SSLContext;
  41import javax.net.ssl.SSLSocket;
  42import javax.net.ssl.SSLSocketFactory;
  43import javax.net.ssl.X509TrustManager;
  44
  45import eu.siacs.conversations.Config;
  46import eu.siacs.conversations.crypto.sasl.DigestMd5;
  47import eu.siacs.conversations.crypto.sasl.Plain;
  48import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  49import eu.siacs.conversations.crypto.sasl.ScramSha1;
  50import eu.siacs.conversations.entities.Account;
  51import eu.siacs.conversations.entities.Message;
  52import eu.siacs.conversations.generator.IqGenerator;
  53import eu.siacs.conversations.services.XmppConnectionService;
  54import eu.siacs.conversations.utils.CryptoHelper;
  55import eu.siacs.conversations.utils.DNSHelper;
  56import eu.siacs.conversations.utils.Xmlns;
  57import eu.siacs.conversations.xml.Element;
  58import eu.siacs.conversations.xml.Tag;
  59import eu.siacs.conversations.xml.TagWriter;
  60import eu.siacs.conversations.xml.XmlReader;
  61import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  62import eu.siacs.conversations.xmpp.jid.Jid;
  63import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  64import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  65import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  66import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  67import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  68import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  69import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  70import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  71import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  72import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  73import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  74import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
  75import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
  76
  77public class XmppConnection implements Runnable {
  78
  79	private static final int PACKET_IQ = 0;
  80	private static final int PACKET_MESSAGE = 1;
  81	private static final int PACKET_PRESENCE = 2;
  82	protected Account account;
  83	private final WakeLock wakeLock;
  84	private Socket socket;
  85	private XmlReader tagReader;
  86	private TagWriter tagWriter;
  87	private final Features features = new Features(this);
  88	private boolean needsBinding = true;
  89	private boolean shouldAuthenticate = true;
  90	private Element streamFeatures;
  91	private final HashMap<Jid, Info> disco = new HashMap<>();
  92
  93	private String streamId = null;
  94	private int smVersion = 3;
  95	private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
  96
  97	private int stanzasReceived = 0;
  98	private int stanzasSent = 0;
  99	private long lastPacketReceived = 0;
 100	private long lastPingSent = 0;
 101	private long lastConnect = 0;
 102	private long lastSessionStarted = 0;
 103	private int attempt = 0;
 104	private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 105	private OnPresencePacketReceived presenceListener = null;
 106	private OnJinglePacketReceived jingleListener = null;
 107	private OnIqPacketReceived unregisteredIqListener = null;
 108	private OnMessagePacketReceived messageListener = null;
 109	private OnStatusChanged statusListener = null;
 110	private OnBindListener bindListener = null;
 111	private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
 112	private OnMessageAcknowledged acknowledgedListener = null;
 113	private XmppConnectionService mXmppConnectionService = null;
 114
 115	private SaslMechanism saslMechanism;
 116
 117	public XmppConnection(final Account account, final XmppConnectionService service) {
 118		this.account = account;
 119		this.wakeLock = service.getPowerManager().newWakeLock(
 120				PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
 121		tagWriter = new TagWriter();
 122		mXmppConnectionService = service;
 123	}
 124
 125	protected void changeStatus(final Account.State nextStatus) {
 126		if (account.getStatus() != nextStatus) {
 127			if ((nextStatus == Account.State.OFFLINE)
 128					&& (account.getStatus() != Account.State.CONNECTING)
 129					&& (account.getStatus() != Account.State.ONLINE)
 130					&& (account.getStatus() != Account.State.DISABLED)) {
 131				return;
 132					}
 133			if (nextStatus == Account.State.ONLINE) {
 134				this.attempt = 0;
 135			}
 136			account.setStatus(nextStatus);
 137			if (statusListener != null) {
 138				statusListener.onStatusChanged(account);
 139			}
 140		}
 141	}
 142
 143	protected void connect() {
 144		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
 145		features.encryptionEnabled = false;
 146		lastConnect = SystemClock.elapsedRealtime();
 147		lastPingSent = SystemClock.elapsedRealtime();
 148		this.attempt++;
 149		try {
 150			shouldAuthenticate = needsBinding = !account.isOptionSet(Account.OPTION_REGISTER);
 151			tagReader = new XmlReader(wakeLock);
 152			tagWriter = new TagWriter();
 153			this.changeStatus(Account.State.CONNECTING);
 154			if (DNSHelper.isIp(account.getServer().toString())) {
 155				socket = new Socket();
 156				try {
 157					socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
 158				} catch (IOException e) {
 159					throw new UnknownHostException();
 160				}
 161			} else {
 162				final Bundle result = DNSHelper.getSRVRecord(account.getServer());
 163				if (result == null) {
 164					throw new IOException("unhandled exception in DNS resolver");
 165				}
 166				final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
 167				if ("timeout".equals(result.getString("error"))) {
 168					throw new IOException("timeout in dns");
 169				} else if (values != null) {
 170					int i = 0;
 171					boolean socketError = true;
 172					while (socketError && values.size() > i) {
 173						final Bundle namePort = (Bundle) values.get(i);
 174						try {
 175							String srvRecordServer;
 176							try {
 177								srvRecordServer = IDN.toASCII(namePort.getString("name"));
 178							} catch (final IllegalArgumentException e) {
 179								// TODO: Handle me?`
 180								srvRecordServer = "";
 181							}
 182							final int srvRecordPort = namePort.getInt("port");
 183							final String srvIpServer = namePort.getString("ip");
 184							final InetSocketAddress addr;
 185							if (srvIpServer != null) {
 186								addr = new InetSocketAddress(srvIpServer, srvRecordPort);
 187								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 188										+ ": using values from dns " + srvRecordServer
 189										+ "[" + srvIpServer + "]:" + srvRecordPort);
 190							} else {
 191								addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
 192								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 193										+ ": using values from dns "
 194										+ srvRecordServer + ":" + srvRecordPort);
 195							}
 196							socket = new Socket();
 197							socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 198							socketError = false;
 199						} catch (final Throwable e) {
 200							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 201							i++;
 202						}
 203					}
 204					if (socketError) {
 205						throw new UnknownHostException();
 206					}
 207				} else {
 208					throw new IOException("unhandled exception in DNS resolver");
 209				}
 210			}
 211			final OutputStream out = socket.getOutputStream();
 212			tagWriter.setOutputStream(out);
 213			final InputStream in = socket.getInputStream();
 214			tagReader.setInputStream(in);
 215			tagWriter.beginDocument();
 216			sendStartStream();
 217			Tag nextTag;
 218			while ((nextTag = tagReader.readTag()) != null) {
 219				if (nextTag.isStart("stream")) {
 220					processStream(nextTag);
 221					break;
 222				} else {
 223					throw new IOException("unknown tag on connect");
 224				}
 225			}
 226			if (socket.isConnected()) {
 227				socket.close();
 228			}
 229		} catch (final IncompatibleServerException e) {
 230			this.changeStatus(Account.State.INCOMPATIBLE_SERVER);
 231		} catch (final SecurityException e) {
 232			this.changeStatus(Account.State.SECURITY_ERROR);
 233		} catch (final UnauthorizedException e) {
 234			this.changeStatus(Account.State.UNAUTHORIZED);
 235		} catch (final UnknownHostException | ConnectException e) {
 236			this.changeStatus(Account.State.SERVER_NOT_FOUND);
 237		} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
 238			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 239			this.changeStatus(Account.State.OFFLINE);
 240			this.attempt--; //don't count attempt when reconnecting instantly anyway
 241		} finally {
 242			if (socket != null) {
 243				try {
 244					socket.close();
 245				} catch (IOException e) {
 246
 247				}
 248			}
 249			if (wakeLock.isHeld()) {
 250				try {
 251					wakeLock.release();
 252				} catch (final RuntimeException ignored) {
 253				}
 254			}
 255		}
 256	}
 257
 258	@Override
 259	public void run() {
 260		try {
 261			if (socket != null) {
 262				socket.close();
 263			}
 264		} catch (final IOException ignored) {
 265
 266		}
 267		connect();
 268	}
 269
 270	private void processStream(final Tag currentTag) throws XmlPullParserException,
 271					IOException, NoSuchAlgorithmException {
 272						Tag nextTag = tagReader.readTag();
 273
 274						while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
 275							if (nextTag.isStart("error")) {
 276								processStreamError(nextTag);
 277							} else if (nextTag.isStart("features")) {
 278								processStreamFeatures(nextTag);
 279							} else if (nextTag.isStart("proceed")) {
 280								switchOverToTls(nextTag);
 281							} else if (nextTag.isStart("success")) {
 282								final String challenge = tagReader.readElement(nextTag).getContent();
 283								try {
 284									saslMechanism.getResponse(challenge);
 285								} catch (final SaslMechanism.AuthenticationException e) {
 286									disconnect(true);
 287									Log.e(Config.LOGTAG, String.valueOf(e));
 288								}
 289								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
 290								account.setKey(Account.PINNED_MECHANISM_KEY,
 291										String.valueOf(saslMechanism.getPriority()));
 292								tagReader.reset();
 293								sendStartStream();
 294								processStream(tagReader.readTag());
 295								break;
 296							} else if (nextTag.isStart("failure")) {
 297								throw new UnauthorizedException();
 298							} else if (nextTag.isStart("challenge")) {
 299								final String challenge = tagReader.readElement(nextTag).getContent();
 300								final Element response = new Element("response");
 301								response.setAttribute("xmlns",
 302										"urn:ietf:params:xml:ns:xmpp-sasl");
 303								try {
 304									response.setContent(saslMechanism.getResponse(challenge));
 305								} catch (final SaslMechanism.AuthenticationException e) {
 306									// TODO: Send auth abort tag.
 307									Log.e(Config.LOGTAG, e.toString());
 308								}
 309								tagWriter.writeElement(response);
 310							} else if (nextTag.isStart("enabled")) {
 311								final Element enabled = tagReader.readElement(nextTag);
 312								if ("true".equals(enabled.getAttribute("resume"))) {
 313									this.streamId = enabled.getAttribute("id");
 314									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 315											+ ": stream managment(" + smVersion
 316											+ ") enabled (resumable)");
 317								} else {
 318									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 319											+ ": stream management(" + smVersion + ") enabled");
 320								}
 321								this.lastSessionStarted = SystemClock.elapsedRealtime();
 322								this.stanzasReceived = 0;
 323								final RequestPacket r = new RequestPacket(smVersion);
 324								tagWriter.writeStanzaAsync(r);
 325							} else if (nextTag.isStart("resumed")) {
 326								lastPacketReceived = SystemClock.elapsedRealtime();
 327								final Element resumed = tagReader.readElement(nextTag);
 328								final String h = resumed.getAttribute("h");
 329								try {
 330									final int serverCount = Integer.parseInt(h);
 331									if (serverCount != stanzasSent) {
 332										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 333												+ ": session resumed with lost packages");
 334										stanzasSent = serverCount;
 335									} else {
 336										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
 337									}
 338									acknowledgeStanzaUpTo(serverCount);
 339									ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 340									for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
 341										failedStanzas.add(mStanzaQueue.valueAt(i));
 342									}
 343									mStanzaQueue.clear();
 344									Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
 345									for(AbstractAcknowledgeableStanza packet : failedStanzas) {
 346										if (packet instanceof MessagePacket) {
 347											MessagePacket message = (MessagePacket) packet;
 348											mXmppConnectionService.markMessage(account,
 349													message.getTo().toBareJid(),
 350													message.getId(),
 351													Message.STATUS_UNSEND);
 352										}
 353										sendPacket(packet);
 354									}
 355								} catch (final NumberFormatException ignored) {
 356								}
 357								Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
 358								changeStatus(Account.State.ONLINE);
 359							} else if (nextTag.isStart("r")) {
 360								tagReader.readElement(nextTag);
 361								if (Config.EXTENDED_SM_LOGGING) {
 362									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 363								}
 364								final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 365								tagWriter.writeStanzaAsync(ack);
 366							} else if (nextTag.isStart("a")) {
 367								final Element ack = tagReader.readElement(nextTag);
 368								lastPacketReceived = SystemClock.elapsedRealtime();
 369								try {
 370									final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 371									acknowledgeStanzaUpTo(serverSequence);
 372								} catch (NumberFormatException e) {
 373									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
 374								}
 375							} else if (nextTag.isStart("failed")) {
 376								tagReader.readElement(nextTag);
 377								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
 378								streamId = null;
 379								if (account.getStatus() != Account.State.ONLINE) {
 380									sendBindRequest();
 381								}
 382							} else if (nextTag.isStart("iq")) {
 383								processIq(nextTag);
 384							} else if (nextTag.isStart("message")) {
 385								processMessage(nextTag);
 386							} else if (nextTag.isStart("presence")) {
 387								processPresence(nextTag);
 388							}
 389							nextTag = tagReader.readTag();
 390						}
 391						if (account.getStatus() == Account.State.ONLINE) {
 392							account. setStatus(Account.State.OFFLINE);
 393							if (statusListener != null) {
 394								statusListener.onStatusChanged(account);
 395							}
 396						}
 397	}
 398
 399	private void acknowledgeStanzaUpTo(int serverCount) {
 400		for (int i = 0; i < mStanzaQueue.size(); ++i) {
 401			if (serverCount >= mStanzaQueue.keyAt(i)) {
 402				if (Config.EXTENDED_SM_LOGGING) {
 403					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 404				}
 405				AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 406				if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 407					MessagePacket packet = (MessagePacket) stanza;
 408					acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 409				}
 410				mStanzaQueue.removeAt(i);
 411				i--;
 412			}
 413		}
 414	}
 415
 416	private Element processPacket(final Tag currentTag, final int packetType)
 417		throws XmlPullParserException, IOException {
 418		Element element;
 419		switch (packetType) {
 420			case PACKET_IQ:
 421				element = new IqPacket();
 422				break;
 423			case PACKET_MESSAGE:
 424				element = new MessagePacket();
 425				break;
 426			case PACKET_PRESENCE:
 427				element = new PresencePacket();
 428				break;
 429			default:
 430				return null;
 431		}
 432		element.setAttributes(currentTag.getAttributes());
 433		Tag nextTag = tagReader.readTag();
 434		if (nextTag == null) {
 435			throw new IOException("interrupted mid tag");
 436		}
 437		while (!nextTag.isEnd(element.getName())) {
 438			if (!nextTag.isNo()) {
 439				final Element child = tagReader.readElement(nextTag);
 440				final String type = currentTag.getAttribute("type");
 441				if (packetType == PACKET_IQ
 442						&& "jingle".equals(child.getName())
 443						&& ("set".equalsIgnoreCase(type) || "get"
 444							.equalsIgnoreCase(type))) {
 445					element = new JinglePacket();
 446					element.setAttributes(currentTag.getAttributes());
 447							}
 448				element.addChild(child);
 449			}
 450			nextTag = tagReader.readTag();
 451			if (nextTag == null) {
 452				throw new IOException("interrupted mid tag");
 453			}
 454		}
 455		if (stanzasReceived == Integer.MAX_VALUE) {
 456			resetStreamId();
 457			throw new IOException("time to restart the session. cant handle >2 billion pcks");
 458		}
 459		++stanzasReceived;
 460		lastPacketReceived = SystemClock.elapsedRealtime();
 461		return element;
 462	}
 463
 464	private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 465		final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 466
 467		if (packet.getId() == null) {
 468			return; // an iq packet without id is definitely invalid
 469		}
 470
 471		if (packet instanceof JinglePacket) {
 472			if (this.jingleListener != null) {
 473				this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
 474			}
 475		} else {
 476			synchronized (this.packetCallbacks) {
 477				if (packetCallbacks.containsKey(packet.getId())) {
 478					final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 479					// Packets to the server should have responses from the server
 480					if (packetCallbackDuple.first.toServer(account)) {
 481						if (packet.fromServer(account)) {
 482							packetCallbackDuple.second.onIqPacketReceived(account, packet);
 483							packetCallbacks.remove(packet.getId());
 484						} else {
 485							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 486						}
 487					} else {
 488						if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 489							packetCallbackDuple.second.onIqPacketReceived(account, packet);
 490							packetCallbacks.remove(packet.getId());
 491						} else {
 492							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 493						}
 494					}
 495				} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 496					this.unregisteredIqListener.onIqPacketReceived(account, packet);
 497				}
 498			}
 499		}
 500	}
 501
 502	private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 503		final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
 504		this.messageListener.onMessagePacketReceived(account, packet);
 505	}
 506
 507	private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 508		PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 509		this.presenceListener.onPresencePacketReceived(account, packet);
 510	}
 511
 512	private void sendStartTLS() throws IOException {
 513		final Tag startTLS = Tag.empty("starttls");
 514		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
 515		tagWriter.writeTag(startTLS);
 516	}
 517
 518	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
 519		tagReader.readTag();
 520		try {
 521			final SSLContext sc = SSLContext.getInstance("TLS");
 522			sc.init(null,new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},mXmppConnectionService.getRNG());
 523			final SSLSocketFactory factory = sc.getSocketFactory();
 524			final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
 525			final InetAddress address = socket == null ? null : socket.getInetAddress();
 526
 527			if (factory == null || address == null || verifier == null) {
 528				throw new IOException("could not setup ssl");
 529			}
 530
 531			final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
 532
 533			if (sslSocket == null) {
 534				throw new IOException("could not initialize ssl socket");
 535			}
 536
 537			final String[] supportProtocols;
 538			final Collection<String> supportedProtocols = new LinkedList<>(
 539					Arrays.asList(sslSocket.getSupportedProtocols()));
 540			supportedProtocols.remove("SSLv3");
 541			supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
 542
 543			sslSocket.setEnabledProtocols(supportProtocols);
 544
 545			final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
 546					sslSocket.getSupportedCipherSuites());
 547			//Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
 548			if (cipherSuites.length > 0) {
 549				sslSocket.setEnabledCipherSuites(cipherSuites);
 550			}
 551
 552			if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
 553				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 554				throw new SecurityException();
 555			}
 556			tagReader.setInputStream(sslSocket.getInputStream());
 557			tagWriter.setOutputStream(sslSocket.getOutputStream());
 558			sendStartStream();
 559			Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
 560			features.encryptionEnabled = true;
 561			processStream(tagReader.readTag());
 562			sslSocket.close();
 563		} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 564			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 565			throw new SecurityException();
 566		}
 567	}
 568
 569	private void processStreamFeatures(final Tag currentTag)
 570		throws XmlPullParserException, IOException {
 571		this.streamFeatures = tagReader.readElement(currentTag);
 572		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 573			sendStartTLS();
 574		} else if (this.streamFeatures.hasChild("register")
 575				&& account.isOptionSet(Account.OPTION_REGISTER)
 576				&& features.encryptionEnabled) {
 577			sendRegistryRequest();
 578		} else if (!this.streamFeatures.hasChild("register")
 579				&& account.isOptionSet(Account.OPTION_REGISTER)) {
 580			changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
 581			disconnect(true);
 582		} else if (this.streamFeatures.hasChild("mechanisms")
 583				&& shouldAuthenticate && features.encryptionEnabled) {
 584			final List<String> mechanisms = extractMechanisms(streamFeatures
 585					.findChild("mechanisms"));
 586			final Element auth = new Element("auth");
 587			auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
 588			if (mechanisms.contains("SCRAM-SHA-1")) {
 589				saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 590			} else if (mechanisms.contains("PLAIN")) {
 591				saslMechanism = new Plain(tagWriter, account);
 592			} else if (mechanisms.contains("DIGEST-MD5")) {
 593				saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 594			}
 595			if (saslMechanism != null) {
 596				final JSONObject keys = account.getKeys();
 597				try {
 598					if (keys.has(Account.PINNED_MECHANISM_KEY) &&
 599							keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
 600						Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 601								" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 602								") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
 603								"). Possible downgrade attack?");
 604						throw new SecurityException();
 605					}
 606				} catch (final JSONException e) {
 607					Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
 608				}
 609				Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 610				auth.setAttribute("mechanism", saslMechanism.getMechanism());
 611				if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 612					auth.setContent(saslMechanism.getClientFirstMessage());
 613				}
 614				tagWriter.writeElement(auth);
 615			} else {
 616				throw new IncompatibleServerException();
 617			}
 618		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 619			if (Config.EXTENDED_SM_LOGGING) {
 620				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
 621			}
 622			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 623			this.tagWriter.writeStanzaAsync(resume);
 624		} else if (needsBinding) {
 625			if (this.streamFeatures.hasChild("bind")) {
 626				sendBindRequest();
 627			} else {
 628				throw new IncompatibleServerException();
 629			}
 630		}
 631	}
 632
 633	private List<String> extractMechanisms(final Element stream) {
 634		final ArrayList<String> mechanisms = new ArrayList<>(stream
 635				.getChildren().size());
 636		for (final Element child : stream.getChildren()) {
 637			mechanisms.add(child.getContent());
 638		}
 639		return mechanisms;
 640	}
 641
 642	private void sendRegistryRequest() {
 643		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 644		register.query("jabber:iq:register");
 645		register.setTo(account.getServer());
 646		sendIqPacket(register, new OnIqPacketReceived() {
 647
 648			@Override
 649			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 650				if (packet.getType() == IqPacket.TYPE.RESULT
 651						&& packet.query().hasChild("username")
 652						&& (packet.query().hasChild("password"))) {
 653					final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
 654					final Element username = new Element("username").setContent(account.getUsername());
 655					final Element password = new Element("password").setContent(account.getPassword());
 656					register.query("jabber:iq:register").addChild(username);
 657					register.query().addChild(password);
 658					sendIqPacket(register, new OnIqPacketReceived() {
 659
 660						@Override
 661						public void onIqPacketReceived(final Account account, final IqPacket packet) {
 662							if (packet.getType() == IqPacket.TYPE.RESULT) {
 663								account.setOption(Account.OPTION_REGISTER,
 664										false);
 665								changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
 666							} else if (packet.hasChild("error")
 667									&& (packet.findChild("error")
 668									.hasChild("conflict"))) {
 669								changeStatus(Account.State.REGISTRATION_CONFLICT);
 670							} else {
 671								changeStatus(Account.State.REGISTRATION_FAILED);
 672								Log.d(Config.LOGTAG, packet.toString());
 673							}
 674							disconnect(true);
 675						}
 676					});
 677				} else {
 678					final Element instructions = packet.query().findChild("instructions");
 679					changeStatus(Account.State.REGISTRATION_FAILED);
 680					disconnect(true);
 681					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 682							+ ": could not register. instructions are"
 683							+ (instructions != null ? instructions.getContent() : ""));
 684				}
 685			}
 686		});
 687	}
 688
 689	private void sendBindRequest() {
 690		while(!mXmppConnectionService.areMessagesInitialized()) {
 691			try {
 692				Thread.sleep(500);
 693			} catch (final InterruptedException ignored) {
 694			}
 695		}
 696		needsBinding = false;
 697		clearIqCallbacks();
 698		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 699		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 700				.addChild("resource").setContent(account.getResource());
 701		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
 702			@Override
 703			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 704				final Element bind = packet.findChild("bind");
 705				if (bind != null) {
 706					final Element jid = bind.findChild("jid");
 707					if (jid != null && jid.getContent() != null) {
 708						try {
 709							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 710						} catch (final InvalidJidException e) {
 711							// TODO: Handle the case where an external JID is technically invalid?
 712						}
 713						if (streamFeatures.hasChild("session")) {
 714							sendStartSession();
 715						} else {
 716							sendPostBindInitialization();
 717						}
 718					} else {
 719						Log.d(Config.LOGTAG,account.getJid()+": disconnecting because of bind failure");
 720						disconnect(true);
 721					}
 722				} else {
 723					Log.d(Config.LOGTAG,account.getJid()+": disconnecting because of bind failure");
 724					disconnect(true);
 725				}
 726			}
 727		});
 728	}
 729
 730	private void clearIqCallbacks() {
 731		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
 732		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 733		synchronized (this.packetCallbacks) {
 734			if (this.packetCallbacks.size() == 0) {
 735				return;
 736			}
 737			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
 738			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
 739			while (iterator.hasNext()) {
 740				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
 741				callbacks.add(entry.second);
 742				iterator.remove();
 743			}
 744		}
 745		for(OnIqPacketReceived callback : callbacks) {
 746			callback.onIqPacketReceived(account,failurePacket);
 747		}
 748		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": done clearing iq callbacks. "+this.packetCallbacks.size()+" left");
 749	}
 750
 751	private void sendStartSession() {
 752		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
 753		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
 754		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
 755			@Override
 756			public void onIqPacketReceived(Account account, IqPacket packet) {
 757				if (packet.getType() == IqPacket.TYPE.RESULT) {
 758					sendPostBindInitialization();
 759				} else {
 760					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
 761					disconnect(true);
 762				}
 763			}
 764		});
 765	}
 766
 767	private void sendPostBindInitialization() {
 768		smVersion = 0;
 769		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
 770			smVersion = 3;
 771		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
 772			smVersion = 2;
 773		}
 774		if (smVersion != 0) {
 775			final EnablePacket enable = new EnablePacket(smVersion);
 776			tagWriter.writeStanzaAsync(enable);
 777			stanzasSent = 0;
 778			mStanzaQueue.clear();
 779		}
 780		features.carbonsEnabled = false;
 781		features.blockListRequested = false;
 782		disco.clear();
 783		sendServiceDiscoveryInfo(account.getServer());
 784		sendServiceDiscoveryInfo(account.getJid().toBareJid());
 785		sendServiceDiscoveryItems(account.getServer());
 786		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
 787		changeStatus(Account.State.ONLINE);
 788		if (bindListener != null) {
 789			bindListener.onBind(account);
 790		}
 791	}
 792
 793	private void sendServiceDiscoveryInfo(final Jid jid) {
 794		if (disco.containsKey(jid)) {
 795			if (account.getServer().equals(jid)) {
 796				enableAdvancedStreamFeatures();
 797			}
 798		} else {
 799			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 800			iq.setTo(jid);
 801			iq.query("http://jabber.org/protocol/disco#info");
 802			this.sendIqPacket(iq, new OnIqPacketReceived() {
 803
 804				@Override
 805				public void onIqPacketReceived(final Account account, final IqPacket packet) {
 806					if (packet.getType() == IqPacket.TYPE.RESULT) {
 807						final List<Element> elements = packet.query().getChildren();
 808						final Info info = new Info();
 809						for (final Element element : elements) {
 810							if (element.getName().equals("identity")) {
 811								String type = element.getAttribute("type");
 812								String category = element.getAttribute("category");
 813								if (type != null && category != null) {
 814									info.identities.add(new Pair<>(category, type));
 815								}
 816							} else if (element.getName().equals("feature")) {
 817								info.features.add(element.getAttribute("var"));
 818							}
 819						}
 820						disco.put(jid, info);
 821						if (account.getServer().equals(jid)) {
 822							enableAdvancedStreamFeatures();
 823							for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
 824								listener.onAdvancedStreamFeaturesAvailable(account);
 825							}
 826						}
 827					} else {
 828						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco info for "+jid.toString());
 829					}
 830				}
 831			});
 832		}
 833	}
 834
 835	private void enableAdvancedStreamFeatures() {
 836		if (getFeatures().carbons() && !features.carbonsEnabled) {
 837			sendEnableCarbons();
 838		}
 839		if (getFeatures().blocking() && !features.blockListRequested) {
 840			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": Requesting block list");
 841			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
 842		}
 843	}
 844
 845	private void sendServiceDiscoveryItems(final Jid server) {
 846		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 847		iq.setTo(server.toDomainJid());
 848		iq.query("http://jabber.org/protocol/disco#items");
 849		this.sendIqPacket(iq, new OnIqPacketReceived() {
 850
 851			@Override
 852			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 853				if (packet.getType() == IqPacket.TYPE.RESULT) {
 854					final List<Element> elements = packet.query().getChildren();
 855					for (final Element element : elements) {
 856						if (element.getName().equals("item")) {
 857							final Jid jid = element.getAttributeAsJid("jid");
 858							if (jid != null && !jid.equals(account.getServer())) {
 859								sendServiceDiscoveryInfo(jid);
 860							}
 861						}
 862					}
 863				} else {
 864					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco items of "+server);
 865				}
 866			}
 867		});
 868	}
 869
 870	private void sendEnableCarbons() {
 871		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 872		iq.addChild("enable", "urn:xmpp:carbons:2");
 873		this.sendIqPacket(iq, new OnIqPacketReceived() {
 874
 875			@Override
 876			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 877				if (!packet.hasChild("error")) {
 878					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 879							+ ": successfully enabled carbons");
 880					features.carbonsEnabled = true;
 881				} else {
 882					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 883							+ ": error enableing carbons " + packet.toString());
 884				}
 885			}
 886		});
 887	}
 888
 889	private void processStreamError(final Tag currentTag)
 890		throws XmlPullParserException, IOException {
 891		final Element streamError = tagReader.readElement(currentTag);
 892		if (streamError != null && streamError.hasChild("conflict")) {
 893			final String resource = account.getResource().split("\\.")[0];
 894			account.setResource(resource + "." + nextRandomId());
 895			Log.d(Config.LOGTAG,
 896					account.getJid().toBareJid() + ": switching resource due to conflict ("
 897					+ account.getResource() + ")");
 898		} else if (streamError != null) {
 899			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
 900		}
 901	}
 902
 903	private void sendStartStream() throws IOException {
 904		final Tag stream = Tag.start("stream:stream");
 905		stream.setAttribute("from", account.getJid().toBareJid().toString());
 906		stream.setAttribute("to", account.getServer().toString());
 907		stream.setAttribute("version", "1.0");
 908		stream.setAttribute("xml:lang", "en");
 909		stream.setAttribute("xmlns", "jabber:client");
 910		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
 911		tagWriter.writeTag(stream);
 912	}
 913
 914	private String nextRandomId() {
 915		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
 916	}
 917
 918	public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
 919		packet.setFrom(account.getJid());
 920		this.sendUnmodifiedIqPacket(packet, callback);
 921
 922	}
 923
 924	private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
 925		if (packet.getId() == null) {
 926			final String id = nextRandomId();
 927			packet.setAttribute("id", id);
 928		}
 929		if (callback != null) {
 930			synchronized (this.packetCallbacks) {
 931				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
 932			}
 933		}
 934		this.sendPacket(packet);
 935	}
 936
 937	public void sendMessagePacket(final MessagePacket packet) {
 938		this.sendPacket(packet);
 939	}
 940
 941	public void sendPresencePacket(final PresencePacket packet) {
 942		this.sendPacket(packet);
 943	}
 944
 945	private synchronized void sendPacket(final AbstractStanza packet) {
 946		if (stanzasSent == Integer.MAX_VALUE) {
 947			resetStreamId();
 948			disconnect(true);
 949			return;
 950		}
 951		final String name = packet.getName();
 952		tagWriter.writeStanzaAsync(packet);
 953		if (packet instanceof AbstractAcknowledgeableStanza) {
 954			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
 955			++stanzasSent;
 956			this.mStanzaQueue.put(stanzasSent, stanza);
 957			if (stanza instanceof MessagePacket && stanza.getId() != null && this.streamId != null) {
 958				if (Config.EXTENDED_SM_LOGGING) {
 959					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
 960				}
 961				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
 962			}
 963		}
 964	}
 965
 966	public void sendPing() {
 967		if (streamFeatures.hasChild("sm")) {
 968			tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 969		} else {
 970			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 971			iq.setFrom(account.getJid());
 972			iq.addChild("ping", "urn:xmpp:ping");
 973			this.sendIqPacket(iq, null);
 974		}
 975		this.lastPingSent = SystemClock.elapsedRealtime();
 976	}
 977
 978	public void setOnMessagePacketReceivedListener(
 979			final OnMessagePacketReceived listener) {
 980		this.messageListener = listener;
 981			}
 982
 983	public void setOnUnregisteredIqPacketReceivedListener(
 984			final OnIqPacketReceived listener) {
 985		this.unregisteredIqListener = listener;
 986			}
 987
 988	public void setOnPresencePacketReceivedListener(
 989			final OnPresencePacketReceived listener) {
 990		this.presenceListener = listener;
 991			}
 992
 993	public void setOnJinglePacketReceivedListener(
 994			final OnJinglePacketReceived listener) {
 995		this.jingleListener = listener;
 996			}
 997
 998	public void setOnStatusChangedListener(final OnStatusChanged listener) {
 999		this.statusListener = listener;
1000	}
1001
1002	public void setOnBindListener(final OnBindListener listener) {
1003		this.bindListener = listener;
1004	}
1005
1006	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1007		this.acknowledgedListener = listener;
1008	}
1009
1010	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1011		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1012			this.advancedStreamFeaturesLoadedListeners.add(listener);
1013		}
1014	}
1015
1016	public void disconnect(final boolean force) {
1017		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
1018		try {
1019			if (force) {
1020				socket.close();
1021				return;
1022			}
1023			new Thread(new Runnable() {
1024
1025				@Override
1026				public void run() {
1027					if (tagWriter.isActive()) {
1028						tagWriter.finish();
1029						try {
1030							while (!tagWriter.finished() && socket.isConnected()) {
1031								Log.d(Config.LOGTAG, "not yet finished");
1032								Thread.sleep(100);
1033							}
1034							tagWriter.writeTag(Tag.end("stream:stream"));
1035							socket.close();
1036						} catch (final IOException e) {
1037							Log.d(Config.LOGTAG,
1038									"io exception during disconnect");
1039						} catch (final InterruptedException e) {
1040							Log.d(Config.LOGTAG, "interrupted");
1041						}
1042					}
1043				}
1044			}).start();
1045		} catch (final IOException e) {
1046			Log.d(Config.LOGTAG, "io exception during disconnect");
1047		}
1048	}
1049
1050	public void resetStreamId() {
1051		this.streamId = null;
1052	}
1053
1054	public List<Jid> findDiscoItemsByFeature(final String feature) {
1055		final List<Jid> items = new ArrayList<>();
1056		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1057			if (cursor.getValue().features.contains(feature)) {
1058				items.add(cursor.getKey());
1059			}
1060		}
1061		return items;
1062	}
1063
1064	public Jid findDiscoItemByFeature(final String feature) {
1065		final List<Jid> items = findDiscoItemsByFeature(feature);
1066		if (items.size() >= 1) {
1067			return items.get(0);
1068		}
1069		return null;
1070	}
1071
1072	public void r() {
1073		this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1074	}
1075
1076	public String getMucServer() {
1077		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1078			final Info value = cursor.getValue();
1079			if (value.features.contains("http://jabber.org/protocol/muc")
1080					&& !value.features.contains("jabber:iq:gateway")
1081					&& !value.identities.contains(new Pair<>("conference","irc"))) {
1082				return cursor.getKey().toString();
1083			}
1084		}
1085		return null;
1086	}
1087
1088	public int getTimeToNextAttempt() {
1089		final int interval = (int) (25 * Math.pow(1.5, attempt));
1090		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1091		return interval - secondsSinceLast;
1092	}
1093
1094	public int getAttempt() {
1095		return this.attempt;
1096	}
1097
1098	public Features getFeatures() {
1099		return this.features;
1100	}
1101
1102	public long getLastSessionEstablished() {
1103		final long diff;
1104		if (this.lastSessionStarted == 0) {
1105			diff = SystemClock.elapsedRealtime() - this.lastConnect;
1106		} else {
1107			diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1108		}
1109		return System.currentTimeMillis() - diff;
1110	}
1111
1112	public long getLastConnect() {
1113		return this.lastConnect;
1114	}
1115
1116	public long getLastPingSent() {
1117		return this.lastPingSent;
1118	}
1119
1120	public long getLastPacketReceived() {
1121		return this.lastPacketReceived;
1122	}
1123
1124	public void sendActive() {
1125		this.sendPacket(new ActivePacket());
1126	}
1127
1128	public void sendInactive() {
1129		this.sendPacket(new InactivePacket());
1130	}
1131
1132	public void resetAttemptCount() {
1133		this.attempt = 0;
1134		this.lastConnect = 0;
1135	}
1136
1137	private class Info {
1138		public final ArrayList<String> features = new ArrayList<>();
1139		public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1140	}
1141
1142	private class UnauthorizedException extends IOException {
1143
1144	}
1145
1146	private class SecurityException extends IOException {
1147
1148	}
1149
1150	private class IncompatibleServerException extends IOException {
1151
1152	}
1153
1154	public class Features {
1155		XmppConnection connection;
1156		private boolean carbonsEnabled = false;
1157		private boolean encryptionEnabled = false;
1158		private boolean blockListRequested = false;
1159
1160		public Features(final XmppConnection connection) {
1161			this.connection = connection;
1162		}
1163
1164		private boolean hasDiscoFeature(final Jid server, final String feature) {
1165			return connection.disco.containsKey(server) &&
1166				connection.disco.get(server).features.contains(feature);
1167		}
1168
1169		public boolean carbons() {
1170			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1171		}
1172
1173		public boolean blocking() {
1174			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1175		}
1176
1177		public boolean register() {
1178			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1179		}
1180
1181		public boolean sm() {
1182			return streamId != null
1183					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1184		}
1185
1186		public boolean csi() {
1187			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1188		}
1189
1190		public boolean pep() {
1191			final Pair<String,String> needle = new Pair<>("pubsub","pep");
1192			Info info = disco.get(account.getServer());
1193			if (info != null && info.identities.contains(needle)) {
1194				return true;
1195			} else {
1196				info = disco.get(account.getJid().toBareJid());
1197				return info != null && info.identities.contains(needle);
1198			}
1199		}
1200
1201		public boolean mam() {
1202			if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1203				return true;
1204			} else {
1205				return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1206			}
1207		}
1208
1209		public boolean advancedStreamFeaturesLoaded() {
1210			return disco.containsKey(account.getServer());
1211		}
1212
1213		public boolean rosterVersioning() {
1214			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1215		}
1216
1217		public void setBlockListRequested(boolean value) {
1218			this.blockListRequested = value;
1219		}
1220
1221		public boolean httpUpload() {
1222			return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1223		}
1224	}
1225
1226	private IqGenerator getIqGenerator() {
1227		return mXmppConnectionService.getIqGenerator();
1228	}
1229}