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