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