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