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