XmppConnection.java

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