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