XmppConnection.java

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