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(),mXmppConnectionService);
 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.stanzasReceived = 0;
 322								final RequestPacket r = new RequestPacket(smVersion);
 323								tagWriter.writeStanzaAsync(r);
 324							} else if (nextTag.isStart("resumed")) {
 325								lastPacketReceived = SystemClock.elapsedRealtime();
 326								final Element resumed = tagReader.readElement(nextTag);
 327								final String h = resumed.getAttribute("h");
 328								try {
 329									final int serverCount = Integer.parseInt(h);
 330									if (serverCount != stanzasSent) {
 331										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 332												+ ": session resumed with lost packages");
 333										stanzasSent = serverCount;
 334									} else {
 335										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
 336									}
 337									acknowledgeStanzaUpTo(serverCount);
 338									ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 339									for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
 340										failedStanzas.add(mStanzaQueue.valueAt(i));
 341									}
 342									mStanzaQueue.clear();
 343									Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
 344									for(AbstractAcknowledgeableStanza packet : failedStanzas) {
 345										if (packet instanceof MessagePacket) {
 346											MessagePacket message = (MessagePacket) packet;
 347											mXmppConnectionService.markMessage(account,
 348													message.getTo().toBareJid(),
 349													message.getId(),
 350													Message.STATUS_UNSEND);
 351										}
 352										sendPacket(packet);
 353									}
 354								} catch (final NumberFormatException ignored) {
 355								}
 356								Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
 357								changeStatus(Account.State.ONLINE);
 358							} else if (nextTag.isStart("r")) {
 359								tagReader.readElement(nextTag);
 360								if (Config.EXTENDED_SM_LOGGING) {
 361									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 362								}
 363								final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 364								tagWriter.writeStanzaAsync(ack);
 365							} else if (nextTag.isStart("a")) {
 366								final Element ack = tagReader.readElement(nextTag);
 367								lastPacketReceived = SystemClock.elapsedRealtime();
 368								try {
 369									final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 370									acknowledgeStanzaUpTo(serverSequence);
 371								} catch (NumberFormatException e) {
 372									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
 373								}
 374							} else if (nextTag.isStart("failed")) {
 375								tagReader.readElement(nextTag);
 376								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
 377								streamId = null;
 378								if (account.getStatus() != Account.State.ONLINE) {
 379									sendBindRequest();
 380								}
 381							} else if (nextTag.isStart("iq")) {
 382								processIq(nextTag);
 383							} else if (nextTag.isStart("message")) {
 384								processMessage(nextTag);
 385							} else if (nextTag.isStart("presence")) {
 386								processPresence(nextTag);
 387							}
 388							nextTag = tagReader.readTag();
 389						}
 390						if (account.getStatus() == Account.State.ONLINE) {
 391							account. setStatus(Account.State.OFFLINE);
 392							if (statusListener != null) {
 393								statusListener.onStatusChanged(account);
 394							}
 395						}
 396	}
 397
 398	private void acknowledgeStanzaUpTo(int serverCount) {
 399		for (int i = 0; i < mStanzaQueue.size(); ++i) {
 400			if (serverCount >= mStanzaQueue.keyAt(i)) {
 401				if (Config.EXTENDED_SM_LOGGING) {
 402					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 403				}
 404				AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 405				if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 406					MessagePacket packet = (MessagePacket) stanza;
 407					acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 408				}
 409				mStanzaQueue.removeAt(i);
 410				i--;
 411			}
 412		}
 413	}
 414
 415	private Element processPacket(final Tag currentTag, final int packetType)
 416		throws XmlPullParserException, IOException {
 417		Element element;
 418		switch (packetType) {
 419			case PACKET_IQ:
 420				element = new IqPacket();
 421				break;
 422			case PACKET_MESSAGE:
 423				element = new MessagePacket();
 424				break;
 425			case PACKET_PRESENCE:
 426				element = new PresencePacket();
 427				break;
 428			default:
 429				return null;
 430		}
 431		element.setAttributes(currentTag.getAttributes());
 432		Tag nextTag = tagReader.readTag();
 433		if (nextTag == null) {
 434			throw new IOException("interrupted mid tag");
 435		}
 436		while (!nextTag.isEnd(element.getName())) {
 437			if (!nextTag.isNo()) {
 438				final Element child = tagReader.readElement(nextTag);
 439				final String type = currentTag.getAttribute("type");
 440				if (packetType == PACKET_IQ
 441						&& "jingle".equals(child.getName())
 442						&& ("set".equalsIgnoreCase(type) || "get"
 443							.equalsIgnoreCase(type))) {
 444					element = new JinglePacket();
 445					element.setAttributes(currentTag.getAttributes());
 446							}
 447				element.addChild(child);
 448			}
 449			nextTag = tagReader.readTag();
 450			if (nextTag == null) {
 451				throw new IOException("interrupted mid tag");
 452			}
 453		}
 454		if (stanzasReceived == Integer.MAX_VALUE) {
 455			resetStreamId();
 456			throw new IOException("time to restart the session. cant handle >2 billion pcks");
 457		}
 458		++stanzasReceived;
 459		lastPacketReceived = SystemClock.elapsedRealtime();
 460		return element;
 461	}
 462
 463	private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 464		final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 465
 466		if (packet.getId() == null) {
 467			return; // an iq packet without id is definitely invalid
 468		}
 469
 470		if (packet instanceof JinglePacket) {
 471			if (this.jingleListener != null) {
 472				this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
 473			}
 474		} else {
 475			OnIqPacketReceived callback = null;
 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							callback = packetCallbackDuple.second;
 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							callback = packetCallbackDuple.second;
 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					callback = this.unregisteredIqListener;
 497				}
 498			}
 499			if (callback != null) {
 500				callback.onIqPacketReceived(account,packet);
 501			}
 502		}
 503	}
 504
 505	private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 506		final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
 507		this.messageListener.onMessagePacketReceived(account, packet);
 508	}
 509
 510	private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 511		PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 512		this.presenceListener.onPresencePacketReceived(account, packet);
 513	}
 514
 515	private void sendStartTLS() throws IOException {
 516		final Tag startTLS = Tag.empty("starttls");
 517		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
 518		tagWriter.writeTag(startTLS);
 519	}
 520
 521	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
 522		tagReader.readTag();
 523		try {
 524			final SSLContext sc = SSLContext.getInstance("TLS");
 525			sc.init(null,new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},mXmppConnectionService.getRNG());
 526			final SSLSocketFactory factory = sc.getSocketFactory();
 527			final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
 528			final InetAddress address = socket == null ? null : socket.getInetAddress();
 529
 530			if (factory == null || address == null || verifier == null) {
 531				throw new IOException("could not setup ssl");
 532			}
 533
 534			final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
 535
 536			if (sslSocket == null) {
 537				throw new IOException("could not initialize ssl socket");
 538			}
 539
 540			final String[] supportProtocols;
 541			final Collection<String> supportedProtocols = new LinkedList<>(
 542					Arrays.asList(sslSocket.getSupportedProtocols()));
 543			supportedProtocols.remove("SSLv3");
 544			supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
 545
 546			sslSocket.setEnabledProtocols(supportProtocols);
 547
 548			final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
 549					sslSocket.getSupportedCipherSuites());
 550			//Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
 551			if (cipherSuites.length > 0) {
 552				sslSocket.setEnabledCipherSuites(cipherSuites);
 553			}
 554
 555			if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
 556				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 557				throw new SecurityException();
 558			}
 559			tagReader.setInputStream(sslSocket.getInputStream());
 560			tagWriter.setOutputStream(sslSocket.getOutputStream());
 561			sendStartStream();
 562			Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
 563			features.encryptionEnabled = true;
 564			processStream(tagReader.readTag());
 565			sslSocket.close();
 566		} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 567			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 568			throw new SecurityException();
 569		}
 570	}
 571
 572	private void processStreamFeatures(final Tag currentTag)
 573		throws XmlPullParserException, IOException {
 574		this.streamFeatures = tagReader.readElement(currentTag);
 575		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 576			sendStartTLS();
 577		} else if (this.streamFeatures.hasChild("register")
 578				&& account.isOptionSet(Account.OPTION_REGISTER)
 579				&& features.encryptionEnabled) {
 580			sendRegistryRequest();
 581		} else if (!this.streamFeatures.hasChild("register")
 582				&& account.isOptionSet(Account.OPTION_REGISTER)) {
 583			changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
 584			disconnect(true);
 585		} else if (this.streamFeatures.hasChild("mechanisms")
 586				&& shouldAuthenticate && features.encryptionEnabled) {
 587			final List<String> mechanisms = extractMechanisms(streamFeatures
 588					.findChild("mechanisms"));
 589			final Element auth = new Element("auth");
 590			auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
 591			if (mechanisms.contains("SCRAM-SHA-1")) {
 592				saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 593			} else if (mechanisms.contains("PLAIN")) {
 594				saslMechanism = new Plain(tagWriter, account);
 595			} else if (mechanisms.contains("DIGEST-MD5")) {
 596				saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 597			}
 598			if (saslMechanism != null) {
 599				final JSONObject keys = account.getKeys();
 600				try {
 601					if (keys.has(Account.PINNED_MECHANISM_KEY) &&
 602							keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
 603						Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 604								" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 605								") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
 606								"). Possible downgrade attack?");
 607						throw new SecurityException();
 608					}
 609				} catch (final JSONException e) {
 610					Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
 611				}
 612				Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 613				auth.setAttribute("mechanism", saslMechanism.getMechanism());
 614				if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 615					auth.setContent(saslMechanism.getClientFirstMessage());
 616				}
 617				tagWriter.writeElement(auth);
 618			} else {
 619				throw new IncompatibleServerException();
 620			}
 621		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 622			if (Config.EXTENDED_SM_LOGGING) {
 623				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
 624			}
 625			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 626			this.tagWriter.writeStanzaAsync(resume);
 627		} else if (needsBinding) {
 628			if (this.streamFeatures.hasChild("bind")) {
 629				sendBindRequest();
 630			} else {
 631				throw new IncompatibleServerException();
 632			}
 633		}
 634	}
 635
 636	private List<String> extractMechanisms(final Element stream) {
 637		final ArrayList<String> mechanisms = new ArrayList<>(stream
 638				.getChildren().size());
 639		for (final Element child : stream.getChildren()) {
 640			mechanisms.add(child.getContent());
 641		}
 642		return mechanisms;
 643	}
 644
 645	private void sendRegistryRequest() {
 646		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 647		register.query("jabber:iq:register");
 648		register.setTo(account.getServer());
 649		sendIqPacket(register, new OnIqPacketReceived() {
 650
 651			@Override
 652			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 653				if (packet.getType() == IqPacket.TYPE.RESULT
 654						&& packet.query().hasChild("username")
 655						&& (packet.query().hasChild("password"))) {
 656					final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
 657					final Element username = new Element("username").setContent(account.getUsername());
 658					final Element password = new Element("password").setContent(account.getPassword());
 659					register.query("jabber:iq:register").addChild(username);
 660					register.query().addChild(password);
 661					sendIqPacket(register, new OnIqPacketReceived() {
 662
 663						@Override
 664						public void onIqPacketReceived(final Account account, final IqPacket packet) {
 665							if (packet.getType() == IqPacket.TYPE.RESULT) {
 666								account.setOption(Account.OPTION_REGISTER,
 667										false);
 668								changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
 669							} else if (packet.hasChild("error")
 670									&& (packet.findChild("error")
 671									.hasChild("conflict"))) {
 672								changeStatus(Account.State.REGISTRATION_CONFLICT);
 673							} else {
 674								changeStatus(Account.State.REGISTRATION_FAILED);
 675								Log.d(Config.LOGTAG, packet.toString());
 676							}
 677							disconnect(true);
 678						}
 679					});
 680				} else {
 681					final Element instructions = packet.query().findChild("instructions");
 682					changeStatus(Account.State.REGISTRATION_FAILED);
 683					disconnect(true);
 684					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 685							+ ": could not register. instructions are"
 686							+ (instructions != null ? instructions.getContent() : ""));
 687				}
 688			}
 689		});
 690	}
 691
 692	private void sendBindRequest() {
 693		while(!mXmppConnectionService.areMessagesInitialized()) {
 694			try {
 695				Thread.sleep(500);
 696			} catch (final InterruptedException ignored) {
 697			}
 698		}
 699		needsBinding = false;
 700		clearIqCallbacks();
 701		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 702		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 703				.addChild("resource").setContent(account.getResource());
 704		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
 705			@Override
 706			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 707				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 708					return;
 709				}
 710				final Element bind = packet.findChild("bind");
 711				if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
 712					final Element jid = bind.findChild("jid");
 713					if (jid != null && jid.getContent() != null) {
 714						try {
 715							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 716						} catch (final InvalidJidException e) {
 717							// TODO: Handle the case where an external JID is technically invalid?
 718						}
 719						if (streamFeatures.hasChild("session")) {
 720							sendStartSession();
 721						} else {
 722							sendPostBindInitialization();
 723						}
 724					} else {
 725						Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 726						disconnect(true);
 727					}
 728				} else {
 729					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 730					disconnect(true);
 731				}
 732			}
 733		});
 734	}
 735
 736	private void clearIqCallbacks() {
 737		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
 738		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 739		synchronized (this.packetCallbacks) {
 740			if (this.packetCallbacks.size() == 0) {
 741				return;
 742			}
 743			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
 744			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
 745			while (iterator.hasNext()) {
 746				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
 747				callbacks.add(entry.second);
 748				iterator.remove();
 749			}
 750		}
 751		for(OnIqPacketReceived callback : callbacks) {
 752			callback.onIqPacketReceived(account,failurePacket);
 753		}
 754		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
 755	}
 756
 757	private void sendStartSession() {
 758		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
 759		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
 760		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
 761			@Override
 762			public void onIqPacketReceived(Account account, IqPacket packet) {
 763				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 764					return;
 765				} else if (packet.getType() == IqPacket.TYPE.RESULT) {
 766					sendPostBindInitialization();
 767				} else {
 768					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
 769					disconnect(true);
 770				}
 771			}
 772		});
 773	}
 774
 775	private void sendPostBindInitialization() {
 776		smVersion = 0;
 777		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
 778			smVersion = 3;
 779		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
 780			smVersion = 2;
 781		}
 782		if (smVersion != 0) {
 783			final EnablePacket enable = new EnablePacket(smVersion);
 784			tagWriter.writeStanzaAsync(enable);
 785			stanzasSent = 0;
 786			mStanzaQueue.clear();
 787		}
 788		features.carbonsEnabled = false;
 789		features.blockListRequested = false;
 790		disco.clear();
 791		sendServiceDiscoveryInfo(account.getServer());
 792		sendServiceDiscoveryInfo(account.getJid().toBareJid());
 793		sendServiceDiscoveryItems(account.getServer());
 794		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
 795		this.lastSessionStarted = SystemClock.elapsedRealtime();
 796		changeStatus(Account.State.ONLINE);
 797		if (bindListener != null) {
 798			bindListener.onBind(account);
 799		}
 800	}
 801
 802	private void sendServiceDiscoveryInfo(final Jid jid) {
 803		if (disco.containsKey(jid)) {
 804			if (account.getServer().equals(jid)) {
 805				enableAdvancedStreamFeatures();
 806			}
 807		} else {
 808			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 809			iq.setTo(jid);
 810			iq.query("http://jabber.org/protocol/disco#info");
 811			this.sendIqPacket(iq, new OnIqPacketReceived() {
 812
 813				@Override
 814				public void onIqPacketReceived(final Account account, final IqPacket packet) {
 815					if (packet.getType() == IqPacket.TYPE.RESULT) {
 816						final List<Element> elements = packet.query().getChildren();
 817						final Info info = new Info();
 818						for (final Element element : elements) {
 819							if (element.getName().equals("identity")) {
 820								String type = element.getAttribute("type");
 821								String category = element.getAttribute("category");
 822								if (type != null && category != null) {
 823									info.identities.add(new Pair<>(category, type));
 824								}
 825							} else if (element.getName().equals("feature")) {
 826								info.features.add(element.getAttribute("var"));
 827							}
 828						}
 829						disco.put(jid, info);
 830						if (account.getServer().equals(jid)) {
 831							enableAdvancedStreamFeatures();
 832							for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
 833								listener.onAdvancedStreamFeaturesAvailable(account);
 834							}
 835						}
 836					} else {
 837						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco info for "+jid.toString());
 838					}
 839				}
 840			});
 841		}
 842	}
 843
 844	private void enableAdvancedStreamFeatures() {
 845		if (getFeatures().carbons() && !features.carbonsEnabled) {
 846			sendEnableCarbons();
 847		}
 848		if (getFeatures().blocking() && !features.blockListRequested) {
 849			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": Requesting block list");
 850			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
 851		}
 852	}
 853
 854	private void sendServiceDiscoveryItems(final Jid server) {
 855		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 856		iq.setTo(server.toDomainJid());
 857		iq.query("http://jabber.org/protocol/disco#items");
 858		this.sendIqPacket(iq, new OnIqPacketReceived() {
 859
 860			@Override
 861			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 862				if (packet.getType() == IqPacket.TYPE.RESULT) {
 863					final List<Element> elements = packet.query().getChildren();
 864					for (final Element element : elements) {
 865						if (element.getName().equals("item")) {
 866							final Jid jid = element.getAttributeAsJid("jid");
 867							if (jid != null && !jid.equals(account.getServer())) {
 868								sendServiceDiscoveryInfo(jid);
 869							}
 870						}
 871					}
 872				} else {
 873					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco items of "+server);
 874				}
 875			}
 876		});
 877	}
 878
 879	private void sendEnableCarbons() {
 880		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 881		iq.addChild("enable", "urn:xmpp:carbons:2");
 882		this.sendIqPacket(iq, new OnIqPacketReceived() {
 883
 884			@Override
 885			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 886				if (!packet.hasChild("error")) {
 887					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 888							+ ": successfully enabled carbons");
 889					features.carbonsEnabled = true;
 890				} else {
 891					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 892							+ ": error enableing carbons " + packet.toString());
 893				}
 894			}
 895		});
 896	}
 897
 898	private void processStreamError(final Tag currentTag)
 899		throws XmlPullParserException, IOException {
 900		final Element streamError = tagReader.readElement(currentTag);
 901		if (streamError != null && streamError.hasChild("conflict")) {
 902			final String resource = account.getResource().split("\\.")[0];
 903			account.setResource(resource + "." + nextRandomId());
 904			Log.d(Config.LOGTAG,
 905					account.getJid().toBareJid() + ": switching resource due to conflict ("
 906					+ account.getResource() + ")");
 907		} else if (streamError != null) {
 908			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
 909		}
 910	}
 911
 912	private void sendStartStream() throws IOException {
 913		final Tag stream = Tag.start("stream:stream");
 914		stream.setAttribute("from", account.getJid().toBareJid().toString());
 915		stream.setAttribute("to", account.getServer().toString());
 916		stream.setAttribute("version", "1.0");
 917		stream.setAttribute("xml:lang", "en");
 918		stream.setAttribute("xmlns", "jabber:client");
 919		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
 920		tagWriter.writeTag(stream);
 921	}
 922
 923	private String nextRandomId() {
 924		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
 925	}
 926
 927	public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
 928		packet.setFrom(account.getJid());
 929		this.sendUnmodifiedIqPacket(packet, callback);
 930
 931	}
 932
 933	private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
 934		if (packet.getId() == null) {
 935			final String id = nextRandomId();
 936			packet.setAttribute("id", id);
 937		}
 938		if (callback != null) {
 939			synchronized (this.packetCallbacks) {
 940				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
 941			}
 942		}
 943		this.sendPacket(packet);
 944	}
 945
 946	public void sendMessagePacket(final MessagePacket packet) {
 947		this.sendPacket(packet);
 948	}
 949
 950	public void sendPresencePacket(final PresencePacket packet) {
 951		this.sendPacket(packet);
 952	}
 953
 954	private synchronized void sendPacket(final AbstractStanza packet) {
 955		if (stanzasSent == Integer.MAX_VALUE) {
 956			resetStreamId();
 957			disconnect(true);
 958			return;
 959		}
 960		final String name = packet.getName();
 961		tagWriter.writeStanzaAsync(packet);
 962		if (packet instanceof AbstractAcknowledgeableStanza) {
 963			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
 964			++stanzasSent;
 965			this.mStanzaQueue.put(stanzasSent, stanza);
 966			if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
 967				if (Config.EXTENDED_SM_LOGGING) {
 968					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
 969				}
 970				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
 971			}
 972		}
 973	}
 974
 975	public void sendPing() {
 976		if (streamFeatures.hasChild("sm")) {
 977			tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 978		} else {
 979			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 980			iq.setFrom(account.getJid());
 981			iq.addChild("ping", "urn:xmpp:ping");
 982			this.sendIqPacket(iq, null);
 983		}
 984		this.lastPingSent = SystemClock.elapsedRealtime();
 985	}
 986
 987	public void setOnMessagePacketReceivedListener(
 988			final OnMessagePacketReceived listener) {
 989		this.messageListener = listener;
 990			}
 991
 992	public void setOnUnregisteredIqPacketReceivedListener(
 993			final OnIqPacketReceived listener) {
 994		this.unregisteredIqListener = listener;
 995			}
 996
 997	public void setOnPresencePacketReceivedListener(
 998			final OnPresencePacketReceived listener) {
 999		this.presenceListener = listener;
1000			}
1001
1002	public void setOnJinglePacketReceivedListener(
1003			final OnJinglePacketReceived listener) {
1004		this.jingleListener = listener;
1005			}
1006
1007	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1008		this.statusListener = listener;
1009	}
1010
1011	public void setOnBindListener(final OnBindListener listener) {
1012		this.bindListener = listener;
1013	}
1014
1015	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1016		this.acknowledgedListener = listener;
1017	}
1018
1019	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1020		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1021			this.advancedStreamFeaturesLoadedListeners.add(listener);
1022		}
1023	}
1024
1025	public void disconnect(final boolean force) {
1026		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
1027		try {
1028			if (force) {
1029				socket.close();
1030				return;
1031			}
1032			new Thread(new Runnable() {
1033
1034				@Override
1035				public void run() {
1036					if (tagWriter.isActive()) {
1037						tagWriter.finish();
1038						try {
1039							int i = 0;
1040							boolean warned = false;
1041							while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1042								if (!warned) {
1043									Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1044									warned = true;
1045								}
1046								Thread.sleep(200);
1047								i++;
1048							}
1049							if (warned) {
1050								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1051							}
1052							tagWriter.writeTag(Tag.end("stream:stream"));
1053							socket.close();
1054						} catch (final IOException e) {
1055							Log.d(Config.LOGTAG,"io exception during disconnect");
1056						} catch (final InterruptedException e) {
1057							Log.d(Config.LOGTAG, "interrupted");
1058						}
1059					}
1060				}
1061			}).start();
1062		} catch (final IOException e) {
1063			Log.d(Config.LOGTAG, "io exception during disconnect");
1064		}
1065	}
1066
1067	public void resetStreamId() {
1068		this.streamId = null;
1069	}
1070
1071	public List<Jid> findDiscoItemsByFeature(final String feature) {
1072		final List<Jid> items = new ArrayList<>();
1073		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1074			if (cursor.getValue().features.contains(feature)) {
1075				items.add(cursor.getKey());
1076			}
1077		}
1078		return items;
1079	}
1080
1081	public Jid findDiscoItemByFeature(final String feature) {
1082		final List<Jid> items = findDiscoItemsByFeature(feature);
1083		if (items.size() >= 1) {
1084			return items.get(0);
1085		}
1086		return null;
1087	}
1088
1089	public void r() {
1090		this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1091	}
1092
1093	public String getMucServer() {
1094		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1095			final Info value = cursor.getValue();
1096			if (value.features.contains("http://jabber.org/protocol/muc")
1097					&& !value.features.contains("jabber:iq:gateway")
1098					&& !value.identities.contains(new Pair<>("conference","irc"))) {
1099				return cursor.getKey().toString();
1100			}
1101		}
1102		return null;
1103	}
1104
1105	public int getTimeToNextAttempt() {
1106		final int interval = (int) (25 * Math.pow(1.5, attempt));
1107		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1108		return interval - secondsSinceLast;
1109	}
1110
1111	public int getAttempt() {
1112		return this.attempt;
1113	}
1114
1115	public Features getFeatures() {
1116		return this.features;
1117	}
1118
1119	public long getLastSessionEstablished() {
1120		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1121		return System.currentTimeMillis() - diff;
1122	}
1123
1124	public long getLastConnect() {
1125		return this.lastConnect;
1126	}
1127
1128	public long getLastPingSent() {
1129		return this.lastPingSent;
1130	}
1131
1132	public long getLastPacketReceived() {
1133		return this.lastPacketReceived;
1134	}
1135
1136	public void sendActive() {
1137		this.sendPacket(new ActivePacket());
1138	}
1139
1140	public void sendInactive() {
1141		this.sendPacket(new InactivePacket());
1142	}
1143
1144	public void resetAttemptCount() {
1145		this.attempt = 0;
1146		this.lastConnect = 0;
1147	}
1148
1149	private class Info {
1150		public final ArrayList<String> features = new ArrayList<>();
1151		public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1152	}
1153
1154	private class UnauthorizedException extends IOException {
1155
1156	}
1157
1158	private class SecurityException extends IOException {
1159
1160	}
1161
1162	private class IncompatibleServerException extends IOException {
1163
1164	}
1165
1166	public class Features {
1167		XmppConnection connection;
1168		private boolean carbonsEnabled = false;
1169		private boolean encryptionEnabled = false;
1170		private boolean blockListRequested = false;
1171
1172		public Features(final XmppConnection connection) {
1173			this.connection = connection;
1174		}
1175
1176		private boolean hasDiscoFeature(final Jid server, final String feature) {
1177			return connection.disco.containsKey(server) &&
1178				connection.disco.get(server).features.contains(feature);
1179		}
1180
1181		public boolean carbons() {
1182			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1183		}
1184
1185		public boolean blocking() {
1186			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1187		}
1188
1189		public boolean register() {
1190			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1191		}
1192
1193		public boolean sm() {
1194			return streamId != null
1195					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1196		}
1197
1198		public boolean csi() {
1199			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1200		}
1201
1202		public boolean pep() {
1203			final Pair<String,String> needle = new Pair<>("pubsub","pep");
1204			Info info = disco.get(account.getServer());
1205			if (info != null && info.identities.contains(needle)) {
1206				return true;
1207			} else {
1208				info = disco.get(account.getJid().toBareJid());
1209				return info != null && info.identities.contains(needle);
1210			}
1211		}
1212
1213		public boolean mam() {
1214			if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1215				return true;
1216			} else {
1217				return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1218			}
1219		}
1220
1221		public boolean advancedStreamFeaturesLoaded() {
1222			return disco.containsKey(account.getServer());
1223		}
1224
1225		public boolean rosterVersioning() {
1226			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1227		}
1228
1229		public void setBlockListRequested(boolean value) {
1230			this.blockListRequested = value;
1231		}
1232
1233		public boolean httpUpload() {
1234			return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1235		}
1236	}
1237
1238	private IqGenerator getIqGenerator() {
1239		return mXmppConnectionService.getIqGenerator();
1240	}
1241}