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