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