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") && account.getPrivateKeyAlias() != null) {
 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() && socket != null && !socket.isClosed()) {
 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		synchronized (this.disco) {
 911			this.disco.clear();
 912		}
 913		sendServiceDiscoveryInfo(account.getServer());
 914		sendServiceDiscoveryInfo(account.getJid().toBareJid());
 915		sendServiceDiscoveryItems(account.getServer());
 916		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
 917		this.lastSessionStarted = SystemClock.elapsedRealtime();
 918		changeStatus(Account.State.ONLINE);
 919		if (bindListener != null) {
 920			bindListener.onBind(account);
 921		}
 922	}
 923
 924	private void sendServiceDiscoveryInfo(final Jid jid) {
 925		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 926		iq.setTo(jid);
 927		iq.query("http://jabber.org/protocol/disco#info");
 928		this.sendIqPacket(iq, new OnIqPacketReceived() {
 929
 930			@Override
 931			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 932				if (packet.getType() == IqPacket.TYPE.RESULT) {
 933					boolean advancedStreamFeaturesLoaded = false;
 934					synchronized (XmppConnection.this.disco) {
 935						final List<Element> elements = packet.query().getChildren();
 936						final Info info = new Info();
 937						for (final Element element : elements) {
 938							if (element.getName().equals("identity")) {
 939								String type = element.getAttribute("type");
 940								String category = element.getAttribute("category");
 941								if (type != null && category != null) {
 942									info.identities.add(new Pair<>(category, type));
 943								}
 944							} else if (element.getName().equals("feature")) {
 945								info.features.add(element.getAttribute("var"));
 946							}
 947						}
 948						disco.put(jid, info);
 949						advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
 950								&& disco.containsKey(account.getJid().toBareJid());
 951					}
 952					if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
 953						enableAdvancedStreamFeatures();
 954					}
 955				} else {
 956					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
 957				}
 958			}
 959		});
 960	}
 961
 962	private void enableAdvancedStreamFeatures() {
 963		if (getFeatures().carbons() && !features.carbonsEnabled) {
 964			sendEnableCarbons();
 965		}
 966		if (getFeatures().blocking() && !features.blockListRequested) {
 967			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
 968			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
 969		}
 970		for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
 971			listener.onAdvancedStreamFeaturesAvailable(account);
 972		}
 973	}
 974
 975	private void sendServiceDiscoveryItems(final Jid server) {
 976		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 977		iq.setTo(server.toDomainJid());
 978		iq.query("http://jabber.org/protocol/disco#items");
 979		this.sendIqPacket(iq, new OnIqPacketReceived() {
 980
 981			@Override
 982			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 983				if (packet.getType() == IqPacket.TYPE.RESULT) {
 984					final List<Element> elements = packet.query().getChildren();
 985					for (final Element element : elements) {
 986						if (element.getName().equals("item")) {
 987							final Jid jid = element.getAttributeAsJid("jid");
 988							if (jid != null && !jid.equals(account.getServer())) {
 989								sendServiceDiscoveryInfo(jid);
 990							}
 991						}
 992					}
 993				} else {
 994					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco items of "+server);
 995				}
 996			}
 997		});
 998	}
 999
