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