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