1000	private void sendEnableCarbons() {
1001		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1002		iq.addChild("enable", "urn:xmpp:carbons:2");
1003		this.sendIqPacket(iq, new OnIqPacketReceived() {
1004
1005			@Override
1006			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1007				if (!packet.hasChild("error")) {
1008					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1009							+ ": successfully enabled carbons");
1010					features.carbonsEnabled = true;
1011				} else {
1012					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1013							+ ": error enableing carbons " + packet.toString());
1014				}
1015			}
1016		});
1017	}
1018
1019	private void processStreamError(final Tag currentTag)
1020		throws XmlPullParserException, IOException {
1021		final Element streamError = tagReader.readElement(currentTag);
1022		if (streamError != null && streamError.hasChild("conflict")) {
1023			final String resource = account.getResource().split("\\.")[0];
1024			account.setResource(resource + "." + nextRandomId());
1025			Log.d(Config.LOGTAG,
1026					account.getJid().toBareJid() + ": switching resource due to conflict ("
1027					+ account.getResource() + ")");
1028		} else if (streamError != null) {
1029			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1030		}
1031	}
1032
1033	private void sendStartStream() throws IOException {
1034		final Tag stream = Tag.start("stream:stream");
1035		stream.setAttribute("to", account.getServer().toString());
1036		stream.setAttribute("version", "1.0");
1037		stream.setAttribute("xml:lang", "en");
1038		stream.setAttribute("xmlns", "jabber:client");
1039		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1040		tagWriter.writeTag(stream);
1041	}
1042
1043	private String nextRandomId() {
1044		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1045	}
1046
1047	public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1048		packet.setFrom(account.getJid());
1049		this.sendUnmodifiedIqPacket(packet, callback);
1050
1051	}
1052
1053	private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1054		if (packet.getId() == null) {
1055			final String id = nextRandomId();
1056			packet.setAttribute("id", id);
1057		}
1058		if (callback != null) {
1059			synchronized (this.packetCallbacks) {
1060				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1061			}
1062		}
1063		this.sendPacket(packet);
1064	}
1065
1066	public void sendMessagePacket(final MessagePacket packet) {
1067		this.sendPacket(packet);
1068	}
1069
1070	public void sendPresencePacket(final PresencePacket packet) {
1071		this.sendPacket(packet);
1072	}
1073
1074	private synchronized void sendPacket(final AbstractStanza packet) {
1075		if (stanzasSent == Integer.MAX_VALUE) {
1076			resetStreamId();
1077			disconnect(true);
1078			return;
1079		}
1080		tagWriter.writeStanzaAsync(packet);
1081		if (packet instanceof AbstractAcknowledgeableStanza) {
1082			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1083			++stanzasSent;
1084			this.mStanzaQueue.put(stanzasSent, stanza);
1085			if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1086				if (Config.EXTENDED_SM_LOGGING) {
1087					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1088				}
1089				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1090			}
1091		}
1092	}
1093
1094	public void sendPing() {
1095		if (!r()) {
1096			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1097			iq.setFrom(account.getJid());
1098			iq.addChild("ping", "urn:xmpp:ping");
1099			this.sendIqPacket(iq, null);
1100		}
1101		this.lastPingSent = SystemClock.elapsedRealtime();
1102	}
1103
1104	public void setOnMessagePacketReceivedListener(
1105			final OnMessagePacketReceived listener) {
1106		this.messageListener = listener;
1107			}
1108
1109	public void setOnUnregisteredIqPacketReceivedListener(
1110			final OnIqPacketReceived listener) {
1111		this.unregisteredIqListener = listener;
1112			}
1113
1114	public void setOnPresencePacketReceivedListener(
1115			final OnPresencePacketReceived listener) {
1116		this.presenceListener = listener;
1117			}
1118
1119	public void setOnJinglePacketReceivedListener(
1120			final OnJinglePacketReceived listener) {
1121		this.jingleListener = listener;
1122			}
1123
1124	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1125		this.statusListener = listener;
1126	}
1127
1128	public void setOnBindListener(final OnBindListener listener) {
1129		this.bindListener = listener;
1130	}
1131
1132	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1133		this.acknowledgedListener = listener;
1134	}
1135
1136	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1137		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1138			this.advancedStreamFeaturesLoadedListeners.add(listener);
1139		}
1140	}
1141
1142	public void disconnect(final boolean force) {
1143		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1144		if (force) {
1145			try {
1146				socket.close();
1147			} catch(Exception e) {
1148				Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": exception during force close ("+e.getMessage()+")");
1149			}
1150			return;
1151		} else {
1152			resetStreamId();
1153			if (tagWriter.isActive()) {
1154				tagWriter.finish();
1155				try {
1156					int i = 0;
1157					boolean warned = false;
1158					while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1159						if (!warned) {
1160							Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1161							warned = true;
1162						}
1163						Thread.sleep(200);
1164						i++;
1165					}
1166					if (warned) {
1167						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1168					}
1169					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1170					tagWriter.writeTag(Tag.end("stream:stream"));
1171					socket.close();
1172				} catch (final IOException e) {
1173					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1174				} catch (final InterruptedException e) {
1175					Log.d(Config.LOGTAG, "interrupted");
1176				}
1177			}
1178		}
1179	}
1180
1181	public void resetStreamId() {
1182		this.streamId = null;
1183	}
1184
1185	public List<Jid> findDiscoItemsByFeature(final String feature) {
1186		synchronized (this.disco) {
1187			final List<Jid> items = new ArrayList<>();
1188			for (final Entry<Jid, Info> cursor : this.disco.entrySet()) {
1189				if (cursor.getValue().features.contains(feature)) {
1190					items.add(cursor.getKey());
1191				}
1192			}
1193			return items;
1194		}
1195	}
1196
1197	public Jid findDiscoItemByFeature(final String feature) {
1198		final List<Jid> items = findDiscoItemsByFeature(feature);
1199		if (items.size() >= 1) {
1200			return items.get(0);
1201		}
1202		return null;
1203	}
1204
1205	public boolean r() {
1206		if (getFeatures().sm()) {
1207			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1208			return true;
1209		} else {
1210			return false;
1211		}
1212	}
1213
1214	public String getMucServer() {
1215		synchronized (this.disco) {
1216			for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1217				final Info value = cursor.getValue();
1218				if (value.features.contains("http://jabber.org/protocol/muc")
1219						&& !value.features.contains("jabber:iq:gateway")
1220						&& !value.identities.contains(new Pair<>("conference", "irc"))) {
1221					return cursor.getKey().toString();
1222				}
1223			}
1224		}
1225		return null;
1226	}
1227
1228	public int getTimeToNextAttempt() {
1229		final int interval = (int) (25 * Math.pow(1.5, attempt));
1230		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1231		return interval - secondsSinceLast;
1232	}
1233
1234	public int getAttempt() {
1235		return this.attempt;
1236	}
1237
1238	public Features getFeatures() {
1239		return this.features;
1240	}
1241
1242	public long getLastSessionEstablished() {
1243		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1244		return System.currentTimeMillis() - diff;
1245	}
1246
1247	public long getLastConnect() {
1248		return this.lastConnect;
1249	}
1250
1251	public long getLastPingSent() {
1252		return this.lastPingSent;
1253	}
1254
1255	public long getLastPacketReceived() {
1256		return this.lastPacketReceived;
1257	}
1258
1259	public void sendActive() {
1260		this.sendPacket(new ActivePacket());
1261	}
1262
1263	public void sendInactive() {
1264		this.sendPacket(new InactivePacket());
1265	}
1266
1267	public void resetAttemptCount() {
1268		this.attempt = 0;
1269		this.lastConnect = 0;
1270	}
1271
1272	public void setInteractive(boolean interactive) {
1273		this.mInteractive = interactive;
1274	}
1275
1276	private class Info {
1277		public final ArrayList<String> features = new ArrayList<>();
1278		public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1279	}
1280
1281	private class UnauthorizedException extends IOException {
1282
1283	}
1284
1285	private class SecurityException extends IOException {
1286
1287	}
1288
1289	private class IncompatibleServerException extends IOException {
1290
1291	}
1292
1293	private class DnsTimeoutException extends IOException {
1294
1295	}
1296
1297	public class Features {
1298		XmppConnection connection;
1299		private boolean carbonsEnabled = false;
1300		private boolean encryptionEnabled = false;
1301		private boolean blockListRequested = false;
1302
1303		public Features(final XmppConnection connection) {
1304			this.connection = connection;
1305		}
1306
1307		private boolean hasDiscoFeature(final Jid server, final String feature) {
1308			synchronized (XmppConnection.this.disco) {
1309				return connection.disco.containsKey(server) &&
1310						connection.disco.get(server).features.contains(feature);
1311			}
1312		}
1313
1314		public boolean carbons() {
1315			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1316		}
1317
1318		public boolean blocking() {
1319			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1320		}
1321
1322		public boolean register() {
1323			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1324		}
1325
1326		public boolean sm() {
1327			return streamId != null
1328					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1329		}
1330
1331		public boolean csi() {
1332			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1333		}
1334
1335		public boolean pep() {
1336			synchronized (XmppConnection.this.disco) {
1337				final Pair<String, String> needle = new Pair<>("pubsub", "pep");
1338				Info info = disco.get(account.getServer());
1339				if (info != null && info.identities.contains(needle)) {
1340					return true;
1341				} else {
1342					info = disco.get(account.getJid().toBareJid());
1343					return info != null && info.identities.contains(needle);
1344				}
1345			}
1346		}
1347
1348		public boolean mam() {
1349			if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1350				return true;
1351			} else {
1352				return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1353			}
1354		}
1355
1356		public boolean advancedStreamFeaturesLoaded() {
1357			synchronized (XmppConnection.this.disco) {
1358				return disco.containsKey(account.getServer());
1359			}
1360		}
1361
1362		public boolean rosterVersioning() {
1363			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1364		}
1365
1366		public void setBlockListRequested(boolean value) {
1367			this.blockListRequested = value;
1368		}
1369
1370		public boolean httpUpload() {
1371			return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1372		}
1373	}
1374
1375	private IqGenerator getIqGenerator() {
1376		return mXmppConnectionService.getIqGenerator();
1377	}
1378}