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