XmppConnection.java

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