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