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