XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.content.SharedPreferences;
   5import android.os.Bundle;
   6import android.os.Parcelable;
   7import android.os.PowerManager;
   8import android.os.PowerManager.WakeLock;
   9import android.os.SystemClock;
  10import android.preference.PreferenceManager;
  11import android.util.Log;
  12import android.util.SparseArray;
  13
  14import org.apache.http.conn.ssl.StrictHostnameVerifier;
  15import org.json.JSONException;
  16import org.json.JSONObject;
  17import org.xmlpull.v1.XmlPullParserException;
  18
  19import java.io.IOException;
  20import java.io.InputStream;
  21import java.io.OutputStream;
  22import java.math.BigInteger;
  23import java.net.IDN;
  24import java.net.InetSocketAddress;
  25import java.net.Socket;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.util.ArrayList;
  30import java.util.Arrays;
  31import java.util.HashMap;
  32import java.util.Hashtable;
  33import java.util.LinkedList;
  34import java.util.List;
  35import java.util.Map.Entry;
  36
  37import javax.net.ssl.HostnameVerifier;
  38import javax.net.ssl.SSLContext;
  39import javax.net.ssl.SSLSocket;
  40import javax.net.ssl.SSLSocketFactory;
  41import javax.net.ssl.X509TrustManager;
  42
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.crypto.sasl.DigestMd5;
  45import eu.siacs.conversations.crypto.sasl.Plain;
  46import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  47import eu.siacs.conversations.crypto.sasl.ScramSha1;
  48import eu.siacs.conversations.entities.Account;
  49import eu.siacs.conversations.services.XmppConnectionService;
  50import eu.siacs.conversations.utils.DNSHelper;
  51import eu.siacs.conversations.utils.zlib.ZLibInputStream;
  52import eu.siacs.conversations.utils.zlib.ZLibOutputStream;
  53import eu.siacs.conversations.xml.Element;
  54import eu.siacs.conversations.xml.Tag;
  55import eu.siacs.conversations.xml.TagWriter;
  56import eu.siacs.conversations.xml.XmlReader;
  57import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  58import eu.siacs.conversations.xmpp.jid.Jid;
  59import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  60import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  61import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  62import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  63import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  64import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  65import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  66import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  67import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  68import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  69import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
  70import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
  71
  72public class XmppConnection implements Runnable {
  73
  74	private static final int PACKET_IQ = 0;
  75	private static final int PACKET_MESSAGE = 1;
  76	private static final int PACKET_PRESENCE = 2;
  77	private final Context applicationContext;
  78	protected Account account;
  79	private WakeLock wakeLock;
  80	private Socket socket;
  81	private XmlReader tagReader;
  82	private TagWriter tagWriter;
  83	private Features features = new Features(this);
  84	private boolean shouldBind = true;
  85	private boolean shouldAuthenticate = true;
  86	private Element streamFeatures;
  87	private HashMap<String, List<String>> disco = new HashMap<>();
  88
  89	private String streamId = null;
  90	private int smVersion = 3;
  91	private SparseArray<String> messageReceipts = new SparseArray<>();
  92
  93	private boolean usingCompression = false;
  94	private boolean usingEncryption = false;
  95	private int stanzasReceived = 0;
  96	private int stanzasSent = 0;
  97	private long lastPaketReceived = 0;
  98	private long lastPingSent = 0;
  99	private long lastConnect = 0;
 100	private long lastSessionStarted = 0;
 101	private int attempt = 0;
 102	private Hashtable<String, PacketReceived> packetCallbacks = new Hashtable<>();
 103	private OnPresencePacketReceived presenceListener = null;
 104	private OnJinglePacketReceived jingleListener = null;
 105	private OnIqPacketReceived unregisteredIqListener = null;
 106	private OnMessagePacketReceived messageListener = null;
 107	private OnStatusChanged statusListener = null;
 108	private OnBindListener bindListener = null;
 109	private OnMessageAcknowledged acknowledgedListener = null;
 110	private XmppConnectionService mXmppConnectionService = null;
 111
 112	private SaslMechanism saslMechanism;
 113
 114	public XmppConnection(Account account, XmppConnectionService service) {
 115		this.account = account;
 116		this.wakeLock = service.getPowerManager().newWakeLock(
 117				PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
 118		tagWriter = new TagWriter();
 119		mXmppConnectionService = service;
 120		applicationContext = service.getApplicationContext();
 121	}
 122
 123	protected void changeStatus(int nextStatus) {
 124		if (account.getStatus() != nextStatus) {
 125			if ((nextStatus == Account.STATUS_OFFLINE)
 126					&& (account.getStatus() != Account.STATUS_CONNECTING)
 127					&& (account.getStatus() != Account.STATUS_ONLINE)
 128					&& (account.getStatus() != Account.STATUS_DISABLED)) {
 129				return;
 130					}
 131			if (nextStatus == Account.STATUS_ONLINE) {
 132				this.attempt = 0;
 133			}
 134			account.setStatus(nextStatus);
 135			if (statusListener != null) {
 136				statusListener.onStatusChanged(account);
 137			}
 138		}
 139	}
 140
 141	protected void connect() {
 142		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
 143		usingCompression = false;
 144		usingEncryption = false;
 145		lastConnect = SystemClock.elapsedRealtime();
 146		lastPingSent = SystemClock.elapsedRealtime();
 147		this.attempt++;
 148		try {
 149			shouldAuthenticate = shouldBind = !account
 150				.isOptionSet(Account.OPTION_REGISTER);
 151			tagReader = new XmlReader(wakeLock);
 152			tagWriter = new TagWriter();
 153			packetCallbacks.clear();
 154			this.changeStatus(Account.STATUS_CONNECTING);
 155			Bundle result = DNSHelper.getSRVRecord(account.getServer());
 156			ArrayList<Parcelable> values = result.getParcelableArrayList("values");
 157			if ("timeout".equals(result.getString("error"))) {
 158				Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": dns timeout");
 159				this.changeStatus(Account.STATUS_OFFLINE);
 160				return;
 161			} else if (values != null) {
 162				int i = 0;
 163				boolean socketError = true;
 164				while (socketError && values.size() > i) {
 165					Bundle namePort = (Bundle) values.get(i);
 166					try {
 167						String srvRecordServer;
 168						try {
 169							srvRecordServer=IDN.toASCII(namePort.getString("name"));
 170						} catch (final IllegalArgumentException e) {
 171							// TODO: Handle me?`
 172							srvRecordServer = "";
 173						}
 174						int srvRecordPort = namePort.getInt("port");
 175						String srvIpServer = namePort.getString("ipv4");
 176						InetSocketAddress addr;
 177						if (srvIpServer != null) {
 178							addr = new InetSocketAddress(srvIpServer, srvRecordPort);
 179							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 180									+ ": using values from dns " + srvRecordServer
 181									+ "[" + srvIpServer + "]:" + srvRecordPort);
 182						} else {
 183							addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
 184							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 185									+ ": using values from dns "
 186									+ srvRecordServer + ":" + srvRecordPort);
 187						}
 188						socket = new Socket();
 189						socket.connect(addr, 20000);
 190						socketError = false;
 191					} catch (UnknownHostException e) {
 192						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 193						i++;
 194					} catch (IOException e) {
 195						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 196						i++;
 197					}
 198				}
 199				if (socketError) {
 200					this.changeStatus(Account.STATUS_SERVER_NOT_FOUND);
 201					if (wakeLock.isHeld()) {
 202						try {
 203							wakeLock.release();
 204						} catch (final RuntimeException ignored) {
 205						}
 206					}
 207					return;
 208				}
 209			} else if (result.containsKey("error")
 210					&& "nosrv".equals(result.getString("error", null))) {
 211				socket = new Socket(account.getServer().getDomainpart(), 5222);
 212			} else {
 213				Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 214						+ ": timeout in DNS resolution");
 215				changeStatus(Account.STATUS_OFFLINE);
 216				return;
 217			}
 218			OutputStream out = socket.getOutputStream();
 219			tagWriter.setOutputStream(out);
 220			InputStream in = socket.getInputStream();
 221			tagReader.setInputStream(in);
 222			tagWriter.beginDocument();
 223			sendStartStream();
 224			Tag nextTag;
 225			while ((nextTag = tagReader.readTag()) != null) {
 226				if (nextTag.isStart("stream")) {
 227					processStream(nextTag);
 228					break;
 229				} else {
 230					Log.d(Config.LOGTAG,
 231							"found unexpected tag: " + nextTag.getName());
 232					return;
 233				}
 234			}
 235			if (socket.isConnected()) {
 236				socket.close();
 237			}
 238		} catch (UnknownHostException e) {
 239			this.changeStatus(Account.STATUS_SERVER_NOT_FOUND);
 240			if (wakeLock.isHeld()) {
 241				try {
 242					wakeLock.release();
 243				} catch (final RuntimeException ignored) {
 244				}
 245			}
 246		} catch (final IOException | XmlPullParserException e) {
 247			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 248			this.changeStatus(Account.STATUS_OFFLINE);
 249			if (wakeLock.isHeld()) {
 250				try {
 251					wakeLock.release();
 252				} catch (final RuntimeException ignored) {
 253				}
 254			}
 255		} catch (NoSuchAlgorithmException e) {
 256			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 257			this.changeStatus(Account.STATUS_OFFLINE);
 258			Log.d(Config.LOGTAG, "compression exception " + e.getMessage());
 259			if (wakeLock.isHeld()) {
 260				try {
 261					wakeLock.release();
 262				} catch (final RuntimeException ignored) {
 263				}
 264			}
 265		}
 266
 267	}
 268
 269	@Override
 270	public void run() {
 271		connect();
 272	}
 273
 274	private void processStream(final Tag currentTag) throws XmlPullParserException,
 275					IOException, NoSuchAlgorithmException {
 276						Tag nextTag = tagReader.readTag();
 277
 278						while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
 279							if (nextTag.isStart("error")) {
 280								processStreamError(nextTag);
 281							} else if (nextTag.isStart("features")) {
 282								processStreamFeatures(nextTag);
 283							} else if (nextTag.isStart("proceed")) {
 284								switchOverToTls(nextTag);
 285							} else if (nextTag.isStart("compressed")) {
 286								switchOverToZLib(nextTag);
 287							} else if (nextTag.isStart("success")) {
 288								final String challenge = tagReader.readElement(nextTag).getContent();
 289								try {
 290									saslMechanism.getResponse(challenge);
 291								} catch (final SaslMechanism.AuthenticationException e) {
 292									disconnect(true);
 293									Log.e(Config.LOGTAG, String.valueOf(e));
 294								}
 295								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
 296								account.setKey(Account.PINNED_MECHANISM_KEY,
 297										String.valueOf(saslMechanism.getPriority()));
 298								tagReader.reset();
 299								sendStartStream();
 300								processStream(tagReader.readTag());
 301								break;
 302							} else if (nextTag.isStart("failure")) {
 303								tagReader.readElement(nextTag);
 304								changeStatus(Account.STATUS_UNAUTHORIZED);
 305							} else if (nextTag.isStart("challenge")) {
 306								final String challenge = tagReader.readElement(nextTag).getContent();
 307								final Element response = new Element("response");
 308								response.setAttribute("xmlns",
 309										"urn:ietf:params:xml:ns:xmpp-sasl");
 310								try {
 311									response.setContent(saslMechanism.getResponse(challenge));
 312								} catch (final SaslMechanism.AuthenticationException e) {
 313									// TODO: Send auth abort tag.
 314									Log.e(Config.LOGTAG, e.toString());
 315								}
 316								tagWriter.writeElement(response);
 317							} else if (nextTag.isStart("enabled")) {
 318								Element enabled = tagReader.readElement(nextTag);
 319								if ("true".equals(enabled.getAttribute("resume"))) {
 320									this.streamId = enabled.getAttribute("id");
 321									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 322											+ ": stream managment(" + smVersion
 323											+ ") enabled (resumable)");
 324								} else {
 325									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 326											+ ": stream managment(" + smVersion + ") enabled");
 327								}
 328								this.lastSessionStarted = SystemClock.elapsedRealtime();
 329								this.stanzasReceived = 0;
 330								RequestPacket r = new RequestPacket(smVersion);
 331								tagWriter.writeStanzaAsync(r);
 332							} else if (nextTag.isStart("resumed")) {
 333								lastPaketReceived = SystemClock.elapsedRealtime();
 334								Element resumed = tagReader.readElement(nextTag);
 335								String h = resumed.getAttribute("h");
 336								try {
 337									int serverCount = Integer.parseInt(h);
 338									if (serverCount != stanzasSent) {
 339										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 340												+ ": session resumed with lost packages");
 341										stanzasSent = serverCount;
 342									} else {
 343										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 344												+ ": session resumed");
 345									}
 346									if (acknowledgedListener != null) {
 347										for (int i = 0; i < messageReceipts.size(); ++i) {
 348											if (serverCount >= messageReceipts.keyAt(i)) {
 349												acknowledgedListener.onMessageAcknowledged(
 350														account, messageReceipts.valueAt(i));
 351											}
 352										}
 353									}
 354									messageReceipts.clear();
 355								} catch (final NumberFormatException ignored) {
 356
 357								}
 358								sendInitialPing();
 359
 360							} else if (nextTag.isStart("r")) {
 361								tagReader.readElement(nextTag);
 362								AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 363								tagWriter.writeStanzaAsync(ack);
 364							} else if (nextTag.isStart("a")) {
 365								Element ack = tagReader.readElement(nextTag);
 366								lastPaketReceived = SystemClock.elapsedRealtime();
 367								int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 368								String msgId = this.messageReceipts.get(serverSequence);
 369								if (msgId != null) {
 370									if (this.acknowledgedListener != null) {
 371										this.acknowledgedListener.onMessageAcknowledged(
 372												account, msgId);
 373									}
 374									this.messageReceipts.remove(serverSequence);
 375								}
 376							} else if (nextTag.isStart("failed")) {
 377								tagReader.readElement(nextTag);
 378								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
 379								streamId = null;
 380								if (account.getStatus() != Account.STATUS_ONLINE) {
 381									sendBindRequest();
 382								}
 383							} else if (nextTag.isStart("iq")) {
 384								processIq(nextTag);
 385							} else if (nextTag.isStart("message")) {
 386								processMessage(nextTag);
 387							} else if (nextTag.isStart("presence")) {
 388								processPresence(nextTag);
 389							}
 390							nextTag = tagReader.readTag();
 391						}
 392						if (account.getStatus() == Account.STATUS_ONLINE) {
 393							account. setStatus(Account.STATUS_OFFLINE);
 394							if (statusListener != null) {
 395								statusListener.onStatusChanged(account);
 396							}
 397						}
 398	}
 399
 400	private void sendInitialPing() {
 401		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": sending intial ping");
 402		IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
 403		iq.setFrom(account.getJid());
 404		iq.addChild("ping", "urn:xmpp:ping");
 405		this.sendIqPacket(iq, new OnIqPacketReceived() {
 406
 407			@Override
 408			public void onIqPacketReceived(Account account, IqPacket packet) {
 409				Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 410						+ ": online with resource " + account.getResource());
 411				changeStatus(Account.STATUS_ONLINE);
 412			}
 413		});
 414	}
 415
 416	private Element processPacket(Tag currentTag, int packetType)
 417		throws XmlPullParserException, IOException {
 418		Element element;
 419		switch (packetType) {
 420			case PACKET_IQ:
 421				element = new IqPacket();
 422				break;
 423			case PACKET_MESSAGE:
 424				element = new MessagePacket();
 425				break;
 426			case PACKET_PRESENCE:
 427				element = new PresencePacket();
 428				break;
 429			default:
 430				return null;
 431		}
 432		element.setAttributes(currentTag.getAttributes());
 433		Tag nextTag = tagReader.readTag();
 434		if (nextTag == null) {
 435			throw new IOException("interrupted mid tag");
 436		}
 437		while (!nextTag.isEnd(element.getName())) {
 438			if (!nextTag.isNo()) {
 439				Element child = tagReader.readElement(nextTag);
 440				String type = currentTag.getAttribute("type");
 441				if (packetType == PACKET_IQ
 442						&& "jingle".equals(child.getName())
 443						&& ("set".equalsIgnoreCase(type) || "get"
 444							.equalsIgnoreCase(type))) {
 445					element = new JinglePacket();
 446					element.setAttributes(currentTag.getAttributes());
 447							}
 448				element.addChild(child);
 449			}
 450			nextTag = tagReader.readTag();
 451			if (nextTag == null) {
 452				throw new IOException("interrupted mid tag");
 453			}
 454		}
 455		++stanzasReceived;
 456		lastPaketReceived = SystemClock.elapsedRealtime();
 457		return element;
 458	}
 459
 460	private void processIq(Tag currentTag) throws XmlPullParserException,
 461					IOException {
 462						IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 463
 464						if (packet.getId() == null) {
 465							return; // an iq packet without id is definitely invalid
 466						}
 467
 468						if (packet instanceof JinglePacket) {
 469							if (this.jingleListener != null) {
 470								this.jingleListener.onJinglePacketReceived(account,
 471										(JinglePacket) packet);
 472							}
 473						} else {
 474							if (packetCallbacks.containsKey(packet.getId())) {
 475								if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) {
 476									((OnIqPacketReceived) packetCallbacks.get(packet.getId()))
 477										.onIqPacketReceived(account, packet);
 478								}
 479
 480								packetCallbacks.remove(packet.getId());
 481							} else if ((packet.getType() == IqPacket.TYPE_GET || packet
 482										.getType() == IqPacket.TYPE_SET)
 483									&& this.unregisteredIqListener != null) {
 484								this.unregisteredIqListener.onIqPacketReceived(account, packet);
 485									}
 486						}
 487	}
 488
 489	private void processMessage(Tag currentTag) throws XmlPullParserException,
 490					IOException {
 491						MessagePacket packet = (MessagePacket) processPacket(currentTag,
 492								PACKET_MESSAGE);
 493						String id = packet.getAttribute("id");
 494						if ((id != null) && (packetCallbacks.containsKey(id))) {
 495							if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) {
 496								((OnMessagePacketReceived) packetCallbacks.get(id))
 497									.onMessagePacketReceived(account, packet);
 498							}
 499							packetCallbacks.remove(id);
 500						} else if (this.messageListener != null) {
 501							this.messageListener.onMessagePacketReceived(account, packet);
 502						}
 503	}
 504
 505	private void processPresence(Tag currentTag) throws XmlPullParserException,
 506					IOException {
 507						PresencePacket packet = (PresencePacket) processPacket(currentTag,
 508								PACKET_PRESENCE);
 509						String id = packet.getAttribute("id");
 510						if ((id != null) && (packetCallbacks.containsKey(id))) {
 511							if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) {
 512								((OnPresencePacketReceived) packetCallbacks.get(id))
 513									.onPresencePacketReceived(account, packet);
 514							}
 515							packetCallbacks.remove(id);
 516						} else if (this.presenceListener != null) {
 517							this.presenceListener.onPresencePacketReceived(account, packet);
 518						}
 519	}
 520
 521	private void sendCompressionZlib() throws IOException {
 522		Element compress = new Element("compress");
 523		compress.setAttribute("xmlns", "http://jabber.org/protocol/compress");
 524		compress.addChild("method").setContent("zlib");
 525		tagWriter.writeElement(compress);
 526	}
 527
 528	private void switchOverToZLib(final Tag currentTag)
 529		throws XmlPullParserException, IOException,
 530										NoSuchAlgorithmException {
 531						 tagReader.readTag(); // read tag close
 532						 tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
 533									 .getOutputStream()));
 534						 tagReader
 535							 .setInputStream(new ZLibInputStream(tagReader.getInputStream()));
 536
 537						 sendStartStream();
 538						 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": compression enabled");
 539						 usingCompression = true;
 540						 processStream(tagReader.readTag());
 541	}
 542
 543	private void sendStartTLS() throws IOException {
 544		Tag startTLS = Tag.empty("starttls");
 545		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
 546		tagWriter.writeTag(startTLS);
 547	}
 548
 549	private SharedPreferences getPreferences() {
 550		return PreferenceManager
 551			.getDefaultSharedPreferences(applicationContext);
 552	}
 553
 554	private boolean enableLegacySSL() {
 555		return getPreferences().getBoolean("enable_legacy_ssl", false);
 556	}
 557
 558	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException,
 559					IOException {
 560						tagReader.readTag();
 561						try {
 562							SSLContext sc = SSLContext.getInstance("TLS");
 563							sc.init(null,
 564									new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},
 565									mXmppConnectionService.getRNG());
 566							SSLSocketFactory factory = sc.getSocketFactory();
 567
 568							if (factory == null) {
 569								throw new IOException("SSLSocketFactory was null");
 570							}
 571
 572							final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
 573
 574							if (socket == null) {
 575								throw new IOException("socket was null");
 576							}
 577							final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
 578									socket.getInetAddress().getHostAddress(), socket.getPort(),
 579									true);
 580
 581							// Support all protocols except legacy SSL.
 582							// The min SDK version prevents us having to worry about SSLv2. In
 583							// future, this may be true of SSLv3 as well.
 584							final String[] supportProtocols;
 585							if (enableLegacySSL()) {
 586								supportProtocols = sslSocket.getSupportedProtocols();
 587							} else {
 588								final List<String> supportedProtocols = new LinkedList<>(
 589										Arrays.asList(sslSocket.getSupportedProtocols()));
 590								supportedProtocols.remove("SSLv3");
 591								supportProtocols = new String[supportedProtocols.size()];
 592								supportedProtocols.toArray(supportProtocols);
 593							}
 594							sslSocket.setEnabledProtocols(supportProtocols);
 595
 596							if (verifier != null
 597									&& !verifier.verify(account.getServer().getDomainpart(),
 598										sslSocket.getSession())) {
 599								sslSocket.close();
 600								throw new IOException("host mismatch in TLS connection");
 601									}
 602							tagReader.setInputStream(sslSocket.getInputStream());
 603							tagWriter.setOutputStream(sslSocket.getOutputStream());
 604							sendStartStream();
 605							Log.d(Config.LOGTAG, account.getJid().toBareJid()
 606									+ ": TLS connection established");
 607							usingEncryption = true;
 608							processStream(tagReader.readTag());
 609							sslSocket.close();
 610						} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 611							e1.printStackTrace();
 612						}
 613	}
 614
 615	private void processStreamFeatures(Tag currentTag)
 616		throws XmlPullParserException, IOException {
 617		this.streamFeatures = tagReader.readElement(currentTag);
 618		if (this.streamFeatures.hasChild("starttls") && !usingEncryption) {
 619			sendStartTLS();
 620		} else if (compressionAvailable()) {
 621			sendCompressionZlib();
 622		} else if (this.streamFeatures.hasChild("register")
 623				&& account.isOptionSet(Account.OPTION_REGISTER)
 624				&& usingEncryption) {
 625			sendRegistryRequest();
 626		} else if (!this.streamFeatures.hasChild("register")
 627				&& account.isOptionSet(Account.OPTION_REGISTER)) {
 628			changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
 629			disconnect(true);
 630		} else if (this.streamFeatures.hasChild("mechanisms")
 631				&& shouldAuthenticate && usingEncryption) {
 632			final List<String> mechanisms = extractMechanisms(streamFeatures
 633					.findChild("mechanisms"));
 634			final Element auth = new Element("auth");
 635			auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
 636			if (mechanisms.contains("SCRAM-SHA-1")) {
 637				saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 638			} else if (mechanisms.contains("DIGEST-MD5")) {
 639				saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 640			} else if (mechanisms.contains("PLAIN")) {
 641				saslMechanism = new Plain(tagWriter, account);
 642			}
 643			final JSONObject keys = account.getKeys();
 644			try {
 645				if (keys.has(Account.PINNED_MECHANISM_KEY) &&
 646						keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority() ) {
 647					Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 648							" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 649							") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
 650							"). Possible downgrade attack?");
 651					disconnect(true);
 652						}
 653			} catch (final JSONException e) {
 654				Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
 655			}
 656			Log.d(Config.LOGTAG, "Authenticating with " + saslMechanism.getMechanism());
 657			auth.setAttribute("mechanism", saslMechanism.getMechanism());
 658			if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 659				auth.setContent(saslMechanism.getClientFirstMessage());
 660			}
 661			tagWriter.writeElement(auth);
 662		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
 663					+ smVersion)
 664				&& streamId != null) {
 665			ResumePacket resume = new ResumePacket(this.streamId,
 666					stanzasReceived, smVersion);
 667			this.tagWriter.writeStanzaAsync(resume);
 668		} else if (this.streamFeatures.hasChild("bind") && shouldBind) {
 669			sendBindRequest();
 670		} else {
 671			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 672					+ ": incompatible server. disconnecting");
 673			disconnect(true);
 674		}
 675	}
 676
 677	private boolean compressionAvailable() {
 678		if (!this.streamFeatures.hasChild("compression",
 679					"http://jabber.org/features/compress"))
 680			return false;
 681		if (!ZLibOutputStream.SUPPORTED)
 682			return false;
 683		if (!account.isOptionSet(Account.OPTION_USECOMPRESSION))
 684			return false;
 685
 686		Element compression = this.streamFeatures.findChild("compression",
 687				"http://jabber.org/features/compress");
 688		for (Element child : compression.getChildren()) {
 689			if (!"method".equals(child.getName()))
 690				continue;
 691
 692			if ("zlib".equalsIgnoreCase(child.getContent())) {
 693				return true;
 694			}
 695		}
 696		return false;
 697	}
 698
 699	private List<String> extractMechanisms(Element stream) {
 700		ArrayList<String> mechanisms = new ArrayList<>(stream
 701				.getChildren().size());
 702		for (Element child : stream.getChildren()) {
 703			mechanisms.add(child.getContent());
 704		}
 705		return mechanisms;
 706	}
 707
 708	private void sendRegistryRequest() {
 709		IqPacket register = new IqPacket(IqPacket.TYPE_GET);
 710		register.query("jabber:iq:register");
 711		register.setTo(account.getServer());
 712		sendIqPacket(register, new OnIqPacketReceived() {
 713
 714			@Override
 715			public void onIqPacketReceived(Account account, IqPacket packet) {
 716				Element instructions = packet.query().findChild("instructions");
 717				if (packet.query().hasChild("username")
 718						&& (packet.query().hasChild("password"))) {
 719					IqPacket register = new IqPacket(IqPacket.TYPE_SET);
 720					Element username = new Element("username")
 721						.setContent(account.getUsername());
 722					Element password = new Element("password")
 723						.setContent(account.getPassword());
 724					register.query("jabber:iq:register").addChild(username);
 725					register.query().addChild(password);
 726					sendIqPacket(register, new OnIqPacketReceived() {
 727
 728						@Override
 729						public void onIqPacketReceived(Account account,
 730								IqPacket packet) {
 731							if (packet.getType() == IqPacket.TYPE_RESULT) {
 732								account.setOption(Account.OPTION_REGISTER,
 733										false);
 734								changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
 735							} else if (packet.hasChild("error")
 736									&& (packet.findChild("error")
 737										.hasChild("conflict"))) {
 738								changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
 739							} else {
 740								changeStatus(Account.STATUS_REGISTRATION_FAILED);
 741								Log.d(Config.LOGTAG, packet.toString());
 742							}
 743							disconnect(true);
 744						}
 745					});
 746				} else {
 747					changeStatus(Account.STATUS_REGISTRATION_FAILED);
 748					disconnect(true);
 749					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 750							+ ": could not register. instructions are"
 751							+ instructions.getContent());
 752				}
 753			}
 754		});
 755	}
 756
 757	private void sendBindRequest() throws IOException {
 758		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
 759		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 760			.addChild("resource").setContent(account.getResource());
 761		this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
 762			@Override
 763			public void onIqPacketReceived(Account account, IqPacket packet) {
 764				Element bind = packet.findChild("bind");
 765				if (bind != null) {
 766					final Element jid = bind.findChild("jid");
 767					if (jid != null && jid.getContent() != null) {
 768						try {
 769							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 770						} catch (final InvalidJidException e) {
 771							// TODO: Handle the case where an external JID is technically invalid?
 772						}
 773						if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
 774							smVersion = 3;
 775							EnablePacket enable = new EnablePacket(smVersion);
 776							tagWriter.writeStanzaAsync(enable);
 777							stanzasSent = 0;
 778							messageReceipts.clear();
 779						} else if (streamFeatures.hasChild("sm",
 780									"urn:xmpp:sm:2")) {
 781							smVersion = 2;
 782							EnablePacket enable = new EnablePacket(smVersion);
 783							tagWriter.writeStanzaAsync(enable);
 784							stanzasSent = 0;
 785							messageReceipts.clear();
 786						}
 787						sendServiceDiscoveryInfo(account.getServer());
 788						sendServiceDiscoveryItems(account.getServer());
 789						if (bindListener != null) {
 790							bindListener.onBind(account);
 791						}
 792						sendInitialPing();
 793					} else {
 794						disconnect(true);
 795					}
 796				} else {
 797					disconnect(true);
 798				}
 799			}
 800		});
 801		if (this.streamFeatures.hasChild("session")) {
 802			Log.d(Config.LOGTAG, account.getJid().toBareJid()
 803					+ ": sending deprecated session");
 804			IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
 805			startSession.addChild("session",
 806					"urn:ietf:params:xml:ns:xmpp-session");
 807			this.sendUnboundIqPacket(startSession, null);
 808		}
 809	}
 810
 811	private void sendServiceDiscoveryInfo(final Jid server) {
 812		final IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
 813		iq.setTo(server.toDomainJid());
 814		iq.query("http://jabber.org/protocol/disco#info");
 815		this.sendIqPacket(iq, new OnIqPacketReceived() {
 816
 817			@Override
 818			public void onIqPacketReceived(Account account, IqPacket packet) {
 819				final List<Element> elements = packet.query().getChildren();
 820				final List<String> features = new ArrayList<>();
 821				for (Element element : elements) {
 822					if (element.getName().equals("feature")) {
 823						features.add(element.getAttribute("var"));
 824					}
 825				}
 826				disco.put(server.toDomainJid().toString(), features);
 827
 828				if (account.getServer().equals(server.toDomainJid())) {
 829					enableAdvancedStreamFeatures();
 830				}
 831			}
 832		});
 833	}
 834
 835	private void enableAdvancedStreamFeatures() {
 836		if (getFeatures().carbons()) {
 837			sendEnableCarbons();
 838		}
 839	}
 840
 841	private void sendServiceDiscoveryItems(final Jid server) {
 842		final IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
 843		iq.setTo(server.toDomainJid());
 844		iq.query("http://jabber.org/protocol/disco#items");
 845		this.sendIqPacket(iq, new OnIqPacketReceived() {
 846
 847			@Override
 848			public void onIqPacketReceived(Account account, IqPacket packet) {
 849				List<Element> elements = packet.query().getChildren();
 850				for (Element element : elements) {
 851					if (element.getName().equals("item")) {
 852						final String jid = element.getAttribute("jid");
 853						try {
 854							sendServiceDiscoveryInfo(Jid.fromString(jid).toDomainJid());
 855						} catch (final InvalidJidException ignored) {
 856							// TODO: Handle the case where an external JID is technically invalid?
 857						}
 858					}
 859				}
 860			}
 861		});
 862	}
 863
 864	private void sendEnableCarbons() {
 865		IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
 866		iq.addChild("enable", "urn:xmpp:carbons:2");
 867		this.sendIqPacket(iq, new OnIqPacketReceived() {
 868
 869			@Override
 870			public void onIqPacketReceived(Account account, IqPacket packet) {
 871				if (!packet.hasChild("error")) {
 872					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 873							+ ": successfully enabled carbons");
 874				} else {
 875					Log.d(Config.LOGTAG, account.getJid().toBareJid()
 876							+ ": error enableing carbons " + packet.toString());
 877				}
 878			}
 879		});
 880	}
 881
 882	private void processStreamError(Tag currentTag)
 883		throws XmlPullParserException, IOException {
 884		Element streamError = tagReader.readElement(currentTag);
 885		if (streamError != null && streamError.hasChild("conflict")) {
 886			final String resource = account.getResource().split("\\.")[0];
 887			account.setResource(resource + "." + nextRandomId());
 888			Log.d(Config.LOGTAG,
 889					account.getJid().toBareJid() + ": switching resource due to conflict ("
 890					+ account.getResource() + ")");
 891		}
 892	}
 893
 894	private void sendStartStream() throws IOException {
 895		Tag stream = Tag.start("stream:stream");
 896		stream.setAttribute("from", account.getJid().toBareJid().toString());
 897		stream.setAttribute("to", account.getServer().toString());
 898		stream.setAttribute("version", "1.0");
 899		stream.setAttribute("xml:lang", "en");
 900		stream.setAttribute("xmlns", "jabber:client");
 901		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
 902		tagWriter.writeTag(stream);
 903	}
 904
 905	private String nextRandomId() {
 906		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
 907	}
 908
 909	public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
 910		if (packet.getId() == null) {
 911			String id = nextRandomId();
 912			packet.setAttribute("id", id);
 913		}
 914		packet.setFrom(account.getJid());
 915		this.sendPacket(packet, callback);
 916	}
 917
 918	public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) {
 919		if (packet.getId() == null) {
 920			String id = nextRandomId();
 921			packet.setAttribute("id", id);
 922		}
 923		this.sendPacket(packet, callback);
 924	}
 925
 926	public void sendMessagePacket(MessagePacket packet) {
 927		this.sendPacket(packet, null);
 928	}
 929
 930	public void sendPresencePacket(PresencePacket packet) {
 931		this.sendPacket(packet, null);
 932	}
 933
 934	private synchronized void sendPacket(final AbstractStanza packet,
 935			PacketReceived callback) {
 936		if (packet.getName().equals("iq") || packet.getName().equals("message")
 937				|| packet.getName().equals("presence")) {
 938			++stanzasSent;
 939				}
 940		tagWriter.writeStanzaAsync(packet);
 941		if (packet instanceof MessagePacket && packet.getId() != null
 942				&& this.streamId != null) {
 943			Log.d(Config.LOGTAG, "request delivery report for stanza "
 944					+ stanzasSent);
 945			this.messageReceipts.put(stanzasSent, packet.getId());
 946			tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
 947				}
 948		if (callback != null) {
 949			if (packet.getId() == null) {
 950				packet.setId(nextRandomId());
 951			}
 952			packetCallbacks.put(packet.getId(), callback);
 953		}
 954	}
 955
 956	public void sendPing() {
 957		if (streamFeatures.hasChild("sm")) {
 958			tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 959		} else {
 960			IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
 961			iq.setFrom(account.getJid());
 962			iq.addChild("ping", "urn:xmpp:ping");
 963			this.sendIqPacket(iq, null);
 964		}
 965		this.lastPingSent = SystemClock.elapsedRealtime();
 966	}
 967
 968	public void setOnMessagePacketReceivedListener(
 969			OnMessagePacketReceived listener) {
 970		this.messageListener = listener;
 971			}
 972
 973	public void setOnUnregisteredIqPacketReceivedListener(
 974			OnIqPacketReceived listener) {
 975		this.unregisteredIqListener = listener;
 976			}
 977
 978	public void setOnPresencePacketReceivedListener(
 979			OnPresencePacketReceived listener) {
 980		this.presenceListener = listener;
 981			}
 982
 983	public void setOnJinglePacketReceivedListener(
 984			OnJinglePacketReceived listener) {
 985		this.jingleListener = listener;
 986			}
 987
 988	public void setOnStatusChangedListener(OnStatusChanged listener) {
 989		this.statusListener = listener;
 990	}
 991
 992	public void setOnBindListener(OnBindListener listener) {
 993		this.bindListener = listener;
 994	}
 995
 996	public void setOnMessageAcknowledgeListener(OnMessageAcknowledged listener) {
 997		this.acknowledgedListener = listener;
 998	}
 999
