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