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.apache.http.conn.ssl.StrictHostnameVerifier;
  17import org.json.JSONException;
  18import org.json.JSONObject;
  19import org.xmlpull.v1.XmlPullParserException;
  20
  21import java.io.ByteArrayInputStream;
  22import java.io.IOException;
  23import java.io.InputStream;
  24import java.io.OutputStream;
  25import java.math.BigInteger;
  26import java.net.ConnectException;
  27import java.net.IDN;
  28import java.net.InetAddress;
  29import java.net.InetSocketAddress;
  30import java.net.Socket;
  31import java.net.UnknownHostException;
  32import java.net.MalformedURLException;
  33import java.net.URL;
  34import java.security.KeyManagementException;
  35import java.security.NoSuchAlgorithmException;
  36import java.security.Principal;
  37import java.security.PrivateKey;
  38import java.security.cert.X509Certificate;
  39import java.util.ArrayList;
  40import java.util.Arrays;
  41import java.util.Collection;
  42import java.util.HashMap;
  43import java.util.Hashtable;
  44import java.util.Iterator;
  45import java.util.LinkedList;
  46import java.util.List;
  47import java.util.Map.Entry;
  48
  49import javax.net.ssl.HostnameVerifier;
  50import javax.net.ssl.KeyManager;
  51import javax.net.ssl.SSLContext;
  52import javax.net.ssl.SSLSocket;
  53import javax.net.ssl.SSLSocketFactory;
  54import javax.net.ssl.X509KeyManager;
  55import javax.net.ssl.X509TrustManager;
  56
  57import de.duenndns.ssl.MemorizingTrustManager;
  58import eu.siacs.conversations.Config;
  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.generator.IqGenerator;
  67import eu.siacs.conversations.services.XmppConnectionService;
  68import eu.siacs.conversations.utils.CryptoHelper;
  69import eu.siacs.conversations.utils.DNSHelper;
  70import eu.siacs.conversations.utils.Xmlns;
  71import eu.siacs.conversations.xml.Element;
  72import eu.siacs.conversations.xml.Tag;
  73import eu.siacs.conversations.xml.TagWriter;
  74import eu.siacs.conversations.xml.XmlReader;
  75import eu.siacs.conversations.xmpp.forms.Data;
  76import eu.siacs.conversations.xmpp.forms.Field;
  77import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  78import eu.siacs.conversations.xmpp.jid.Jid;
  79import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  80import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  81import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  82import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  83import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  84import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  85import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  86import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  87import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  88import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  89import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  90import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
  91import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
  92
  93public class XmppConnection implements Runnable {
  94
  95	private static final int PACKET_IQ = 0;
  96	private static final int PACKET_MESSAGE = 1;
  97	private static final int PACKET_PRESENCE = 2;
  98	protected Account account;
  99	private final WakeLock wakeLock;
 100	private Socket socket;
 101	private XmlReader tagReader;
 102	private TagWriter tagWriter;
 103	private final Features features = new Features(this);
 104	private boolean needsBinding = true;
 105	private boolean shouldAuthenticate = true;
 106	private Element streamFeatures;
 107	private final HashMap<Jid, Info> disco = new HashMap<>();
 108
 109	private String streamId = null;
 110	private int smVersion = 3;
 111	private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 112
 113	private int stanzasReceived = 0;
 114	private int stanzasSent = 0;
 115	private long lastPacketReceived = 0;
 116	private long lastPingSent = 0;
 117	private long lastConnect = 0;
 118	private long lastSessionStarted = 0;
 119	private boolean mInteractive = false;
 120	private int attempt = 0;
 121	private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 122	private OnPresencePacketReceived presenceListener = null;
 123	private OnJinglePacketReceived jingleListener = null;
 124	private OnIqPacketReceived unregisteredIqListener = null;
 125	private OnMessagePacketReceived messageListener = null;
 126	private OnStatusChanged statusListener = null;
 127	private OnBindListener bindListener = null;
 128	private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
 129	private OnMessageAcknowledged acknowledgedListener = null;
 130	private XmppConnectionService mXmppConnectionService = null;
 131
 132	private SaslMechanism saslMechanism;
 133
 134	private X509KeyManager mKeyManager = new X509KeyManager() {
 135		@Override
 136		public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
 137			return account.getPrivateKeyAlias();
 138		}
 139
 140		@Override
 141		public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
 142			return null;
 143		}
 144
 145		@Override
 146		public X509Certificate[] getCertificateChain(String alias) {
 147			try {
 148				return KeyChain.getCertificateChain(mXmppConnectionService, alias);
 149			} catch (Exception e) {
 150				return new X509Certificate[0];
 151			}
 152		}
 153
 154		@Override
 155		public String[] getClientAliases(String s, Principal[] principals) {
 156			return new String[0];
 157		}
 158
 159		@Override
 160		public String[] getServerAliases(String s, Principal[] principals) {
 161			return new String[0];
 162		}
 163
 164		@Override
 165		public PrivateKey getPrivateKey(String alias) {
 166			try {
 167				return KeyChain.getPrivateKey(mXmppConnectionService, alias);
 168			} catch (Exception e) {
 169				return null;
 170			}
 171		}
 172	};
 173
 174	private OnIqPacketReceived createPacketReceiveHandler() {
 175		return new OnIqPacketReceived() {
 176			@Override
 177			public void onIqPacketReceived(Account account, IqPacket packet) {
 178				if (packet.getType() == IqPacket.TYPE.RESULT) {
 179					account.setOption(Account.OPTION_REGISTER,
 180							false);
 181					changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
 182				} else if (packet.hasChild("error")
 183						&& (packet.findChild("error")
 184						.hasChild("conflict"))) {
 185					changeStatus(Account.State.REGISTRATION_CONFLICT);
 186				} else {
 187					changeStatus(Account.State.REGISTRATION_FAILED);
 188					Log.d(Config.LOGTAG, packet.toString());
 189				}
 190				disconnect(true);
 191			}
 192		};
 193	}
 194
 195	public XmppConnection(final Account account, final XmppConnectionService service) {
 196		this.account = account;
 197		this.wakeLock = service.getPowerManager().newWakeLock(
 198				PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
 199		tagWriter = new TagWriter();
 200		mXmppConnectionService = service;
 201	}
 202
 203	protected void changeStatus(final Account.State nextStatus) {
 204		if (account.getStatus() != nextStatus) {
 205			if ((nextStatus == Account.State.OFFLINE)
 206					&& (account.getStatus() != Account.State.CONNECTING)
 207					&& (account.getStatus() != Account.State.ONLINE)
 208					&& (account.getStatus() != Account.State.DISABLED)) {
 209				return;
 210					}
 211			if (nextStatus == Account.State.ONLINE) {
 212				this.attempt = 0;
 213			}
 214			account.setStatus(nextStatus);
 215			if (statusListener != null) {
 216				statusListener.onStatusChanged(account);
 217			}
 218		}
 219	}
 220
 221	protected void connect() {
 222		Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
 223		features.encryptionEnabled = false;
 224		lastConnect = SystemClock.elapsedRealtime();
 225		lastPingSent = SystemClock.elapsedRealtime();
 226		this.attempt++;
 227		try {
 228			shouldAuthenticate = needsBinding = !account.isOptionSet(Account.OPTION_REGISTER);
 229			tagReader = new XmlReader(wakeLock);
 230			tagWriter = new TagWriter();
 231			this.changeStatus(Account.State.CONNECTING);
 232			if (DNSHelper.isIp(account.getServer().toString())) {
 233				socket = new Socket();
 234				try {
 235					socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
 236				} catch (IOException e) {
 237					throw new UnknownHostException();
 238				}
 239			} else {
 240				final Bundle result = DNSHelper.getSRVRecord(account.getServer(),mXmppConnectionService);
 241				final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
 242				int i = 0;
 243				boolean socketError = true;
 244				while (socketError && values.size() > i) {
 245					final Bundle namePort = (Bundle) values.get(i);
 246					try {
 247						String srvRecordServer;
 248						try {
 249							srvRecordServer = IDN.toASCII(namePort.getString("name"));
 250						} catch (final IllegalArgumentException e) {
 251							// TODO: Handle me?`
 252							srvRecordServer = "";
 253						}
 254						final int srvRecordPort = namePort.getInt("port");
 255						final String srvIpServer = namePort.getString("ip");
 256						final InetSocketAddress addr;
 257						if (srvIpServer != null) {
 258							addr = new InetSocketAddress(srvIpServer, srvRecordPort);
 259							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 260									+ ": using values from dns " + srvRecordServer
 261									+ "[" + srvIpServer + "]:" + srvRecordPort);
 262						} else {
 263							addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
 264							Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 265									+ ": using values from dns "
 266									+ srvRecordServer + ":" + srvRecordPort);
 267						}
 268						socket = new Socket();
 269						socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 270						socketError = false;
 271					} catch (final Throwable e) {
 272						Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 273						i++;
 274					}
 275				}
 276				if (socketError) {
 277					throw new UnknownHostException();
 278				}
 279			}
 280			final OutputStream out = socket.getOutputStream();
 281			tagWriter.setOutputStream(out);
 282			final InputStream in = socket.getInputStream();
 283			tagReader.setInputStream(in);
 284			tagWriter.beginDocument();
 285			sendStartStream();
 286			Tag nextTag;
 287			while ((nextTag = tagReader.readTag()) != null) {
 288				if (nextTag.isStart("stream")) {
 289					processStream(nextTag);
 290					break;
 291				} else {
 292					throw new IOException("unknown tag on connect");
 293				}
 294			}
 295			if (socket.isConnected()) {
 296				socket.close();
 297			}
 298		} catch (final IncompatibleServerException e) {
 299			this.changeStatus(Account.State.INCOMPATIBLE_SERVER);
 300		} catch (final SecurityException e) {
 301			this.changeStatus(Account.State.SECURITY_ERROR);
 302		} catch (final UnauthorizedException e) {
 303			this.changeStatus(Account.State.UNAUTHORIZED);
 304		} catch (final UnknownHostException | ConnectException e) {
 305			this.changeStatus(Account.State.SERVER_NOT_FOUND);
 306		} catch (final DnsTimeoutException e) {
 307			this.changeStatus(Account.State.DNS_TIMEOUT);
 308		} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
 309			Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
 310			this.changeStatus(Account.State.OFFLINE);
 311			this.attempt--; //don't count attempt when reconnecting instantly anyway
 312		} finally {
 313			if (socket != null) {
 314				try {
 315					socket.close();
 316				} catch (IOException e) {
 317
 318				}
 319			}
 320			if (wakeLock.isHeld()) {
 321				try {
 322					wakeLock.release();
 323				} catch (final RuntimeException ignored) {
 324				}
 325			}
 326		}
 327	}
 328
 329	@Override
 330	public void run() {
 331		try {
 332			if (socket != null) {
 333				socket.close();
 334			}
 335		} catch (final IOException ignored) {
 336
 337		}
 338		connect();
 339	}
 340
 341	private void processStream(final Tag currentTag) throws XmlPullParserException,
 342					IOException, NoSuchAlgorithmException {
 343						Tag nextTag = tagReader.readTag();
 344
 345						while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
 346							if (nextTag.isStart("error")) {
 347								processStreamError(nextTag);
 348							} else if (nextTag.isStart("features")) {
 349								processStreamFeatures(nextTag);
 350							} else if (nextTag.isStart("proceed")) {
 351								switchOverToTls(nextTag);
 352							} else if (nextTag.isStart("success")) {
 353								final String challenge = tagReader.readElement(nextTag).getContent();
 354								try {
 355									saslMechanism.getResponse(challenge);
 356								} catch (final SaslMechanism.AuthenticationException e) {
 357									disconnect(true);
 358									Log.e(Config.LOGTAG, String.valueOf(e));
 359								}
 360								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
 361								account.setKey(Account.PINNED_MECHANISM_KEY,
 362										String.valueOf(saslMechanism.getPriority()));
 363								tagReader.reset();
 364								sendStartStream();
 365								processStream(tagReader.readTag());
 366								break;
 367							} else if (nextTag.isStart("failure")) {
 368								throw new UnauthorizedException();
 369							} else if (nextTag.isStart("challenge")) {
 370								final String challenge = tagReader.readElement(nextTag).getContent();
 371								final Element response = new Element("response");
 372								response.setAttribute("xmlns",
 373										"urn:ietf:params:xml:ns:xmpp-sasl");
 374								try {
 375									response.setContent(saslMechanism.getResponse(challenge));
 376								} catch (final SaslMechanism.AuthenticationException e) {
 377									// TODO: Send auth abort tag.
 378									Log.e(Config.LOGTAG, e.toString());
 379								}
 380								tagWriter.writeElement(response);
 381							} else if (nextTag.isStart("enabled")) {
 382								final Element enabled = tagReader.readElement(nextTag);
 383								if ("true".equals(enabled.getAttribute("resume"))) {
 384									this.streamId = enabled.getAttribute("id");
 385									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 386											+ ": stream managment(" + smVersion
 387											+ ") enabled (resumable)");
 388								} else {
 389									Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 390											+ ": stream management(" + smVersion + ") enabled");
 391								}
 392								this.stanzasReceived = 0;
 393								final RequestPacket r = new RequestPacket(smVersion);
 394								tagWriter.writeStanzaAsync(r);
 395							} else if (nextTag.isStart("resumed")) {
 396								lastPacketReceived = SystemClock.elapsedRealtime();
 397								final Element resumed = tagReader.readElement(nextTag);
 398								final String h = resumed.getAttribute("h");
 399								try {
 400									final int serverCount = Integer.parseInt(h);
 401									if (serverCount != stanzasSent) {
 402										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
 403												+ ": session resumed with lost packages");
 404										stanzasSent = serverCount;
 405									} else {
 406										Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
 407									}
 408									acknowledgeStanzaUpTo(serverCount);
 409									ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 410									for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
 411										failedStanzas.add(mStanzaQueue.valueAt(i));
 412									}
 413									mStanzaQueue.clear();
 414									Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
 415									for(AbstractAcknowledgeableStanza packet : failedStanzas) {
 416										if (packet instanceof MessagePacket) {
 417											MessagePacket message = (MessagePacket) packet;
 418											mXmppConnectionService.markMessage(account,
 419													message.getTo().toBareJid(),
 420													message.getId(),
 421													Message.STATUS_UNSEND);
 422										}
 423										sendPacket(packet);
 424									}
 425								} catch (final NumberFormatException ignored) {
 426								}
 427								Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
 428								changeStatus(Account.State.ONLINE);
 429							} else if (nextTag.isStart("r")) {
 430								tagReader.readElement(nextTag);
 431								if (Config.EXTENDED_SM_LOGGING) {
 432									Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 433								}
 434								final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 435								tagWriter.writeStanzaAsync(ack);
 436							} else if (nextTag.isStart("a")) {
 437								final Element ack = tagReader.readElement(nextTag);
 438								lastPacketReceived = SystemClock.elapsedRealtime();
 439								try {
 440									final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 441									acknowledgeStanzaUpTo(serverSequence);
 442								} catch (NumberFormatException e) {
 443									Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
 444								}
 445							} else if (nextTag.isStart("failed")) {
 446								tagReader.readElement(nextTag);
 447								Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
 448								streamId = null;
 449								if (account.getStatus() != Account.State.ONLINE) {
 450									sendBindRequest();
 451								}
 452							} else if (nextTag.isStart("iq")) {
 453								processIq(nextTag);
 454							} else if (nextTag.isStart("message")) {
 455								processMessage(nextTag);
 456							} else if (nextTag.isStart("presence")) {
 457								processPresence(nextTag);
 458							}
 459							nextTag = tagReader.readTag();
 460						}
 461						if (account.getStatus() == Account.State.ONLINE) {
 462							account. setStatus(Account.State.OFFLINE);
 463							if (statusListener != null) {
 464								statusListener.onStatusChanged(account);
 465							}
 466						}
 467	}
 468
 469	private void acknowledgeStanzaUpTo(int serverCount) {
 470		for (int i = 0; i < mStanzaQueue.size(); ++i) {
 471			if (serverCount >= mStanzaQueue.keyAt(i)) {
 472				if (Config.EXTENDED_SM_LOGGING) {
 473					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 474				}
 475				AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 476				if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 477					MessagePacket packet = (MessagePacket) stanza;
 478					acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 479				}
 480				mStanzaQueue.removeAt(i);
 481				i--;
 482			}
 483		}
 484	}
 485
 486	private Element processPacket(final Tag currentTag, final int packetType)
 487		throws XmlPullParserException, IOException {
 488		Element element;
 489		switch (packetType) {
 490			case PACKET_IQ:
 491				element = new IqPacket();
 492				break;
 493			case PACKET_MESSAGE:
 494				element = new MessagePacket();
 495				break;
 496			case PACKET_PRESENCE:
 497				element = new PresencePacket();
 498				break;
 499			default:
 500				return null;
 501		}
 502		element.setAttributes(currentTag.getAttributes());
 503		Tag nextTag = tagReader.readTag();
 504		if (nextTag == null) {
 505			throw new IOException("interrupted mid tag");
 506		}
 507		while (!nextTag.isEnd(element.getName())) {
 508			if (!nextTag.isNo()) {
 509				final Element child = tagReader.readElement(nextTag);
 510				final String type = currentTag.getAttribute("type");
 511				if (packetType == PACKET_IQ
 512						&& "jingle".equals(child.getName())
 513						&& ("set".equalsIgnoreCase(type) || "get"
 514							.equalsIgnoreCase(type))) {
 515					element = new JinglePacket();
 516					element.setAttributes(currentTag.getAttributes());
 517							}
 518				element.addChild(child);
 519			}
 520			nextTag = tagReader.readTag();
 521			if (nextTag == null) {
 522				throw new IOException("interrupted mid tag");
 523			}
 524		}
 525		if (stanzasReceived == Integer.MAX_VALUE) {
 526			resetStreamId();
 527			throw new IOException("time to restart the session. cant handle >2 billion pcks");
 528		}
 529		++stanzasReceived;
 530		lastPacketReceived = SystemClock.elapsedRealtime();
 531		return element;
 532	}
 533
 534	private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
 535		final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 536
 537		if (packet.getId() == null) {
 538			return; // an iq packet without id is definitely invalid
 539		}
 540
 541		if (packet instanceof JinglePacket) {
 542			if (this.jingleListener != null) {
 543				this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
 544			}
 545		} else {
 546			OnIqPacketReceived callback = null;
 547			synchronized (this.packetCallbacks) {
 548				if (packetCallbacks.containsKey(packet.getId())) {
 549					final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 550					// Packets to the server should have responses from the server
 551					if (packetCallbackDuple.first.toServer(account)) {
 552						if (packet.fromServer(account) || account.getJid().getDomainpart().equals("chat.facebook.com")) {
 553							callback = packetCallbackDuple.second;
 554							packetCallbacks.remove(packet.getId());
 555						} else {
 556							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 557						}
 558					} else {
 559						if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 560							callback = packetCallbackDuple.second;
 561							packetCallbacks.remove(packet.getId());
 562						} else {
 563							Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
 564						}
 565					}
 566				} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 567					callback = this.unregisteredIqListener;
 568				}
 569			}
 570			if (callback != null) {
 571				callback.onIqPacketReceived(account,packet);
 572			}
 573		}
 574	}
 575
 576	private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 577		final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
 578		this.messageListener.onMessagePacketReceived(account, packet);
 579	}
 580
 581	private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 582		PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 583		this.presenceListener.onPresencePacketReceived(account, packet);
 584	}
 585
 586	private void sendStartTLS() throws IOException {
 587		final Tag startTLS = Tag.empty("starttls");
 588		startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
 589		tagWriter.writeTag(startTLS);
 590	}
 591
 592	private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
 593		tagReader.readTag();
 594		try {
 595			final SSLContext sc = SSLContext.getInstance("TLS");
 596			MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 597			KeyManager[] keyManager;
 598			if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
 599				keyManager = new KeyManager[]{ mKeyManager };
 600			} else {
 601				keyManager = null;
 602			}
 603			sc.init(keyManager,new X509TrustManager[]{mInteractive ? trustManager : trustManager.getNonInteractive()},mXmppConnectionService.getRNG());
 604			final SSLSocketFactory factory = sc.getSocketFactory();
 605			final HostnameVerifier verifier;
 606			if (mInteractive) {
 607				verifier = trustManager.wrapHostnameVerifier(new StrictHostnameVerifier());
 608			} else {
 609				verifier = trustManager.wrapHostnameVerifierNonInteractive(new StrictHostnameVerifier());
 610			}
 611			final InetAddress address = socket == null ? null : socket.getInetAddress();
 612
 613			if (factory == null || address == null || verifier == null) {
 614				throw new IOException("could not setup ssl");
 615			}
 616
 617			final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
 618
 619			if (sslSocket == null) {
 620				throw new IOException("could not initialize ssl socket");
 621			}
 622
 623			final String[] supportProtocols;
 624			final Collection<String> supportedProtocols = new LinkedList<>(
 625					Arrays.asList(sslSocket.getSupportedProtocols()));
 626			supportedProtocols.remove("SSLv3");
 627			supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
 628
 629			sslSocket.setEnabledProtocols(supportProtocols);
 630
 631			final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
 632					sslSocket.getSupportedCipherSuites());
 633			//Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
 634			if (cipherSuites.length > 0) {
 635				sslSocket.setEnabledCipherSuites(cipherSuites);
 636			}
 637
 638			if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
 639				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
 640				throw new SecurityException();
 641			}
 642			tagReader.setInputStream(sslSocket.getInputStream());
 643			tagWriter.setOutputStream(sslSocket.getOutputStream());
 644			sendStartStream();
 645			Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
 646			features.encryptionEnabled = true;
 647			processStream(tagReader.readTag());
 648			sslSocket.close();
 649		} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
 650			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
 651			throw new SecurityException();
 652		}
 653	}
 654
 655	private void processStreamFeatures(final Tag currentTag)
 656		throws XmlPullParserException, IOException {
 657		this.streamFeatures = tagReader.readElement(currentTag);
 658		if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 659			sendStartTLS();
 660		} else if (this.streamFeatures.hasChild("register")
 661				&& account.isOptionSet(Account.OPTION_REGISTER)
 662				&& features.encryptionEnabled) {
 663			sendRegistryRequest();
 664		} else if (!this.streamFeatures.hasChild("register")
 665				&& account.isOptionSet(Account.OPTION_REGISTER)) {
 666			changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
 667			disconnect(true);
 668		} else if (this.streamFeatures.hasChild("mechanisms")
 669				&& shouldAuthenticate && features.encryptionEnabled) {
 670			final List<String> mechanisms = extractMechanisms(streamFeatures
 671					.findChild("mechanisms"));
 672			final Element auth = new Element("auth");
 673			auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
 674			if (mechanisms.contains("EXTERNAL")) {
 675				saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 676			} else if (mechanisms.contains("SCRAM-SHA-1")) {
 677				saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 678			} else if (mechanisms.contains("PLAIN")) {
 679				saslMechanism = new Plain(tagWriter, account);
 680			} else if (mechanisms.contains("DIGEST-MD5")) {
 681				saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 682			}
 683			if (saslMechanism != null) {
 684				final JSONObject keys = account.getKeys();
 685				try {
 686					if (keys.has(Account.PINNED_MECHANISM_KEY) &&
 687							keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
 688						Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 689								" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 690								") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
 691								"). Possible downgrade attack?");
 692						throw new SecurityException();
 693					}
 694				} catch (final JSONException e) {
 695					Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
 696				}
 697				Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 698				auth.setAttribute("mechanism", saslMechanism.getMechanism());
 699				if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 700					auth.setContent(saslMechanism.getClientFirstMessage());
 701				}
 702				tagWriter.writeElement(auth);
 703			} else {
 704				throw new IncompatibleServerException();
 705			}
 706		} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 707			if (Config.EXTENDED_SM_LOGGING) {
 708				Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
 709			}
 710			final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 711			this.tagWriter.writeStanzaAsync(resume);
 712		} else if (needsBinding) {
 713			if (this.streamFeatures.hasChild("bind")) {
 714				sendBindRequest();
 715			} else {
 716				throw new IncompatibleServerException();
 717			}
 718		}
 719	}
 720
 721	private List<String> extractMechanisms(final Element stream) {
 722		final ArrayList<String> mechanisms = new ArrayList<>(stream
 723				.getChildren().size());
 724		for (final Element child : stream.getChildren()) {
 725			mechanisms.add(child.getContent());
 726		}
 727		return mechanisms;
 728	}
 729
 730	public void sendCaptchaRegistryRequest(String id, Data data) {
 731		if (data == null) {
 732			setAccountCreationFailed("");
 733		} else {
 734			IqPacket request = getIqGenerator().generateCreateAccountWithCaptcha(account, id, data);
 735			sendIqPacket(request, createPacketReceiveHandler());
 736		}
 737	}
 738
 739	private void sendRegistryRequest() {
 740		final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 741		register.query("jabber:iq:register");
 742		register.setTo(account.getServer());
 743		sendIqPacket(register, new OnIqPacketReceived() {
 744
 745			@Override
 746			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 747				boolean failed = false;
 748				if (packet.getType() == IqPacket.TYPE.RESULT
 749						&& packet.query().hasChild("username")
 750						&& (packet.query().hasChild("password"))) {
 751					final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
 752					final Element username = new Element("username").setContent(account.getUsername());
 753					final Element password = new Element("password").setContent(account.getPassword());
 754					register.query("jabber:iq:register").addChild(username);
 755					register.query().addChild(password);
 756					sendIqPacket(register, createPacketReceiveHandler());
 757				} else if (packet.getType() == IqPacket.TYPE.RESULT
 758						&& (packet.query().hasChild("x", "jabber:x:data"))) {
 759					final Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
 760					final Element blob = packet.query().findChild("data", "urn:xmpp:bob");
 761					final String id = packet.getId();
 762
 763					Bitmap captcha = null;
 764					if (blob != null) {
 765						try {
 766							final String base64Blob = blob.getContent();
 767							final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 768							InputStream stream = new ByteArrayInputStream(strBlob);
 769							captcha = BitmapFactory.decodeStream(stream);
 770						} catch (Exception e) {
 771							//ignored
 772						}
 773					} else {
 774						try {
 775							Field url = data.getFieldByName("url");
 776							String urlString = url.findChildContent("value");
 777							URL uri = new URL(urlString);
 778							captcha = BitmapFactory.decodeStream(uri.openConnection().getInputStream());
 779						} catch(IOException e) {
 780							Log.e(Config.LOGTAG, e.toString());
 781						}
 782					}
 783
 784					if (captcha != null) {
 785						failed = !mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha);
 786					}
 787				} else {
 788					failed = true;
 789				}
 790
 791				if (failed) {
 792					final Element instructions = packet.query().findChild("instructions");
 793					setAccountCreationFailed((instructions != null) ? instructions.getContent() : "");
 794				}
 795			}
 796		});
 797	}
 798
 799	private void setAccountCreationFailed(String instructions) {
 800		changeStatus(Account.State.REGISTRATION_FAILED);
 801		disconnect(true);
 802		Log.d(Config.LOGTAG, account.getJid().toBareJid()
 803				+ ": could not register. instructions are"
 804				+ instructions);
 805	}
 806
 807	private void sendBindRequest() {
 808		while(!mXmppConnectionService.areMessagesInitialized()) {
 809			try {
 810				Thread.sleep(500);
 811			} catch (final InterruptedException ignored) {
 812			}
 813		}
 814		needsBinding = false;
 815		clearIqCallbacks();
 816		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 817		iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
 818				.addChild("resource").setContent(account.getResource());
 819		this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
 820			@Override
 821			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 822				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 823					return;
 824				}
 825				final Element bind = packet.findChild("bind");
 826				if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
 827					final Element jid = bind.findChild("jid");
 828					if (jid != null && jid.getContent() != null) {
 829						try {
 830							account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
 831						} catch (final InvalidJidException e) {
 832							// TODO: Handle the case where an external JID is technically invalid?
 833						}
 834						if (streamFeatures.hasChild("session")) {
 835							sendStartSession();
 836						} else {
 837							sendPostBindInitialization();
 838						}
 839					} else {
 840						Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 841						disconnect(true);
 842					}
 843				} else {
 844					Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
 845					disconnect(true);
 846				}
 847			}
 848		});
 849	}
 850
 851	private void clearIqCallbacks() {
 852		final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
 853		final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
 854		synchronized (this.packetCallbacks) {
 855			if (this.packetCallbacks.size() == 0) {
 856				return;
 857			}
 858			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
 859			final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
 860			while (iterator.hasNext()) {
 861				Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
 862				callbacks.add(entry.second);
 863				iterator.remove();
 864			}
 865		}
 866		for(OnIqPacketReceived callback : callbacks) {
 867			callback.onIqPacketReceived(account,failurePacket);
 868		}
 869		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
 870	}
 871
 872	private void sendStartSession() {
 873		final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
 874		startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
 875		this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
 876			@Override
 877			public void onIqPacketReceived(Account account, IqPacket packet) {
 878				if (packet.getType() == IqPacket.TYPE.RESULT) {
 879					sendPostBindInitialization();
 880				} else if (packet.getType() != IqPacket.TYPE.TIMEOUT){
 881					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
 882					disconnect(true);
 883				}
 884			}
 885		});
 886	}
 887
 888	private void sendPostBindInitialization() {
 889		smVersion = 0;
 890		if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
 891			smVersion = 3;
 892		} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
 893			smVersion = 2;
 894		}
 895		if (smVersion != 0) {
 896			final EnablePacket enable = new EnablePacket(smVersion);
 897			tagWriter.writeStanzaAsync(enable);
 898			stanzasSent = 0;
 899			mStanzaQueue.clear();
 900		}
 901		features.carbonsEnabled = false;
 902		features.blockListRequested = false;
 903		disco.clear();
 904		sendServiceDiscoveryInfo(account.getServer());
 905		sendServiceDiscoveryInfo(account.getJid().toBareJid());
 906		sendServiceDiscoveryItems(account.getServer());
 907		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
 908		this.lastSessionStarted = SystemClock.elapsedRealtime();
 909		changeStatus(Account.State.ONLINE);
 910		if (bindListener != null) {
 911			bindListener.onBind(account);
 912		}
 913	}
 914
 915	private void sendServiceDiscoveryInfo(final Jid jid) {
 916		if (disco.containsKey(jid)) {
 917			if (account.getServer().equals(jid)) {
 918				enableAdvancedStreamFeatures();
 919			}
 920		} else {
 921			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 922			iq.setTo(jid);
 923			iq.query("http://jabber.org/protocol/disco#info");
 924			this.sendIqPacket(iq, new OnIqPacketReceived() {
 925
 926				@Override
 927				public void onIqPacketReceived(final Account account, final IqPacket packet) {
 928					if (packet.getType() == IqPacket.TYPE.RESULT) {
 929						final List<Element> elements = packet.query().getChildren();
 930						final Info info = new Info();
 931						for (final Element element : elements) {
 932							if (element.getName().equals("identity")) {
 933								String type = element.getAttribute("type");
 934								String category = element.getAttribute("category");
 935								if (type != null && category != null) {
 936									info.identities.add(new Pair<>(category, type));
 937								}
 938							} else if (element.getName().equals("feature")) {
 939								info.features.add(element.getAttribute("var"));
 940							}
 941						}
 942						disco.put(jid, info);
 943						if (account.getServer().equals(jid)) {
 944							enableAdvancedStreamFeatures();
 945							for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
 946								listener.onAdvancedStreamFeaturesAvailable(account);
 947							}
 948						}
 949					} else {
 950						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco info for "+jid.toString());
 951					}
 952				}
 953			});
 954		}
 955	}
 956
 957	private void enableAdvancedStreamFeatures() {
 958		if (getFeatures().carbons() && !features.carbonsEnabled) {
 959			sendEnableCarbons();
 960		}
 961		if (getFeatures().blocking() && !features.blockListRequested) {
 962			Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
 963			this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
 964		}
 965	}
 966
 967	private void sendServiceDiscoveryItems(final Jid server) {
 968		final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
 969		iq.setTo(server.toDomainJid());
 970		iq.query("http://jabber.org/protocol/disco#items");
 971		this.sendIqPacket(iq, new OnIqPacketReceived() {
 972
 973			@Override
 974			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 975				if (packet.getType() == IqPacket.TYPE.RESULT) {
 976					final List<Element> elements = packet.query().getChildren();
 977					for (final Element element : elements) {
 978						if (element.getName().equals("item")) {
 979							final Jid jid = element.getAttributeAsJid("jid");
 980							if (jid != null && !jid.equals(account.getServer())) {
 981								sendServiceDiscoveryInfo(jid);
 982							}
 983						}
 984					}
 985				} else {
 986					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco items of "+server);
 987				}
 988			}
 989		});
 990	}
 991
 992	private void sendEnableCarbons() {
 993		final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
 994		iq.addChild("enable", "urn:xmpp:carbons:2");
 995		this.sendIqPacket(iq, new OnIqPacketReceived() {
 996
 997			@Override
 998			public void onIqPacketReceived(final Account account, final IqPacket packet) {
 999				if (!packet.hasChild("error")) {
1000					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1001							+ ": successfully enabled carbons");
1002					features.carbonsEnabled = true;
1003				} else {
1004					Log.d(Config.LOGTAG, account.getJid().toBareJid()
1005							+ ": error enableing carbons " + packet.toString());
1006				}
1007			}
1008		});
1009	}
1010
1011	private void processStreamError(final Tag currentTag)
1012		throws XmlPullParserException, IOException {
1013		final Element streamError = tagReader.readElement(currentTag);
1014		if (streamError != null && streamError.hasChild("conflict")) {
1015			final String resource = account.getResource().split("\\.")[0];
1016			account.setResource(resource + "." + nextRandomId());
1017			Log.d(Config.LOGTAG,
1018					account.getJid().toBareJid() + ": switching resource due to conflict ("
1019					+ account.getResource() + ")");
1020		} else if (streamError != null) {
1021			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1022		}
1023	}
1024
1025	private void sendStartStream() throws IOException {
1026		final Tag stream = Tag.start("stream:stream");
1027		stream.setAttribute("to", account.getServer().toString());
1028		stream.setAttribute("version", "1.0");
1029		stream.setAttribute("xml:lang", "en");
1030		stream.setAttribute("xmlns", "jabber:client");
1031		stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1032		tagWriter.writeTag(stream);
1033	}
1034
1035	private String nextRandomId() {
1036		return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1037	}
1038
1039	public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1040		packet.setFrom(account.getJid());
1041		this.sendUnmodifiedIqPacket(packet, callback);
1042
1043	}
1044
1045	private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1046		if (packet.getId() == null) {
1047			final String id = nextRandomId();
1048			packet.setAttribute("id", id);
1049		}
1050		if (callback != null) {
1051			synchronized (this.packetCallbacks) {
1052				packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1053			}
1054		}
1055		this.sendPacket(packet);
1056	}
1057
1058	public void sendMessagePacket(final MessagePacket packet) {
1059		this.sendPacket(packet);
1060	}
1061
1062	public void sendPresencePacket(final PresencePacket packet) {
1063		this.sendPacket(packet);
1064	}
1065
1066	private synchronized void sendPacket(final AbstractStanza packet) {
1067		if (stanzasSent == Integer.MAX_VALUE) {
1068			resetStreamId();
1069			disconnect(true);
1070			return;
1071		}
1072		tagWriter.writeStanzaAsync(packet);
1073		if (packet instanceof AbstractAcknowledgeableStanza) {
1074			AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1075			++stanzasSent;
1076			this.mStanzaQueue.put(stanzasSent, stanza);
1077			if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1078				if (Config.EXTENDED_SM_LOGGING) {
1079					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1080				}
1081				tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1082			}
1083		}
1084	}
1085
1086	public void sendPing() {
1087		if (!r()) {
1088			final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1089			iq.setFrom(account.getJid());
1090			iq.addChild("ping", "urn:xmpp:ping");
1091			this.sendIqPacket(iq, null);
1092		}
1093		this.lastPingSent = SystemClock.elapsedRealtime();
1094	}
1095
1096	public void setOnMessagePacketReceivedListener(
1097			final OnMessagePacketReceived listener) {
1098		this.messageListener = listener;
1099			}
1100
1101	public void setOnUnregisteredIqPacketReceivedListener(
1102			final OnIqPacketReceived listener) {
1103		this.unregisteredIqListener = listener;
1104			}
1105
1106	public void setOnPresencePacketReceivedListener(
1107			final OnPresencePacketReceived listener) {
1108		this.presenceListener = listener;
1109			}
1110
1111	public void setOnJinglePacketReceivedListener(
1112			final OnJinglePacketReceived listener) {
1113		this.jingleListener = listener;
1114			}
1115
1116	public void setOnStatusChangedListener(final OnStatusChanged listener) {
1117		this.statusListener = listener;
1118	}
1119
1120	public void setOnBindListener(final OnBindListener listener) {
1121		this.bindListener = listener;
1122	}
1123
1124	public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1125		this.acknowledgedListener = listener;
1126	}
1127
1128	public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1129		if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1130			this.advancedStreamFeaturesLoadedListeners.add(listener);
1131		}
1132	}
1133
1134	public void disconnect(final boolean force) {
1135		Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
1136		try {
1137			if (force) {
1138				socket.close();
1139				return;
1140			}
1141			new Thread(new Runnable() {
1142
1143				@Override
1144				public void run() {
1145					if (tagWriter.isActive()) {
1146						tagWriter.finish();
1147						try {
1148							int i = 0;
1149							boolean warned = false;
1150							while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1151								if (!warned) {
1152									Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1153									warned = true;
1154								}
1155								Thread.sleep(200);
1156								i++;
1157							}
1158							if (warned) {
1159								Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1160							}
1161							tagWriter.writeTag(Tag.end("stream:stream"));
1162							socket.close();
1163						} catch (final IOException e) {
1164							Log.d(Config.LOGTAG,"io exception during disconnect");
1165						} catch (final InterruptedException e) {
1166							Log.d(Config.LOGTAG, "interrupted");
1167						}
1168					}
1169				}
1170			}).start();
1171		} catch (final IOException e) {
1172			Log.d(Config.LOGTAG, "io exception during disconnect");
1173		}
1174	}
1175
1176	public void resetStreamId() {
1177		this.streamId = null;
1178	}
1179
1180	public List<Jid> findDiscoItemsByFeature(final String feature) {
1181		final List<Jid> items = new ArrayList<>();
1182		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1183			if (cursor.getValue().features.contains(feature)) {
1184				items.add(cursor.getKey());
1185			}
1186		}
1187		return items;
1188	}
1189
1190	public Jid findDiscoItemByFeature(final String feature) {
1191		final List<Jid> items = findDiscoItemsByFeature(feature);
1192		if (items.size() >= 1) {
1193			return items.get(0);
1194		}
1195		return null;
1196	}
1197
1198	public boolean r() {
1199		if (getFeatures().sm()) {
1200			this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1201			return true;
1202		} else {
1203			return false;
1204		}
1205	}
1206
1207	public String getMucServer() {
1208		for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1209			final Info value = cursor.getValue();
1210			if (value.features.contains("http://jabber.org/protocol/muc")
1211					&& !value.features.contains("jabber:iq:gateway")
1212					&& !value.identities.contains(new Pair<>("conference","irc"))) {
1213				return cursor.getKey().toString();
1214			}
1215		}
1216		return null;
1217	}
1218
1219	public int getTimeToNextAttempt() {
1220		final int interval = (int) (25 * Math.pow(1.5, attempt));
1221		final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1222		return interval - secondsSinceLast;
1223	}
1224
1225	public int getAttempt() {
1226		return this.attempt;
1227	}
1228
1229	public Features getFeatures() {
1230		return this.features;
1231	}
1232
1233	public long getLastSessionEstablished() {
1234		final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1235		return System.currentTimeMillis() - diff;
1236	}
1237
1238	public long getLastConnect() {
1239		return this.lastConnect;
1240	}
1241
1242	public long getLastPingSent() {
1243		return this.lastPingSent;
1244	}
1245
1246	public long getLastPacketReceived() {
1247		return this.lastPacketReceived;
1248	}
1249
1250	public void sendActive() {
1251		this.sendPacket(new ActivePacket());
1252	}
1253
1254	public void sendInactive() {
1255		this.sendPacket(new InactivePacket());
1256	}
1257
1258	public void resetAttemptCount() {
1259		this.attempt = 0;
1260		this.lastConnect = 0;
1261	}
1262
1263	public void setInteractive(boolean interactive) {
1264		this.mInteractive = interactive;
1265	}
1266
1267	private class Info {
1268		public final ArrayList<String> features = new ArrayList<>();
1269		public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1270	}
1271
1272	private class UnauthorizedException extends IOException {
1273
1274	}
1275
1276	private class SecurityException extends IOException {
1277
1278	}
1279
1280	private class IncompatibleServerException extends IOException {
1281
1282	}
1283
1284	private class DnsTimeoutException extends IOException {
1285
1286	}
1287
1288	public class Features {
1289		XmppConnection connection;
1290		private boolean carbonsEnabled = false;
1291		private boolean encryptionEnabled = false;
1292		private boolean blockListRequested = false;
1293
1294		public Features(final XmppConnection connection) {
1295			this.connection = connection;
1296		}
1297
1298		private boolean hasDiscoFeature(final Jid server, final String feature) {
1299			return connection.disco.containsKey(server) &&
1300				connection.disco.get(server).features.contains(feature);
1301		}
1302
1303		public boolean carbons() {
1304			return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1305		}
1306
1307		public boolean blocking() {
1308			return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1309		}
1310
1311		public boolean register() {
1312			return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1313		}
1314
1315		public boolean sm() {
1316			return streamId != null
1317					|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1318		}
1319
1320		public boolean csi() {
1321			return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1322		}
1323
1324		public boolean pep() {
1325			final Pair<String,String> needle = new Pair<>("pubsub","pep");
1326			Info info = disco.get(account.getServer());
1327			if (info != null && info.identities.contains(needle)) {
1328				return true;
1329			} else {
1330				info = disco.get(account.getJid().toBareJid());
1331				return info != null && info.identities.contains(needle);
1332			}
1333		}
1334
1335		public boolean mam() {
1336			if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1337				return true;
1338			} else {
1339				return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1340			}
1341		}
1342
1343		public boolean advancedStreamFeaturesLoaded() {
1344			return disco.containsKey(account.getServer());
1345		}
1346
1347		public boolean rosterVersioning() {
1348			return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1349		}
1350
1351		public void setBlockListRequested(boolean value) {
1352			this.blockListRequested = value;
1353		}
1354
1355		public boolean httpUpload() {
1356			return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1357		}
1358	}
1359
1360	private IqGenerator getIqGenerator() {
1361		return mXmppConnectionService.getIqGenerator();
1362	}
1363}