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