XmppConnection.java

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