1000	public void disconnect(boolean force) {
1001		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
1002		try {
1003			if (force) {
1004				socket.close();
1005				return;
1006			}
1007			new Thread(new Runnable() {
1008
1009				@Override
1010				public void run() {
1011					if (tagWriter.isActive()) {
1012						tagWriter.finish();
1013						try {
1014							while (!tagWriter.finished()) {
1015								Log.d(Config.LOGTAG, "not yet finished");
1016								Thread.sleep(100);
1017							}
1018							tagWriter.writeTag(Tag.end("stream:stream"));
1019							socket.close();
1020						} catch (IOException e) {
1021							Log.d(Config.LOGTAG,
1022									"io exception during disconnect");
1023						} catch (InterruptedException e) {
1024							Log.d(Config.LOGTAG, "interrupted");
1025						}
1026					}
1027				}
1028			}).start();
1029		} catch (IOException e) {
1030			Log.d(Config.LOGTAG, "io exception during disconnect");
1031		}
1032	}
1033
1034	public List<String> findDiscoItemsByFeature(String feature) {
1035		final List<String> items = new ArrayList<>();
1036		for (Entry<String, List<String>> cursor : disco.entrySet()) {
1037			if (cursor.getValue().contains(feature)) {
1038				items.add(cursor.getKey());
1039			}
1040		}
1041		return items;
1042	}
1043
1044	public String findDiscoItemByFeature(String feature) {
1045		List<String> items = findDiscoItemsByFeature(feature);
1046		if (items.size() >= 1) {
1047			return items.get(0);
1048		}
1049		return null;
1050	}
1051
1052	public void r() {
1053		this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1054	}
1055
1056	public String getMucServer() {
1057		return findDiscoItemByFeature("http://jabber.org/protocol/muc");
1058	}
1059
1060	public int getTimeToNextAttempt() {
1061		int interval = (int) (25 * Math.pow(1.5, attempt));
1062		int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1063		return interval - secondsSinceLast;
1064	}
1065
1066	public int getAttempt() {
1067		return this.attempt;
1068	}
1069
1070	public Features getFeatures() {
1071		return this.features;
1072	}
1073
1074	public long getLastSessionEstablished() {
1075		long diff;
1076		if (this.lastSessionStarted == 0) {
1077			diff = SystemClock.elapsedRealtime() - this.lastConnect;
1078		} else {
1079			diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1080		}
1081		return System.currentTimeMillis() - diff;
1082	}
1083
1084	public long getLastConnect() {
1085		return this.lastConnect;
1086	}
1087
1088	public long getLastPingSent() {
1089		return this.lastPingSent;
1090	}
1091
1092	public long getLastPacketReceived() {
1093		return this.lastPaketReceived;
1094	}
1095
1096	public void sendActive() {
1097		this.sendPacket(new ActivePacket(), null);
1098	}
1099
1100	public void sendInactive() {
1101		this.sendPacket(new InactivePacket(), null);
1102	}
1103
1104	public class Features {
1105		XmppConnection connection;
1106
1107		public Features(XmppConnection connection) {
1108			this.connection = connection;
1109		}
1110
1111		private boolean hasDiscoFeature(final Jid server, final String feature) {
1112			return connection.disco.containsKey(server.toDomainJid().toString()) &&
1113				connection.disco.get(server.toDomainJid().toString()).contains(feature);
1114		}
1115
1116		public boolean carbons() {
1117			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1118		}
1119
1120		public boolean sm() {
1121			return streamId != null;
1122		}
1123
1124		public boolean csi() {
1125			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1126		}
1127
1128		public boolean pubsub() {
1129			return hasDiscoFeature(account.getServer(),
1130					"http://jabber.org/protocol/pubsub#publish");
1131		}
1132
1133		public boolean mam() {
1134			return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1135		}
1136
1137		public boolean rosterVersioning() {
1138			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1139		}
1140
1141		public boolean streamhost() {
1142			return connection
1143				.findDiscoItemByFeature("http://jabber.org/protocol/bytestreams") != null;
1144		}
1145
1146		public boolean compression() {
1147			return connection.usingCompression;
1148		}
1149	}
1150}