XmppConnection.java

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