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