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