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