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					final int serverCount = Integer.parseInt(h);
 510					if (serverCount != stanzasSent) {
 511						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 512								+ ": session resumed with lost packages");
 513						stanzasSent = serverCount;
 514					} else {
 515						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
 516					}
 517					acknowledgeStanzaUpTo(serverCount);
 518					ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 519					for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
 520						failedStanzas.add(mStanzaQueue.valueAt(i));
 521					}
 522					mStanzaQueue.clear();
 523					Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
 524					for(AbstractAcknowledgeableStanza packet : failedStanzas) {
 525						if (packet instanceof MessagePacket) {
 526							MessagePacket message = (MessagePacket) packet;
 527							mXmppConnectionService.markMessage(account,
 528									message.getTo().toBareJid(),
 529									message.getId(),
 530									Message.STATUS_UNSEND);
 531						}
 532						sendPacket(packet);
 533					}
 534				} catch (final NumberFormatException ignored) {
 535				}
 536				Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
 537				changeStatus(Account.State.ONLINE);
 538			} else if (nextTag.isStart("r")) {
 539				tagReader.readElement(nextTag);
 540				if (Config.EXTENDED_SM_LOGGING) {
 541					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 542				}
 543				final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 544				tagWriter.writeStanzaAsync(ack);
 545			} else if (nextTag.isStart("a")) {
 546				final Element ack = tagReader.readElement(nextTag);
 547				lastPacketReceived = SystemClock.elapsedRealtime();
 548				try {
 549					final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 550					acknowledgeStanzaUpTo(serverSequence);
 551				} catch (NumberFormatException | NullPointerException e) {
 552					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
 553				}
 554			} else if (nextTag.isStart("failed")) {
 555				Element failed = tagReader.readElement(nextTag);
 556				try {
 557					final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 558					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed but server acknowledged stanza #"+serverCount);
 559					acknowledgeStanzaUpTo(serverCount);
 560				} catch (NumberFormatException | NullPointerException e) {
 561					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": resumption failed");
 562				}
 563				resetStreamId();
 564				if (account.getStatus() != Account.State.ONLINE) {
 565					sendBindRequest();
 566				}
 567			} else if (nextTag.isStart("iq")) {
 568				processIq(nextTag);
 569			} else if (nextTag.isStart("message")) {
 570				processMessage(nextTag);
 571			} else if (nextTag.isStart("presence")) {
 572				processPresence(nextTag);
 573			}
 574			nextTag = tagReader.readTag();
 575		}
 576	}
 577
 578	private void acknowledgeStanzaUpTo(int serverCount) {
 579		for (int i = 0; i < mStanzaQueue.size(); ++i) {
 580			if (serverCount >= mStanzaQueue.keyAt(i)) {
 581				if (Config.EXTENDED_SM_LOGGING) {
 582					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 583				}
 584				AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 585				if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 586					MessagePacket packet = (MessagePacket) stanza;
 587					acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 588				}
 589				mStanzaQueue.removeAt(i);
 590				i--;
 591			}
 592		}
 593	}
 594
 595	private Element processPacket(final Tag currentTag, final int packetType)
 596		throws XmlPullParserException, IOException {
 597		Element element;
 598		switch (packetType) {
 599			case PACKET_IQ:
 600				element = new IqPacket();
 601				break;
 602			case PACKET_MESSAGE:
 603				element = new MessagePacket();
 604				break;
 605			case PACKET_PRESENCE:
 606				element = new PresencePacket();
 607				break;
 608			default:
 609				return null;
 610		}
 611		element.setAttributes(currentTag.getAttributes());
 612		Tag nextTag = tagReader.readTag();
 613		if (nextTag == null) {
 614			throw new IOException("interrupted mid tag");
 615		}
 616		while (!nextTag.isEnd(element.getName())) {
 617			if (!nextTag.isNo()) {
 618				final Element child = tagReader.readElement(nextTag);
 619				final String type = currentTag.getAttribute("type");
 620				if (packetType == PACKET_IQ
 621						&& "jingle".equals(child.getName())
 622						&& ("set".equalsIgnoreCase(type) || "get"
 623							.equalsIgnoreCase(type))) {
 624					element = new JinglePacket();
 625					element.setAttributes(currentTag.getAttributes());
 626							}
 627				element.addChild(child);
 628			}
 629			nextTag = tagReader.readTag();
 630			if (nextTag == null) {
 631				throw new IOException("interrupted mid tag");
 632			}
 633		}
 634		if (stanzasReceived == Integer.MAX_VALUE) {
 635			resetStreamId();
 636			throw new IOException("time to restart the session. cant handle >2 billion pcks");
 637		}
 638		++stanzasReceived;
 639		lastPacketReceived = SystemClock.elapsedRealtime();
 640		if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 641			Log.d(Config.LOGTAG,"[background stanza] "+element);
 642		}
 643		return element;
 644	}
 645
 646	private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 647		final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 648
 649		if (packet.getId() == null) {
 650			return; // an iq packet without id is definitely invalid
 651		}
 652
 653		if (packet instanceof JinglePacket) {
 654			if (this.jingleListener != null) {
 655				this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
 656			}
 657		} else {
 658			OnIqPacketReceived callback = null;
 659			synchronized (this.packetCallbacks) {
 660				if (packetCallbacks.containsKey(packet.getId())) {
 661					final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 662					// Packets to the server should have responses from the server
 663					if (packetCallbackDuple.first.toServer(account)) {
 664						if (packet.fromServer(account) || mServerIdentity == Identity.FACEBOOK) {
 665							callback = packetCallbackDuple.second;
 666							packetCallbacks.remove(packet.getId());
 667						} else {
 668							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 669						}
 670					} else {
 671						if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 672							callback = packetCallbackDuple.second;
 673							packetCallbacks.remove(packet.getId());
 674						} else {
 675							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 676						}
 677					}
 678				} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 679					callback = this.unregisteredIqListener;
 680				}
 681			}
 682			if (callback != null) {
 683				callback.onIqPacketReceived(account,packet);
 684			}
 685		}
 686	}
 687
 688	private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 689		final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
 690		this.messageListener.onMessagePacketReceived(account, packet);
 691	}
 692
 693	private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 694		PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 695		this.presenceListener.onPresencePacketReceived(account, packet);
 696	}
 697
 698	private void sendStartTLS() throws IOException {
 699		final Tag startTLS = Tag.empty("starttls");
 700		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
 701		tagWriter.writeTag(startTLS);
 702	}
 703
 704
 705
 706	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
 707		tagReader.readTag();
 708		try {
 709			final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
 710			final InetAddress address = socket == null ? null : socket.getInetAddress();
 711
 712			if (address == null) {
 713				throw new IOException("could not setup ssl");
 714			}
 715
 716			final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 717
 718			if (sslSocket == null) {
 719				throw new IOException("could not initialize ssl socket");
 720			}
 721
 722			SSLSocketHelper.setSecurity(sslSocket);
 723
 724			if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), sslSocket.getSession())) {
 725				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 726				throw new SecurityException();
 727			}
 728			tagReader.setInputStream(sslSocket.getInputStream());
 729			tagWriter.setOutputStream(sslSocket.getOutputStream());
 730			sendStartStream();
 731			Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
 732			features.encryptionEnabled = true;
 733			final Tag tag = tagReader.readTag();
 734			if (tag != null && tag.isStart("stream")) {
 735				processStream();
 736			} else {
 737				throw new IOException("server didn't restart stream after STARTTLS");
 738			}
 739			sslSocket.close();
 740		} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 741			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
 742			throw new SecurityException();
 743		}
 744	}
 745
 746	private void processStreamFeatures(final Tag currentTag)
 747		throws XmlPullParserException, IOException {
 748		this.streamFeatures = tagReader.readElement(currentTag);
 749		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 750			sendStartTLS();
 751		} else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 752			if (features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS) {
 753				sendRegistryRequest();
 754			} else {
 755				throw new IncompatibleServerException();
 756			}
 757		} else if (!this.streamFeatures.hasChild("register")
 758				&& account.isOptionSet(Account.OPTION_REGISTER)) {
 759			forceCloseSocket();
 760			changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
 761		} else if (this.streamFeatures.hasChild("mechanisms")
 762				&& shouldAuthenticate
 763				&& (features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS)) {
 764			authenticate();
 765		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 766			if (Config.EXTENDED_SM_LOGGING) {
 767				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
 768			}
 769			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 770			this.tagWriter.writeStanzaAsync(resume);
 771		} else if (needsBinding) {
 772			if (this.streamFeatures.hasChild("bind")) {
 773				sendBindRequest();
 774			} else {
 775				throw new IncompatibleServerException();
 776			}
 777		}
 778	}
 779
 780	private void authenticate() throws IOException {
 781		final List<String> mechanisms = extractMechanisms(streamFeatures
 782				.findChild("mechanisms"));
 783		final Element auth = new Element("auth");
 784		auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
 785		if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 786			saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 787		} else if (mechanisms.contains("SCRAM-SHA-1")) {
 788			saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 789		} else if (mechanisms.contains("PLAIN")) {
 790			saslMechanism = new Plain(tagWriter, account);
 791		} else if (mechanisms.contains("DIGEST-MD5")) {
 792			saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 793		}
 794		if (saslMechanism != null) {
 795			final JSONObject keys = account.getKeys();
 796			try {
 797				if (keys.has(Account.PINNED_MECHANISM_KEY) &&
 798						keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
 799					Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 800							" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 801							") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
 802							"). Possible downgrade attack?");
 803					throw new SecurityException();
 804				}
 805			} catch (final JSONException e) {
 806				Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
 807			}
 808			Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 809			auth.setAttribute("mechanism", saslMechanism.getMechanism());
 810			if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 811				auth.setContent(saslMechanism.getClientFirstMessage());
 812			}
 813			tagWriter.writeElement(auth);
 814		} else {
 815			throw new IncompatibleServerException();
 816		}
 817	}
 818
 819	private List<String> extractMechanisms(final Element stream) {
 820		final ArrayList<String> mechanisms = new ArrayList<>(stream
 821				.getChildren().size());
 822		for (final Element child : stream.getChildren()) {
 823			mechanisms.add(child.getContent());
 824		}
 825		return mechanisms;
 826	}
 827
 828	private void sendRegistryRequest() {
 829		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 830		register.query("jabber:iq:register");
 831		register.setTo(account.getServer());
 832		sendIqPacket(register, new OnIqPacketReceived() {
 833
 834			@Override
 835			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 836				boolean failed = false;
 837				if (packet.getType() == IqPacket.TYPE.RESULT
 838						&& packet.query().hasChild("username")
 839						&& (packet.query().hasChild("password"))) {
 840					final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
 841					final Element username = new Element("username").setContent(account.getUsername());
 842					final Element password = new Element("password").setContent(account.getPassword());
 843					register.query("jabber:iq:register").addChild(username);
 844					register.query().addChild(password);
 845					sendIqPacket(register, registrationResponseListener);
 846				} else if (packet.getType() == IqPacket.TYPE.RESULT
 847						&& (packet.query().hasChild("x", "jabber:x:data"))) {
 848					final Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
 849					final Element blob = packet.query().findChild("data", "urn:xmpp:bob");
 850					final String id = packet.getId();
 851
 852					Bitmap captcha = null;
 853					if (blob != null) {
 854						try {
 855							final String base64Blob = blob.getContent();
 856							final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 857							InputStream stream = new ByteArrayInputStream(strBlob);
 858							captcha = BitmapFactory.decodeStream(stream);
 859						} catch (Exception e) {
 860							//ignored
 861						}
 862					} else {
 863						try {
 864							Field url = data.getFieldByName("url");
 865							String urlString = url.findChildContent("value");
 866							URL uri = new URL(urlString);
 867							captcha = BitmapFactory.decodeStream(uri.openConnection().getInputStream());
 868						} catch (IOException e) {
 869							Log.e(Config.LOGTAG, e.toString());
 870						}
 871					}
 872
 873					if (captcha != null) {
 874						failed = !mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha);
 875					}
 876				} else {
 877					failed = true;
 878				}
 879
 880				if (failed) {
 881					final Element instructions = packet.query().findChild("instructions");
 882					setAccountCreationFailed((instructions != null) ? instructions.getContent() : "");
 883				}
 884			}
 885		});
 886	}
 887
 888	private void setAccountCreationFailed(String instructions) {
 889		changeStatus(Account.State.REGISTRATION_FAILED);
 890		disconnect(true);
 891		Log.d(Config.LOGTAG, account.getJid().toBareJid()
 892				+ ": could not register. instructions are"
 893				+ instructions);
 894	}
 895
 896	public void resetEverything() {
 897		resetAttemptCount();
 898		resetStreamId();
 899		clearIqCallbacks();
 900		mStanzaQueue.clear();
 901		synchronized (this.disco) {
 902			disco.clear();
 903		}
 904	}
 905
 906	private void sendBindRequest() {
 907		while(!mXmppConnectionService.areMessagesInitialized() && socket != null && !socket.isClosed()) {
 908			try {
 909				Thread.sleep(500);
 910			} catch (final InterruptedException ignored) {
 911			}
 912		}
 913		needsBinding = false;
 914		clearIqCallbacks();
 915		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 916		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 917				.addChild("resource").setContent(account.getResource());
 918		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
 919			@Override
 920			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 921				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 922					return;
 923				}
 924				final Element bind = packet.findChild("bind");
 925				if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
 926					final Element jid = bind.findChild("jid");
 927					if (jid != null && jid.getContent() != null) {
 928						try {
 929							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 930							if (streamFeatures.hasChild("session")
 931									&& !streamFeatures.findChild("session").hasChild("optional")) {
 932								sendStartSession();
 933							} else {
 934								sendPostBindInitialization();
 935							}
 936							return;
 937						} catch (final InvalidJidException e) {
 938							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server reported invalid jid ("+jid.getContent()+") on bind");
 939						}
 940					} else {
 941						Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
 942					}
 943				} else {
 944					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
 945				}
 946				forceCloseSocket();
 947				changeStatus(Account.State.BIND_FAILURE);
 948			}
 949		});
 950	}
 951
 952	private void clearIqCallbacks() {
 953		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
 954		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 955		synchronized (this.packetCallbacks) {
 956			if (this.packetCallbacks.size() == 0) {
 957				return;
 958			}
 959			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
 960			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
 961			while (iterator.hasNext()) {
 962				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
 963				callbacks.add(entry.second);
 964				iterator.remove();
 965			}
 966		}
 967		for(OnIqPacketReceived callback : callbacks) {
 968			callback.onIqPacketReceived(account,failurePacket);
 969		}
 970		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
 971	}
 972
 973	public void sendDiscoTimeout() {
 974		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR); //don't use timeout
 975		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 976		synchronized (this.mPendingServiceDiscoveriesIds) {
 977			for(String id : mPendingServiceDiscoveriesIds) {
 978				synchronized (this.packetCallbacks) {
 979					Pair<IqPacket, OnIqPacketReceived> pair = this.packetCallbacks.remove(id);
 980					if (pair != null) {
 981						callbacks.add(pair.second);
 982					}
 983				}
 984			}
 985			this.mPendingServiceDiscoveriesIds.clear();
 986		}
 987		if (callbacks.size() > 0) {
 988			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending disco timeout");
 989			resetStreamId(); //we don't want to live with this for ever
 990		}
 991		for(OnIqPacketReceived callback : callbacks) {
 992			callback.onIqPacketReceived(account,failurePacket);
 993		}
 994	}
 995
 996	private void sendStartSession() {
 997		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending legacy session to outdated server");
 998		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
 999		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1000		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
1001			@Override
1002			public void onIqPacketReceived(Account account, IqPacket packet) {
1003				if (packet.getType() == IqPacket.TYPE.RESULT) {
1004					sendPostBindInitialization();
1005				} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1006					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
1007					disconnect(true);
1008				}
1009			}
1010		});
1011	}
1012
1013	private void sendPostBindInitialization() {
1014		smVersion = 0;
1015		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1016			smVersion = 3;
1017		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1018			smVersion = 2;
1019		}
1020		if (smVersion != 0) {
1021			final EnablePacket enable = new EnablePacket(smVersion);
1022			tagWriter.writeStanzaAsync(enable);
1023			stanzasSent = 0;
1024			mStanzaQueue.clear();
1025		}
1026		features.carbonsEnabled = false;
1027		features.blockListRequested = false;
1028		synchronized (this.disco) {
1029			this.disco.clear();
1030		}
1031		mPendingServiceDiscoveries.set(0);
1032		mIsServiceItemsDiscoveryPending.set(true);
1033		mWaitForDisco = mServerIdentity != Identity.NIMBUZZ;
1034		lastDiscoStarted = SystemClock.elapsedRealtime();
1035		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1036		mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1037		Element caps = streamFeatures.findChild("c");
1038		final String hash = caps == null ? null : caps.getAttribute("hash");
1039		final String ver = caps == null ? null : caps.getAttribute("ver");
1040		ServiceDiscoveryResult discoveryResult = null;
1041		if (hash != null && ver != null) {
1042			discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1043		}
1044		if (discoveryResult == null) {
1045			sendServiceDiscoveryInfo(account.getServer());
1046		} else {
1047			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server caps came from cache");
1048			disco.put(account.getServer(), discoveryResult);
1049		}
1050		sendServiceDiscoveryInfo(account.getJid().toBareJid());
1051		sendServiceDiscoveryItems(account.getServer());
1052		if (!mWaitForDisco) {
1053			finalizeBind();
1054		}
1055		this.lastSessionStarted = SystemClock.elapsedRealtime();
1056	}
1057
1058	private void sendServiceDiscoveryInfo(final Jid jid) {
1059		mPendingServiceDiscoveries.incrementAndGet();
1060		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1061		iq.setTo(jid);
1062		iq.query("http://jabber.org/protocol/disco#info");
1063		String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1064
1065			@Override
1066			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1067				if (packet.getType() == IqPacket.TYPE.RESULT) {
1068					boolean advancedStreamFeaturesLoaded;
1069					synchronized (XmppConnection.this.disco) {
1070						ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1071						for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1072							if (mServerIdentity == Identity.UNKNOWN && id.getType().equals("im") &&
1073							    id.getCategory().equals("server") && id.getName() != null &&
1074							    jid.equals(account.getServer())) {
1075									switch (id.getName()) {
1076										case "Prosody":
1077											mServerIdentity = Identity.PROSODY;
1078											break;
1079										case "ejabberd":
1080											mServerIdentity = Identity.EJABBERD;
1081											break;
1082										case "Slack-XMPP":
1083											mServerIdentity = Identity.SLACK;
1084											break;
1085									}
1086									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server name: " + id.getName());
1087								}
1088						}
1089						if (jid.equals(account.getServer())) {
1090							mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1091						}
1092						disco.put(jid, result);
1093						advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1094								&& disco.containsKey(account.getJid().toBareJid());
1095					}
1096					if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1097						enableAdvancedStreamFeatures();
1098					}
1099				} else {
1100					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1101				}
1102				if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1103					if (mPendingServiceDiscoveries.decrementAndGet() == 0
1104							&& !mIsServiceItemsDiscoveryPending.get()
1105							&& mWaitForDisco) {
1106						finalizeBind();
1107					}
1108				}
1109			}
1110		});
1111		synchronized (this.mPendingServiceDiscoveriesIds) {
1112			this.mPendingServiceDiscoveriesIds.add(id);
1113		}
1114	}
1115
1116	private void finalizeBind() {
1117		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1118		if (bindListener != null) {
1119			bindListener.onBind(account);
1120		}
1121		changeStatus(Account.State.ONLINE);
1122	}
1123
1124	private void enableAdvancedStreamFeatures() {
1125		if (getFeatures().carbons() && !features.carbonsEnabled) {
1126			sendEnableCarbons();
1127		}
1128		if (getFeatures().blocking() && !features.blockListRequested) {
1129			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1130			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1131		}
1132		for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1133			listener.onAdvancedStreamFeaturesAvailable(account);
1134		}
1135	}
1136
1137	private void sendServiceDiscoveryItems(final Jid server) {
1138		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1139		iq.setTo(server.toDomainJid());
1140		iq.query("http://jabber.org/protocol/disco#items");
1141		String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1142
1143			@Override
1144			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1145				if (packet.getType() == IqPacket.TYPE.RESULT) {
1146					final List<Element> elements = packet.query().getChildren();
1147					for (final Element element : elements) {
1148						if (element.getName().equals("item")) {
1149							final Jid jid = element.getAttributeAsJid("jid");
1150							if (jid != null && !jid.equals(account.getServer())) {
1151								sendServiceDiscoveryInfo(jid);
1152							}
1153						}
1154					}
1155				} else {
1156					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1157				}
1158				if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1159					mIsServiceItemsDiscoveryPending.set(false);
1160					if (mPendingServiceDiscoveries.get() == 0 && mWaitForDisco) {
1161						finalizeBind();
1162					}
1163				}
1164			}
1165		});
1166		synchronized (this.mPendingServiceDiscoveriesIds) {
1167			this.mPendingServiceDiscoveriesIds.add(id);
1168		}
1169	}
1170
1171	private void sendEnableCarbons() {
1172		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1173		iq.addChild("enable", "urn:xmpp:carbons:2");
1174		this.sendIqPacket(iq, new OnIqPacketReceived() {
1175
1176			@Override
1177			public void onIqPacketReceived(final Account account, final IqPacket packet) {
1178				if (!packet.hasChild("error")) {
1179					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1180							+ ": successfully enabled carbons");
1181					features.carbonsEnabled = true;
1182				} else {
1183					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1184							+ ": error enableing carbons " + packet.toString());
1185				}
1186			}
1187		});
1188	}
1189
1190	private void processStreamError(final Tag currentTag)
1191		throws XmlPullParserException, IOException {
1192		final Element streamError = tagReader.readElement(currentTag);
1193		if (streamError == null) {
1194			return;
1195		}
1196		Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1197		if (streamError.hasChild("conflict")) {
1198			final String resource = account.getResource().split("\\.")[0];
1199			account.setResource(resource + "." + nextRandomId());
1200			Log.d(Config.LOGTAG,
1201					account.getJid().toBareJid() + ": switching resource due to conflict ("
1202					+ account.getResource() + ")");
1203		} else if (streamError.hasChild("host-unknown")) {
1204			changeStatus(Account.State.HOST_UNKNOWN);
1205		}
1206		forceCloseSocket();
1207	}
1208
1209	private void sendStartStream() throws IOException {
1210		final Tag stream = Tag.start("stream:stream");
1211		stream.setAttribute("to", account.getServer().toString());
1212		stream.setAttribute("version", "1.0");
1213		stream.setAttribute("xml:lang", "en");
1214		stream.setAttribute("xmlns", "jabber:client");
1215		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1216		tagWriter.writeTag(stream);
1217	}
1218
1219	private String nextRandomId() {
1220		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1221	}
1222
1223	public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1224		packet.setFrom(account.getJid());
1225		return this.sendUnmodifiedIqPacket(packet, callback);
1226	}
1227
1228	private synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1229		if (packet.getId() == null) {
1230			final String id = nextRandomId();
1231			packet.setAttribute("id", id);
1232		}
1233		if (callback != null) {
1234			synchronized (this.packetCallbacks) {
1235				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1236			}
1237		}
1238		this.sendPacket(packet);
1239		return packet.getId();
1240	}
1241
1242	public void sendMessagePacket(final MessagePacket packet) {
1243		this.sendPacket(packet);
1244	}
1245
1246	public void sendPresencePacket(final PresencePacket packet) {
1247		this.sendPacket(packet);
1248	}
1249
1250	private synchronized void sendPacket(final AbstractStanza packet) {
1251		if (stanzasSent == Integer.MAX_VALUE) {
1252			resetStreamId();
1253			disconnect(true);
1254			return;
1255		}
1256		tagWriter.writeStanzaAsync(packet);
1257		if (packet instanceof AbstractAcknowledgeableStanza) {
1258			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1259			++stanzasSent;
1260			this.mStanzaQueue.put(stanzasSent, stanza);
1261			if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1262				if (Config.EXTENDED_SM_LOGGING) {
1263					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1264				}
1265				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1266			}
1267		}
1268	}
1269
1270	public void sendPing() {
1271		if (!r()) {
1272			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1273			iq.setFrom(account.getJid());
1274			iq.addChild("ping", "urn:xmpp:ping");
1275			this.sendIqPacket(iq, null);
1276		}
1277		this.lastPingSent = SystemClock.elapsedRealtime();
1278	}
1279
1280	public void setOnMessagePacketReceivedListener(
1281			final OnMessagePacketReceived listener) {
1282		this.messageListener = listener;
1283			}
1284
1285	public void setOnUnregisteredIqPacketReceivedListener(
1286			final OnIqPacketReceived listener) {
1287		this.unregisteredIqListener = listener;
1288			}
1289
1290	public void setOnPresencePacketReceivedListener(
1291			final OnPresencePacketReceived listener) {
1292		this.presenceListener = listener;
1293			}
1294
1295	public void setOnJinglePacketReceivedListener(
1296			final OnJinglePacketReceived listener) {
1297		this.jingleListener = listener;
1298			}
1299
1300	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1301		this.statusListener = listener;
1302	}
1303
1304	public void setOnBindListener(final OnBindListener listener) {
1305		this.bindListener = listener;
1306	}
1307
1308	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1309		this.acknowledgedListener = listener;
1310	}
1311
1312	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1313		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1314			this.advancedStreamFeaturesLoadedListeners.add(listener);
1315		}
1316	}
1317
1318	public void waitForPush() {
1319		if (tagWriter.isActive()) {
1320			tagWriter.finish();
1321			new Thread(new Runnable() {
1322				@Override
1323				public void run() {
1324					try {
1325						while(!tagWriter.finished()) {
1326							Thread.sleep(10);
1327						}
1328						socket.close();
1329						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closed tcp without closing stream");
1330					} catch (IOException | InterruptedException e) {
1331						return;
1332					}
1333				}
1334			}).start();
1335		} else {
1336			forceCloseSocket();
1337			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closed tcp without closing stream (no waiting)");
1338		}
1339	}
1340
1341	private void forceCloseSocket() {
1342		if (socket != null) {
1343			try {
1344				socket.close();
1345			} catch (IOException e) {
1346				e.printStackTrace();
1347			}
1348		}
1349	}
1350
1351	public void interrupt() {
1352		Thread.currentThread().interrupt();
1353	}
1354
1355	public void disconnect(final boolean force) {
1356		interrupt();
1357		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1358		if (force) {
1359			tagWriter.forceClose();
1360			forceCloseSocket();
1361		} else {
1362			if (tagWriter.isActive()) {
1363				tagWriter.finish();
1364				try {
1365					int i = 0;
1366					boolean warned = false;
1367					while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1368						if (!warned) {
1369							Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1370							warned = true;
1371						}
1372						Thread.sleep(200);
1373						i++;
1374					}
1375					if (warned) {
1376						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1377					}
1378					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1379					tagWriter.writeTag(Tag.end("stream:stream"));
1380				} catch (final IOException e) {
1381					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1382				} catch (final InterruptedException e) {
1383					Log.d(Config.LOGTAG, "interrupted");
1384				}
1385			}
1386		}
1387	}
1388
1389	public void resetStreamId() {
1390		this.streamId = null;
1391	}
1392
1393	private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1394		synchronized (this.disco) {
1395			final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1396			for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1397				if (cursor.getValue().getFeatures().contains(feature)) {
1398					items.add(cursor);
1399				}
1400			}
1401			return items;
1402		}
1403	}
1404
1405	public Jid findDiscoItemByFeature(final String feature) {
1406		final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1407		if (items.size() >= 1) {
1408			return items.get(0).getKey();
1409		}
1410		return null;
1411	}
1412
1413	public boolean r() {
1414		if (getFeatures().sm()) {
1415			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1416			return true;
1417		} else {
1418			return false;
1419		}
1420	}
1421
1422	public String getMucServer() {
1423		synchronized (this.disco) {
1424			for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1425				final ServiceDiscoveryResult value = cursor.getValue();
1426				if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1427						&& !value.getFeatures().contains("jabber:iq:gateway")
1428						&& !value.hasIdentity("conference", "irc")) {
1429					return cursor.getKey().toString();
1430				}
1431			}
1432		}
1433		return null;
1434	}
1435
1436	public int getTimeToNextAttempt() {
1437		final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1438		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1439		return interval - secondsSinceLast;
1440	}
1441
1442	public int getAttempt() {
1443		return this.attempt;
1444	}
1445
1446	public Features getFeatures() {
1447		return this.features;
1448	}
1449
1450	public long getLastSessionEstablished() {
1451		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1452		return System.currentTimeMillis() - diff;
1453	}
1454
1455	public long getLastConnect() {
1456		return this.lastConnect;
1457	}
1458
1459	public long getLastPingSent() {
1460		return this.lastPingSent;
1461	}
1462
1463	public long getLastDiscoStarted() {
1464		return this.lastDiscoStarted;
1465	}
1466	public long getLastPacketReceived() {
1467		return this.lastPacketReceived;
1468	}
1469
1470	public void sendActive() {
1471		this.sendPacket(new ActivePacket());
1472	}
1473
1474	public void sendInactive() {
1475		this.sendPacket(new InactivePacket());
1476	}
1477
1478	public void resetAttemptCount() {
1479		this.attempt = 0;
1480		this.lastConnect = 0;
1481	}
1482
1483	public void setInteractive(boolean interactive) {
1484		this.mInteractive = interactive;
1485	}
1486
1487	public Identity getServerIdentity() {
1488		return mServerIdentity;
1489	}
1490
1491	private class UnauthorizedException extends IOException {
1492
1493	}
1494
1495	private class SecurityException extends IOException {
1496
1497	}
1498
1499	private class IncompatibleServerException extends IOException {
1500
1501	}
1502
1503	public enum Identity {
1504		FACEBOOK,
1505		SLACK,
1506		EJABBERD,
1507		PROSODY,
1508		NIMBUZZ,
1509		UNKNOWN
1510	}
1511
1512	public class Features {
1513		XmppConnection connection;
1514		private boolean carbonsEnabled = false;
1515		private boolean encryptionEnabled = false;
1516		private boolean blockListRequested = false;
1517
1518		public Features(final XmppConnection connection) {
1519			this.connection = connection;
1520		}
1521
1522		private boolean hasDiscoFeature(final Jid server, final String feature) {
1523			synchronized (XmppConnection.this.disco) {
1524				return connection.disco.containsKey(server) &&
1525						connection.disco.get(server).getFeatures().contains(feature);
1526			}
1527		}
1528
1529		public boolean carbons() {
1530			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1531		}
1532
1533		public boolean blocking() {
1534			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1535		}
1536
1537		public boolean register() {
1538			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1539		}
1540
1541		public boolean sm() {
1542			return streamId != null
1543					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1544		}
1545
1546		public boolean csi() {
1547			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1548		}
1549
1550		public boolean pep() {
1551			synchronized (XmppConnection.this.disco) {
1552				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1553				return info != null && info.hasIdentity("pubsub", "pep");
1554			}
1555		}
1556
1557		public boolean pepPersistent() {
1558			synchronized (XmppConnection.this.disco) {
1559				ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1560				return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1561			}
1562		}
1563
1564		public boolean mam() {
1565			return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")
1566				|| hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1567		}
1568
1569		public boolean push() {
1570			return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1571					|| hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1572		}
1573
1574		public boolean rosterVersioning() {
1575			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1576		}
1577
1578		public void setBlockListRequested(boolean value) {
1579			this.blockListRequested = value;
1580		}
1581
1582		public boolean httpUpload(long filesize) {
1583			if (Config.DISABLE_HTTP_UPLOAD) {
1584				return false;
1585			} else {
1586				List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1587				if (items.size() > 0) {
1588					try {
1589						long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1590						if(filesize <= maxsize) {
1591							return true;
1592						} else {
1593							Log.d(Config.LOGTAG,account.getJid().toBareJid()+": http upload is not available for files with size "+filesize+" (max is "+maxsize+")");
1594							return false;
1595						}
1596					} catch (Exception e) {
1597						return true;
1598					}
1599				} else {
1600					return false;
1601				}
1602			}
1603		}
1604
1605		public long getMaxHttpUploadSize() {
1606			List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1607				if (items.size() > 0) {
1608					try {
1609						return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1610					} catch (Exception e) {
1611						return -1;
1612					}
1613				} else {
1614					return -1;
1615				}
1616		}
1617	}
1618
1619	private IqGenerator getIqGenerator() {
1620		return mXmppConnectionService.getIqGenerator();
1621	}
1622}