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	public void resetEverything() {
 879		resetStreamId();
 880		clearIqCallbacks();
 881		synchronized (this.disco) {
 882			disco.clear();
 883		}
 884	}
 885
 886	private void sendBindRequest() {
 887		while(!mXmppConnectionService.areMessagesInitialized() && socket != null && !socket.isClosed()) {
 888			try {
 889				Thread.sleep(500);
 890			} catch (final InterruptedException ignored) {
 891			}
 892		}
 893		needsBinding = false;
 894		clearIqCallbacks();
 895		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 896		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 897				.addChild("resource").setContent(account.getResource());
 898		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
 899			@Override
 900			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 901				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 902					return;
 903				}
 904				final Element bind = packet.findChild("bind");
 905				if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
 906					final Element jid = bind.findChild("jid");
 907					if (jid != null && jid.getContent() != null) {
 908						try {
 909							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 910						} catch (final InvalidJidException e) {
 911							// TODO: Handle the case where an external JID is technically invalid?
 912						}
 913						if (streamFeatures.hasChild("session")) {
 914							sendStartSession();
 915						} else {
 916							sendPostBindInitialization();
 917						}
 918					} else {
 919						Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 920						disconnect(true);
 921					}
 922				} else {
 923					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 924					disconnect(true);
 925				}
 926			}
 927		});
 928	}
 929
 930	private void clearIqCallbacks() {
 931		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
 932		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 933		synchronized (this.packetCallbacks) {
 934			if (this.packetCallbacks.size() == 0) {
 935				return;
 936			}
 937			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
 938			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
 939			while (iterator.hasNext()) {
 940				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
 941				callbacks.add(entry.second);
 942				iterator.remove();
 943			}
 944		}
 945		for(OnIqPacketReceived callback : callbacks) {
 946			callback.onIqPacketReceived(account,failurePacket);
 947		}
 948		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
 949	}
 950
 951	public void sendDiscoTimeout() {
 952		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR); //don't use timeout
 953		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 954		synchronized (this.mPendingServiceDiscoveriesIds) {
 955			for(String id : mPendingServiceDiscoveriesIds) {
 956				synchronized (this.packetCallbacks) {
 957					Pair<IqPacket, OnIqPacketReceived> pair = this.packetCallbacks.remove(id);
 958					if (pair != null) {
 959						callbacks.add(pair.second);
 960					}
 961				}
 962			}
 963			this.mPendingServiceDiscoveriesIds.clear();
 964		}
 965		if (callbacks.size() > 0) {
 966			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending disco timeout");
 967			resetStreamId(); //we don't want to live with this for ever
 968		}
 969		for(OnIqPacketReceived callback : callbacks) {
 970			callback.onIqPacketReceived(account,failurePacket);
 971		}
 972	}
 973
 974	private void sendStartSession() {
 975		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
 976		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
 977		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
 978			@Override
 979			public void onIqPacketReceived(Account account, IqPacket packet) {
 980				if (packet.getType() == IqPacket.TYPE.RESULT) {
 981					sendPostBindInitialization();
 982				} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
 983					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
 984					disconnect(true);
 985				}
 986			}
 987		});
 988	}
 989
 990	private void sendPostBindInitialization() {
 991		smVersion = 0;
 992		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
 993			smVersion = 3;
 994		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
 995			smVersion = 2;
 996		}
 997		if (smVersion != 0) {
 998			final EnablePacket enable = new EnablePacket(smVersion);
 999			tagWriter.writeStanzaAsync(enable);
1000			stanzasSent = 0;
1001			mStanzaQueue.clear();
1002		}
1003		features.carbonsEnabled = false;
1004		features.blockListRequested = false;
1005		synchronized (this.disco) {
1006			this.disco.clear();
1007		}
1008		mPendingServiceDiscoveries = mServerIdentity == Identity.NIMBUZZ ? 1 : 0;
1009		lastDiscoStarted = SystemClock.elapsedRealtime();
1010		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1011		mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1012		sendServiceDiscoveryItems(account.getServer());
1013		sendServiceDiscoveryInfo(account.getServer());
1014		sendServiceDiscoveryInfo(account.getJid().toBareJid());
1015		this.lastSessionStarted = SystemClock.elapsedRealtime();
1016	}
1017
1018	private void sendServiceDiscoveryInfo(final Jid jid) {
1019		if (mServerIdentity != Identity.NIMBUZZ) {
1020			mPendingServiceDiscoveries++;
1021		}
1022		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1023		iq.setTo(jid);
1024		iq.query("http://jabber.org/protocol/disco#info");
1025		String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1026
1027			@Override
1028			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1029				if (packet.getType() == IqPacket.TYPE.RESULT) {
1030					boolean advancedStreamFeaturesLoaded;
1031					synchronized (XmppConnection.this.disco) {
1032						final List<Element> elements = packet.query().getChildren();
1033						final Info info = new Info();
1034						for (final Element element : elements) {
1035							if (element.getName().equals("identity")) {
1036								String type = element.getAttribute("type");
1037								String category = element.getAttribute("category");
1038								String name = element.getAttribute("name");
1039								if (type != null && category != null) {
1040									info.identities.add(new Pair<>(category, type));
1041									if (mServerIdentity == Identity.UNKNOWN
1042											&& type.equals("im")
1043											&& category.equals("server")) {
1044										if (name != null && jid.equals(account.getServer())) {
1045											switch (name) {
1046												case "Prosody":
1047													mServerIdentity = Identity.PROSODY;
1048													break;
1049												case "ejabberd":
1050													mServerIdentity = Identity.EJABBERD;
1051													break;
1052												case "Slack-XMPP":
1053													mServerIdentity = Identity.SLACK;
1054													break;
1055											}
1056											Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server name: " + name);
1057										}
1058									}
1059								}
1060							} else if (element.getName().equals("feature")) {
1061								info.features.add(element.getAttribute("var"));
1062							}
1063						}
1064						disco.put(jid, info);
1065						advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1066								&& disco.containsKey(account.getJid().toBareJid());
1067					}
1068					if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1069						enableAdvancedStreamFeatures();
1070					}
1071				} else {
1072					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1073				}
1074				if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1075					mPendingServiceDiscoveries--;
1076					if (mPendingServiceDiscoveries == 0) {
1077						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": done with service discovery");
1078						Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1079						changeStatus(Account.State.ONLINE);
1080						if (bindListener != null) {
1081							bindListener.onBind(account);
1082						}
1083					}
1084				}
1085			}
1086		});
1087		synchronized (this.mPendingServiceDiscoveriesIds) {
1088			this.mPendingServiceDiscoveriesIds.add(id);
1089		}
1090	}
1091
1092	private void enableAdvancedStreamFeatures() {
1093		if (getFeatures().carbons() && !features.carbonsEnabled) {
1094			sendEnableCarbons();
1095		}
1096		if (getFeatures().blocking() && !features.blockListRequested) {
1097			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1098			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1099		}
1100		for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1101			listener.onAdvancedStreamFeaturesAvailable(account);
1102		}
1103	}
1104
1105	private void sendServiceDiscoveryItems(final Jid server) {
1106		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1107		iq.setTo(server.toDomainJid());
1108		iq.query("http://jabber.org/protocol/disco#items");
1109		this.sendIqPacket(iq, new OnIqPacketReceived() {
1110
1111			@Override
1112			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1113				if (packet.getType() == IqPacket.TYPE.RESULT) {
1114					final List<Element> elements = packet.query().getChildren();
1115					for (final Element element : elements) {
1116						if (element.getName().equals("item")) {
1117							final Jid jid = element.getAttributeAsJid("jid");
1118							if (jid != null && !jid.equals(account.getServer())) {
1119								sendServiceDiscoveryInfo(jid);
1120							}
1121						}
1122					}
1123				} else {
1124					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1125				}
1126			}
1127		});
1128	}
1129
1130	private void sendEnableCarbons() {
1131		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1132		iq.addChild("enable", "urn:xmpp:carbons:2");
1133		this.sendIqPacket(iq, new OnIqPacketReceived() {
1134
1135			@Override
1136			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1137				if (!packet.hasChild("error")) {
1138					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1139							+ ": successfully enabled carbons");
1140					features.carbonsEnabled = true;
1141				} else {
1142					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1143							+ ": error enableing carbons " + packet.toString());
1144				}
1145			}
1146		});
1147	}
1148
1149	private void processStreamError(final Tag currentTag)
1150		throws XmlPullParserException, IOException {
1151		final Element streamError = tagReader.readElement(currentTag);
1152		if (streamError != null && streamError.hasChild("conflict")) {
1153			final String resource = account.getResource().split("\\.")[0];
1154			account.setResource(resource + "." + nextRandomId());
1155			Log.d(Config.LOGTAG,
1156					account.getJid().toBareJid() + ": switching resource due to conflict ("
1157					+ account.getResource() + ")");
1158		} else if (streamError != null) {
1159			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1160		}
1161	}
1162
1163	private void sendStartStream() throws IOException {
1164		final Tag stream = Tag.start("stream:stream");
1165		stream.setAttribute("to", account.getServer().toString());
1166		stream.setAttribute("version", "1.0");
1167		stream.setAttribute("xml:lang", "en");
1168		stream.setAttribute("xmlns", "jabber:client");
1169		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1170		tagWriter.writeTag(stream);
1171	}
1172
1173	private String nextRandomId() {
1174		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1175	}
1176
1177	public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1178		packet.setFrom(account.getJid());
1179		return this.sendUnmodifiedIqPacket(packet, callback);
1180	}
1181
1182	private synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1183		if (packet.getId() == null) {
1184			final String id = nextRandomId();
1185			packet.setAttribute("id", id);
1186		}
1187		if (callback != null) {
1188			synchronized (this.packetCallbacks) {
1189				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1190			}
1191		}
1192		this.sendPacket(packet);
1193		return packet.getId();
1194	}
1195
1196	public void sendMessagePacket(final MessagePacket packet) {
1197		this.sendPacket(packet);
1198	}
1199
1200	public void sendPresencePacket(final PresencePacket packet) {
1201		this.sendPacket(packet);
1202	}
1203
1204	private synchronized void sendPacket(final AbstractStanza packet) {
1205		if (stanzasSent == Integer.MAX_VALUE) {
1206			resetStreamId();
1207			disconnect(true);
1208			return;
1209		}
1210		tagWriter.writeStanzaAsync(packet);
1211		if (packet instanceof AbstractAcknowledgeableStanza) {
1212			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1213			++stanzasSent;
1214			this.mStanzaQueue.put(stanzasSent, stanza);
1215			if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1216				if (Config.EXTENDED_SM_LOGGING) {
1217					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1218				}
1219				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1220			}
1221		}
1222	}
1223
1224	public void sendPing() {
1225		if (!r()) {
1226			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1227			iq.setFrom(account.getJid());
1228			iq.addChild("ping", "urn:xmpp:ping");
1229			this.sendIqPacket(iq, null);
1230		}
1231		this.lastPingSent = SystemClock.elapsedRealtime();
1232	}
1233
1234	public void setOnMessagePacketReceivedListener(
1235			final OnMessagePacketReceived listener) {
1236		this.messageListener = listener;
1237			}
1238
1239	public void setOnUnregisteredIqPacketReceivedListener(
1240			final OnIqPacketReceived listener) {
1241		this.unregisteredIqListener = listener;
1242			}
1243
1244	public void setOnPresencePacketReceivedListener(
1245			final OnPresencePacketReceived listener) {
1246		this.presenceListener = listener;
1247			}
1248
1249	public void setOnJinglePacketReceivedListener(
1250			final OnJinglePacketReceived listener) {
1251		this.jingleListener = listener;
1252			}
1253
1254	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1255		this.statusListener = listener;
1256	}
1257
1258	public void setOnBindListener(final OnBindListener listener) {
1259		this.bindListener = listener;
1260	}
1261
1262	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1263		this.acknowledgedListener = listener;
1264	}
1265
1266	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1267		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1268			this.advancedStreamFeaturesLoadedListeners.add(listener);
1269		}
1270	}
1271
1272	public void disconnect(final boolean force) {
1273		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1274		if (force) {
1275			try {
1276				socket.close();
1277			} catch(Exception e) {
1278				Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": exception during force close ("+e.getMessage()+")");
1279			}
1280			return;
1281		} else {
1282			resetStreamId();
1283			if (tagWriter.isActive()) {
1284				tagWriter.finish();
1285				try {
1286					int i = 0;
1287					boolean warned = false;
1288					while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1289						if (!warned) {
1290							Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1291							warned = true;
1292						}
1293						Thread.sleep(200);
1294						i++;
1295					}
1296					if (warned) {
1297						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1298					}
1299					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1300					tagWriter.writeTag(Tag.end("stream:stream"));
1301				} catch (final IOException e) {
1302					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1303				} catch (final InterruptedException e) {
1304					Log.d(Config.LOGTAG, "interrupted");
1305				}
1306			}
1307		}
1308	}
1309
1310	public void resetStreamId() {
1311		this.streamId = null;
1312	}
1313
1314	public List<Jid> findDiscoItemsByFeature(final String feature) {
1315		synchronized (this.disco) {
1316			final List<Jid> items = new ArrayList<>();
1317			for (final Entry<Jid, Info> cursor : this.disco.entrySet()) {
1318				if (cursor.getValue().features.contains(feature)) {
1319					items.add(cursor.getKey());
1320				}
1321			}
1322			return items;
1323		}
1324	}
1325
1326	public Jid findDiscoItemByFeature(final String feature) {
1327		final List<Jid> items = findDiscoItemsByFeature(feature);
1328		if (items.size() >= 1) {
1329			return items.get(0);
1330		}
1331		return null;
1332	}
1333
1334	public boolean r() {
1335		if (getFeatures().sm()) {
1336			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1337			return true;
1338		} else {
1339			return false;
1340		}
1341	}
1342
1343	public String getMucServer() {
1344		synchronized (this.disco) {
1345			for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1346				final Info value = cursor.getValue();
1347				if (value.features.contains("http://jabber.org/protocol/muc")
1348						&& !value.features.contains("jabber:iq:gateway")
1349						&& !value.identities.contains(new Pair<>("conference", "irc"))) {
1350					return cursor.getKey().toString();
1351				}
1352			}
1353		}
1354		return null;
1355	}
1356
1357	public int getTimeToNextAttempt() {
1358		final int interval = (int) (25 * Math.pow(1.5, attempt));
1359		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1360		return interval - secondsSinceLast;
1361	}
1362
1363	public int getAttempt() {
1364		return this.attempt;
1365	}
1366
1367	public Features getFeatures() {
1368		return this.features;
1369	}
1370
1371	public long getLastSessionEstablished() {
1372		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1373		return System.currentTimeMillis() - diff;
1374	}
1375
1376	public long getLastConnect() {
1377		return this.lastConnect;
1378	}
1379
1380	public long getLastPingSent() {
1381		return this.lastPingSent;
1382	}
1383
1384	public long getLastDiscoStarted() {
1385		return this.lastDiscoStarted;
1386	}
1387	public long getLastPacketReceived() {
1388		return this.lastPacketReceived;
1389	}
1390
1391	public void sendActive() {
1392		this.sendPacket(new ActivePacket());
1393	}
1394
1395	public void sendInactive() {
1396		this.sendPacket(new InactivePacket());
1397	}
1398
1399	public void resetAttemptCount() {
1400		this.attempt = 0;
1401		this.lastConnect = 0;
1402	}
1403
1404	public void setInteractive(boolean interactive) {
1405		this.mInteractive = interactive;
1406	}
1407
1408	public Identity getServerIdentity() {
1409		return mServerIdentity;
1410	}
1411
1412	private class Info {
1413		public final ArrayList<String> features = new ArrayList<>();
1414		public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1415	}
1416
1417	private class UnauthorizedException extends IOException {
1418
1419	}
1420
1421	private class SecurityException extends IOException {
1422
1423	}
1424
1425	private class IncompatibleServerException extends IOException {
1426
1427	}
1428
1429	public enum Identity {
1430		FACEBOOK,
1431		SLACK,
1432		EJABBERD,
1433		PROSODY,
1434		NIMBUZZ,
1435		UNKNOWN
1436	}
1437
1438	public class Features {
1439		XmppConnection connection;
1440		private boolean carbonsEnabled = false;
1441		private boolean encryptionEnabled = false;
1442		private boolean blockListRequested = false;
1443
1444		public Features(final XmppConnection connection) {
1445			this.connection = connection;
1446		}
1447
1448		private boolean hasDiscoFeature(final Jid server, final String feature) {
1449			synchronized (XmppConnection.this.disco) {
1450				return connection.disco.containsKey(server) &&
1451						connection.disco.get(server).features.contains(feature);
1452			}
1453		}
1454
1455		public boolean carbons() {
1456			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1457		}
1458
1459		public boolean blocking() {
1460			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1461		}
1462
1463		public boolean register() {
1464			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1465		}
1466
1467		public boolean sm() {
1468			return streamId != null
1469					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1470		}
1471
1472		public boolean csi() {
1473			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1474		}
1475
1476		public boolean pep() {
1477			synchronized (XmppConnection.this.disco) {
1478				final Pair<String, String> needle = new Pair<>("pubsub", "pep");
1479				Info info = disco.get(account.getServer());
1480				if (info != null && info.identities.contains(needle)) {
1481					return true;
1482				} else {
1483					info = disco.get(account.getJid().toBareJid());
1484					return info != null && info.identities.contains(needle);
1485				}
1486			}
1487		}
1488
1489		public boolean mam() {
1490			if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1491				return true;
1492			} else {
1493				return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1494			}
1495		}
1496
1497		public boolean advancedStreamFeaturesLoaded() {
1498			synchronized (XmppConnection.this.disco) {
1499				return disco.containsKey(account.getServer());
1500			}
1501		}
1502
1503		public boolean rosterVersioning() {
1504			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1505		}
1506
1507		public void setBlockListRequested(boolean value) {
1508			this.blockListRequested = value;
1509		}
1510
1511		public boolean httpUpload() {
1512			return !Config.DISABLE_HTTP_UPLOAD && findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1513		}
1514	}
1515
1516	private IqGenerator getIqGenerator() {
1517		return mXmppConnectionService.getIqGenerator();
1518	}
1519}