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