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