XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.graphics.Bitmap;
   5import android.graphics.BitmapFactory;
   6import android.os.SystemClock;
   7import android.security.KeyChain;
   8import android.util.Base64;
   9import android.util.Log;
  10import android.util.Pair;
  11import android.util.SparseArray;
  12
  13import androidx.annotation.NonNull;
  14
  15import org.xmlpull.v1.XmlPullParserException;
  16
  17import java.io.ByteArrayInputStream;
  18import java.io.IOException;
  19import java.io.InputStream;
  20import java.net.ConnectException;
  21import java.net.IDN;
  22import java.net.InetAddress;
  23import java.net.InetSocketAddress;
  24import java.net.Socket;
  25import java.net.UnknownHostException;
  26import java.security.KeyManagementException;
  27import java.security.NoSuchAlgorithmException;
  28import java.security.Principal;
  29import java.security.PrivateKey;
  30import java.security.cert.X509Certificate;
  31import java.util.ArrayList;
  32import java.util.Arrays;
  33import java.util.Collections;
  34import java.util.HashMap;
  35import java.util.HashSet;
  36import java.util.Hashtable;
  37import java.util.Iterator;
  38import java.util.List;
  39import java.util.Map.Entry;
  40import java.util.Set;
  41import java.util.concurrent.CountDownLatch;
  42import java.util.concurrent.TimeUnit;
  43import java.util.concurrent.atomic.AtomicBoolean;
  44import java.util.concurrent.atomic.AtomicInteger;
  45import java.util.regex.Matcher;
  46
  47import javax.net.ssl.KeyManager;
  48import javax.net.ssl.SSLContext;
  49import javax.net.ssl.SSLPeerUnverifiedException;
  50import javax.net.ssl.SSLSocket;
  51import javax.net.ssl.SSLSocketFactory;
  52import javax.net.ssl.X509KeyManager;
  53import javax.net.ssl.X509TrustManager;
  54
  55import eu.siacs.conversations.Config;
  56import eu.siacs.conversations.R;
  57import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  58import eu.siacs.conversations.crypto.XmppDomainVerifier;
  59import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  60import eu.siacs.conversations.crypto.sasl.Anonymous;
  61import eu.siacs.conversations.crypto.sasl.DigestMd5;
  62import eu.siacs.conversations.crypto.sasl.External;
  63import eu.siacs.conversations.crypto.sasl.Plain;
  64import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  65import eu.siacs.conversations.crypto.sasl.ScramSha1;
  66import eu.siacs.conversations.crypto.sasl.ScramSha256;
  67import eu.siacs.conversations.crypto.sasl.ScramSha512;
  68import eu.siacs.conversations.entities.Account;
  69import eu.siacs.conversations.entities.Message;
  70import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  71import eu.siacs.conversations.generator.IqGenerator;
  72import eu.siacs.conversations.http.HttpConnectionManager;
  73import eu.siacs.conversations.persistance.FileBackend;
  74import eu.siacs.conversations.services.MemorizingTrustManager;
  75import eu.siacs.conversations.services.MessageArchiveService;
  76import eu.siacs.conversations.services.NotificationService;
  77import eu.siacs.conversations.services.XmppConnectionService;
  78import eu.siacs.conversations.utils.CryptoHelper;
  79import eu.siacs.conversations.utils.Patterns;
  80import eu.siacs.conversations.utils.Resolver;
  81import eu.siacs.conversations.utils.SSLSocketHelper;
  82import eu.siacs.conversations.utils.SocksSocketFactory;
  83import eu.siacs.conversations.utils.XmlHelper;
  84import eu.siacs.conversations.xml.Element;
  85import eu.siacs.conversations.xml.LocalizedContent;
  86import eu.siacs.conversations.xml.Namespace;
  87import eu.siacs.conversations.xml.Tag;
  88import eu.siacs.conversations.xml.TagWriter;
  89import eu.siacs.conversations.xml.XmlReader;
  90import eu.siacs.conversations.xmpp.forms.Data;
  91import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  92import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  93import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  94import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  95import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  96import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  97import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  98import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  99import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
 100import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
 101import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 102import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 103import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 104import okhttp3.HttpUrl;
 105
 106public class XmppConnection implements Runnable {
 107
 108    private static final int PACKET_IQ = 0;
 109    private static final int PACKET_MESSAGE = 1;
 110    private static final int PACKET_PRESENCE = 2;
 111    public final OnIqPacketReceived registrationResponseListener = (account, packet) -> {
 112        if (packet.getType() == IqPacket.TYPE.RESULT) {
 113            account.setOption(Account.OPTION_REGISTER, false);
 114            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully registered new account on server");
 115            throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 116        } else {
 117            final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 118                    "The password is too weak",
 119                    "Please use a longer password.");
 120            Element error = packet.findChild("error");
 121            Account.State state = Account.State.REGISTRATION_FAILED;
 122            if (error != null) {
 123                if (error.hasChild("conflict")) {
 124                    state = Account.State.REGISTRATION_CONFLICT;
 125                } else if (error.hasChild("resource-constraint")
 126                        && "wait".equals(error.getAttribute("type"))) {
 127                    state = Account.State.REGISTRATION_PLEASE_WAIT;
 128                } else if (error.hasChild("not-acceptable")
 129                        && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 130                    state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 131                }
 132            }
 133            throw new StateChangingError(state);
 134        }
 135    };
 136    protected final Account account;
 137    private final Features features = new Features(this);
 138    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 139    private final HashMap<String, Jid> commands = new HashMap<>();
 140    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 141    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 142    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
 143    private final XmppConnectionService mXmppConnectionService;
 144    private Socket socket;
 145    private XmlReader tagReader;
 146    private TagWriter tagWriter = new TagWriter();
 147    private boolean shouldAuthenticate = true;
 148    private boolean inSmacksSession = false;
 149    private boolean isBound = false;
 150    private Element streamFeatures;
 151    private String streamId = null;
 152    private int smVersion = 3;
 153    private int stanzasReceived = 0;
 154    private int stanzasSent = 0;
 155    private long lastPacketReceived = 0;
 156    private long lastPingSent = 0;
 157    private long lastConnect = 0;
 158    private long lastSessionStarted = 0;
 159    private long lastDiscoStarted = 0;
 160    private boolean isMamPreferenceAlways = false;
 161    private final AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 162    private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 163    private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 164    private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 165    private boolean mInteractive = false;
 166    private int attempt = 0;
 167    private OnPresencePacketReceived presenceListener = null;
 168    private OnJinglePacketReceived jingleListener = null;
 169    private OnIqPacketReceived unregisteredIqListener = null;
 170    private OnMessagePacketReceived messageListener = null;
 171    private OnStatusChanged statusListener = null;
 172    private OnBindListener bindListener = null;
 173    private OnMessageAcknowledged acknowledgedListener = null;
 174    private SaslMechanism saslMechanism;
 175    private HttpUrl redirectionUrl = null;
 176    private String verifiedHostname = null;
 177    private volatile Thread mThread;
 178    private CountDownLatch mStreamCountDownLatch;
 179
 180
 181    public XmppConnection(final Account account, final XmppConnectionService service) {
 182        this.account = account;
 183        this.mXmppConnectionService = service;
 184    }
 185
 186    private static void fixResource(Context context, Account account) {
 187        String resource = account.getResource();
 188        int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
 189        int randomPartLength = 4; // 3 bytes
 190        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 191            if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 192                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 193            }
 194        }
 195    }
 196
 197    private static boolean validBase64(String input) {
 198        try {
 199            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 200        } catch (Throwable throwable) {
 201            return false;
 202        }
 203    }
 204
 205    private void changeStatus(final Account.State nextStatus) {
 206        synchronized (this) {
 207            if (Thread.currentThread().isInterrupted()) {
 208                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
 209                return;
 210            }
 211            if (account.getStatus() != nextStatus) {
 212                if ((nextStatus == Account.State.OFFLINE)
 213                        && (account.getStatus() != Account.State.CONNECTING)
 214                        && (account.getStatus() != Account.State.ONLINE)
 215                        && (account.getStatus() != Account.State.DISABLED)) {
 216                    return;
 217                }
 218                if (nextStatus == Account.State.ONLINE) {
 219                    this.attempt = 0;
 220                }
 221                account.setStatus(nextStatus);
 222            } else {
 223                return;
 224            }
 225        }
 226        if (statusListener != null) {
 227            statusListener.onStatusChanged(account);
 228        }
 229    }
 230
 231    public Jid getJidForCommand(final String node) {
 232        synchronized (this.commands) {
 233            return this.commands.get(node);
 234        }
 235    }
 236
 237    public void prepareNewConnection() {
 238        this.lastConnect = SystemClock.elapsedRealtime();
 239        this.lastPingSent = SystemClock.elapsedRealtime();
 240        this.lastDiscoStarted = Long.MAX_VALUE;
 241        this.mWaitingForSmCatchup.set(false);
 242        this.changeStatus(Account.State.CONNECTING);
 243    }
 244
 245    public boolean isWaitingForSmCatchup() {
 246        return mWaitingForSmCatchup.get();
 247    }
 248
 249    public void incrementSmCatchupMessageCounter() {
 250        this.mSmCatchupMessageCounter.incrementAndGet();
 251    }
 252
 253    protected void connect() {
 254        if (mXmppConnectionService.areMessagesInitialized()) {
 255            mXmppConnectionService.resetSendingToWaiting(account);
 256        }
 257        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 258        features.encryptionEnabled = false;
 259        inSmacksSession = false;
 260        isBound = false;
 261        this.attempt++;
 262        this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
 263        try {
 264            Socket localSocket;
 265            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 266            this.changeStatus(Account.State.CONNECTING);
 267            final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 268            final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 269            if (useTor) {
 270                String destination;
 271                if (account.getHostname().isEmpty() || account.isOnion()) {
 272                    destination = account.getServer();
 273                } else {
 274                    destination = account.getHostname();
 275                    this.verifiedHostname = destination;
 276                }
 277
 278                final int port = account.getPort();
 279                final boolean directTls = Resolver.useDirectTls(port);
 280
 281                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor. directTls=" + directTls);
 282                localSocket = SocksSocketFactory.createSocketOverTor(destination, port);
 283
 284                if (directTls) {
 285                    localSocket = upgradeSocketToTls(localSocket);
 286                    features.encryptionEnabled = true;
 287                }
 288
 289                try {
 290                    startXmpp(localSocket);
 291                } catch (InterruptedException e) {
 292                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 293                    return;
 294                } catch (Exception e) {
 295                    throw new IOException(e.getMessage());
 296                }
 297            } else {
 298                final String domain = account.getServer();
 299                final List<Resolver.Result> results;
 300                final boolean hardcoded = extended && !account.getHostname().isEmpty();
 301                if (hardcoded) {
 302                    results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
 303                } else {
 304                    results = Resolver.resolve(domain);
 305                }
 306                if (Thread.currentThread().isInterrupted()) {
 307                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 308                    return;
 309                }
 310                if (results.size() == 0) {
 311                    Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": Resolver results were empty");
 312                    return;
 313                }
 314                final Resolver.Result storedBackupResult;
 315                if (hardcoded) {
 316                    storedBackupResult = null;
 317                } else {
 318                    storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
 319                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 320                        results.add(storedBackupResult);
 321                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
 322                    }
 323                }
 324                for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
 325                    final Resolver.Result result = iterator.next();
 326                    if (Thread.currentThread().isInterrupted()) {
 327                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 328                        return;
 329                    }
 330                    try {
 331                        // if tls is true, encryption is implied and must not be started
 332                        features.encryptionEnabled = result.isDirectTls();
 333                        verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
 334                        Log.d(Config.LOGTAG, "verified hostname " + verifiedHostname);
 335                        final InetSocketAddress addr;
 336                        if (result.getIp() != null) {
 337                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 338                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 339                                    + ": using values from resolver " + (result.getHostname() == null ? "" : result.getHostname().toString()
 340                                    + "/") + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 341                        } else {
 342                            addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
 343                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 344                                    + ": using values from resolver "
 345                                    + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 346                        }
 347
 348                        localSocket = new Socket();
 349                        localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 350
 351                        if (features.encryptionEnabled) {
 352                            localSocket = upgradeSocketToTls(localSocket);
 353                        }
 354
 355                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 356                        if (startXmpp(localSocket)) {
 357                            localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
 358                            if (!hardcoded && !result.equals(storedBackupResult)) {
 359                                mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
 360                            }
 361                            break; // successfully connected to server that speaks xmpp
 362                        } else {
 363                            FileBackend.close(localSocket);
 364                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 365                        }
 366                    } catch (final StateChangingException e) {
 367                        if (!iterator.hasNext()) {
 368                            throw e;
 369                        }
 370                    } catch (InterruptedException e) {
 371                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 372                        return;
 373                    } catch (final Throwable e) {
 374                        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
 375                        if (!iterator.hasNext()) {
 376                            throw new UnknownHostException();
 377                        }
 378                    }
 379                }
 380            }
 381            processStream();
 382        } catch (final SecurityException e) {
 383            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 384        } catch (final StateChangingException e) {
 385            this.changeStatus(e.state);
 386        } catch (final UnknownHostException | ConnectException | SocksSocketFactory.HostNotFoundException e) {
 387            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 388        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 389            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 390        } catch (final IOException | XmlPullParserException e) {
 391            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 392            this.changeStatus(Account.State.OFFLINE);
 393            this.attempt = Math.max(0, this.attempt - 1);
 394        } finally {
 395            if (!Thread.currentThread().isInterrupted()) {
 396                forceCloseSocket();
 397            } else {
 398                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
 399            }
 400        }
 401    }
 402
 403    /**
 404     * Starts xmpp protocol, call after connecting to socket
 405     *
 406     * @return true if server returns with valid xmpp, false otherwise
 407     */
 408    private boolean startXmpp(Socket socket) throws Exception {
 409        if (Thread.currentThread().isInterrupted()) {
 410            throw new InterruptedException();
 411        }
 412        this.socket = socket;
 413        tagReader = new XmlReader();
 414        if (tagWriter != null) {
 415            tagWriter.forceClose();
 416        }
 417        tagWriter = new TagWriter();
 418        tagWriter.setOutputStream(socket.getOutputStream());
 419        tagReader.setInputStream(socket.getInputStream());
 420        tagWriter.beginDocument();
 421        sendStartStream();
 422        final Tag tag = tagReader.readTag();
 423        if (Thread.currentThread().isInterrupted()) {
 424            throw new InterruptedException();
 425        }
 426        if (socket instanceof SSLSocket) {
 427            SSLSocketHelper.log(account, (SSLSocket) socket);
 428        }
 429        return tag != null && tag.isStart("stream");
 430    }
 431
 432    private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
 433        final SSLContext sc = SSLSocketHelper.getSSLContext();
 434        final MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 435        final KeyManager[] keyManager;
 436        if (account.getPrivateKeyAlias() != null) {
 437            keyManager = new KeyManager[]{new MyKeyManager()};
 438        } else {
 439            keyManager = null;
 440        }
 441        final String domain = account.getServer();
 442        sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 443        return sc.getSocketFactory();
 444    }
 445
 446    @Override
 447    public void run() {
 448        synchronized (this) {
 449            this.mThread = Thread.currentThread();
 450            if (this.mThread.isInterrupted()) {
 451                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
 452                return;
 453            }
 454            forceCloseSocket();
 455        }
 456        connect();
 457    }
 458
 459    private void processStream() throws XmlPullParserException, IOException {
 460        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 461        this.mStreamCountDownLatch = streamCountDownLatch;
 462        Tag nextTag = tagReader.readTag();
 463        while (nextTag != null && !nextTag.isEnd("stream")) {
 464            if (nextTag.isStart("error")) {
 465                processStreamError(nextTag);
 466            } else if (nextTag.isStart("features")) {
 467                processStreamFeatures(nextTag);
 468            } else if (nextTag.isStart("proceed")) {
 469                switchOverToTls();
 470            } else if (nextTag.isStart("success")) {
 471                final String challenge = tagReader.readElement(nextTag).getContent();
 472                try {
 473                    saslMechanism.getResponse(challenge);
 474                } catch (final SaslMechanism.AuthenticationException e) {
 475                    Log.e(Config.LOGTAG, String.valueOf(e));
 476                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 477                }
 478                Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
 479                account.setKey(Account.PINNED_MECHANISM_KEY,
 480                        String.valueOf(saslMechanism.getPriority()));
 481                tagReader.reset();
 482                sendStartStream();
 483                final Tag tag = tagReader.readTag();
 484                if (tag != null && tag.isStart("stream")) {
 485                    processStream();
 486                } else {
 487                    throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 488                }
 489                break;
 490            } else if (nextTag.isStart("failure")) {
 491                final Element failure = tagReader.readElement(nextTag);
 492                if (Namespace.SASL.equals(failure.getNamespace())) {
 493                    final String text = failure.findChildContent("text");
 494                    if (failure.hasChild("account-disabled") && text != null) {
 495                        Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 496                        if (matcher.find()) {
 497                            final HttpUrl url;
 498                            try {
 499                                url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
 500                                if (url.isHttps()) {
 501                                    this.redirectionUrl = url;
 502                                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 503                                }
 504                            } catch (IllegalArgumentException e) {
 505                                throw new StateChangingException(Account.State.UNAUTHORIZED);
 506                            }
 507                        }
 508                    }
 509                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 510                } else if (Namespace.TLS.equals(failure.getNamespace())) {
 511                    throw new StateChangingException(Account.State.TLS_ERROR);
 512                } else {
 513                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 514                }
 515            } else if (nextTag.isStart("challenge")) {
 516                final String challenge = tagReader.readElement(nextTag).getContent();
 517                final Element response = new Element("response", Namespace.SASL);
 518                try {
 519                    response.setContent(saslMechanism.getResponse(challenge));
 520                } catch (final SaslMechanism.AuthenticationException e) {
 521                    // TODO: Send auth abort tag.
 522                    Log.e(Config.LOGTAG, e.toString());
 523                }
 524                tagWriter.writeElement(response);
 525            } else if (nextTag.isStart("enabled")) {
 526                final Element enabled = tagReader.readElement(nextTag);
 527                if ("true".equals(enabled.getAttribute("resume"))) {
 528                    this.streamId = enabled.getAttribute("id");
 529                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 530                            + ": stream management(" + smVersion
 531                            + ") enabled (resumable)");
 532                } else {
 533                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 534                            + ": stream management(" + smVersion + ") enabled");
 535                }
 536                this.stanzasReceived = 0;
 537                this.inSmacksSession = true;
 538                final RequestPacket r = new RequestPacket(smVersion);
 539                tagWriter.writeStanzaAsync(r);
 540            } else if (nextTag.isStart("resumed")) {
 541                this.inSmacksSession = true;
 542                this.isBound = true;
 543                this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 544                lastPacketReceived = SystemClock.elapsedRealtime();
 545                final Element resumed = tagReader.readElement(nextTag);
 546                final String h = resumed.getAttribute("h");
 547                try {
 548                    ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 549                    final boolean acknowledgedMessages;
 550                    synchronized (this.mStanzaQueue) {
 551                        final int serverCount = Integer.parseInt(h);
 552                        if (serverCount < stanzasSent) {
 553                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 554                                    + ": session resumed with lost packages");
 555                            stanzasSent = serverCount;
 556                        } else {
 557                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
 558                        }
 559                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 560                        for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 561                            failedStanzas.add(mStanzaQueue.valueAt(i));
 562                        }
 563                        mStanzaQueue.clear();
 564                    }
 565                    if (acknowledgedMessages) {
 566                        mXmppConnectionService.updateConversationUi();
 567                    }
 568                    Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 569                    for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 570                        if (packet instanceof MessagePacket) {
 571                            MessagePacket message = (MessagePacket) packet;
 572                            mXmppConnectionService.markMessage(account,
 573                                    message.getTo().asBareJid(),
 574                                    message.getId(),
 575                                    Message.STATUS_UNSEND);
 576                        }
 577                        sendPacket(packet);
 578                    }
 579                } catch (final NumberFormatException ignored) {
 580                }
 581                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
 582                changeStatus(Account.State.ONLINE);
 583            } else if (nextTag.isStart("r")) {
 584                tagReader.readElement(nextTag);
 585                if (Config.EXTENDED_SM_LOGGING) {
 586                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 587                }
 588                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 589                tagWriter.writeStanzaAsync(ack);
 590            } else if (nextTag.isStart("a")) {
 591                boolean accountUiNeedsRefresh = false;
 592                synchronized (NotificationService.CATCHUP_LOCK) {
 593                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 594                        final int messageCount = mSmCatchupMessageCounter.get();
 595                        final int pendingIQs = packetCallbacks.size();
 596                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (messages=" + messageCount + ", pending IQs=" + pendingIQs + ")");
 597                        accountUiNeedsRefresh = true;
 598                        if (messageCount > 0) {
 599                            mXmppConnectionService.getNotificationService().finishBacklog(true, account);
 600                        }
 601                    }
 602                }
 603                if (accountUiNeedsRefresh) {
 604                    mXmppConnectionService.updateAccountUi();
 605                }
 606                final Element ack = tagReader.readElement(nextTag);
 607                lastPacketReceived = SystemClock.elapsedRealtime();
 608                try {
 609                    final boolean acknowledgedMessages;
 610                    synchronized (this.mStanzaQueue) {
 611                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 612                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 613                    }
 614                    if (acknowledgedMessages) {
 615                        mXmppConnectionService.updateConversationUi();
 616                    }
 617                } catch (NumberFormatException | NullPointerException e) {
 618                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
 619                }
 620            } else if (nextTag.isStart("failed")) {
 621                Element failed = tagReader.readElement(nextTag);
 622                try {
 623                    final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 624                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
 625                    final boolean acknowledgedMessages;
 626                    synchronized (this.mStanzaQueue) {
 627                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 628                    }
 629                    if (acknowledgedMessages) {
 630                        mXmppConnectionService.updateConversationUi();
 631                    }
 632                } catch (NumberFormatException | NullPointerException e) {
 633                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 634                }
 635                resetStreamId();
 636                sendBindRequest();
 637            } else if (nextTag.isStart("iq")) {
 638                processIq(nextTag);
 639            } else if (nextTag.isStart("message")) {
 640                processMessage(nextTag);
 641            } else if (nextTag.isStart("presence")) {
 642                processPresence(nextTag);
 643            }
 644            nextTag = tagReader.readTag();
 645        }
 646        if (nextTag != null && nextTag.isEnd("stream")) {
 647            streamCountDownLatch.countDown();
 648        }
 649    }
 650
 651    private boolean acknowledgeStanzaUpTo(int serverCount) {
 652        if (serverCount > stanzasSent) {
 653            Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 654        }
 655        boolean acknowledgedMessages = false;
 656        for (int i = 0; i < mStanzaQueue.size(); ++i) {
 657            if (serverCount >= mStanzaQueue.keyAt(i)) {
 658                if (Config.EXTENDED_SM_LOGGING) {
 659                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 660                }
 661                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 662                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 663                    final MessagePacket packet = (MessagePacket) stanza;
 664                    final String id = packet.getId();
 665                    final Jid to = packet.getTo();
 666                    if (id != null && to != null) {
 667                        acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, to, id);
 668                    }
 669                }
 670                mStanzaQueue.removeAt(i);
 671                i--;
 672            }
 673        }
 674        return acknowledgedMessages;
 675    }
 676
 677    private @NonNull
 678    Element processPacket(final Tag currentTag, final int packetType) throws IOException {
 679        final Element element;
 680        switch (packetType) {
 681            case PACKET_IQ:
 682                element = new IqPacket();
 683                break;
 684            case PACKET_MESSAGE:
 685                element = new MessagePacket();
 686                break;
 687            case PACKET_PRESENCE:
 688                element = new PresencePacket();
 689                break;
 690            default:
 691                throw new AssertionError("Should never encounter invalid type");
 692        }
 693        element.setAttributes(currentTag.getAttributes());
 694        Tag nextTag = tagReader.readTag();
 695        if (nextTag == null) {
 696            throw new IOException("interrupted mid tag");
 697        }
 698        while (!nextTag.isEnd(element.getName())) {
 699            if (!nextTag.isNo()) {
 700                element.addChild(tagReader.readElement(nextTag));
 701            }
 702            nextTag = tagReader.readTag();
 703            if (nextTag == null) {
 704                throw new IOException("interrupted mid tag");
 705            }
 706        }
 707        if (stanzasReceived == Integer.MAX_VALUE) {
 708            resetStreamId();
 709            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 710        }
 711        if (inSmacksSession) {
 712            ++stanzasReceived;
 713        } else if (features.sm()) {
 714            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 715        }
 716        lastPacketReceived = SystemClock.elapsedRealtime();
 717        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 718            Log.d(Config.LOGTAG, "[background stanza] " + element);
 719        }
 720        if (element instanceof IqPacket
 721                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
 722                && element.hasChild("jingle", Namespace.JINGLE)) {
 723            return JinglePacket.upgrade((IqPacket) element);
 724        } else {
 725            return element;
 726        }
 727    }
 728
 729    private void processIq(final Tag currentTag) throws IOException {
 730        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 731        if (!packet.valid()) {
 732            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 733            return;
 734        }
 735        if (packet instanceof JinglePacket) {
 736            if (this.jingleListener != null) {
 737                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 738            }
 739        } else {
 740            OnIqPacketReceived callback = null;
 741            synchronized (this.packetCallbacks) {
 742                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 743                if (packetCallbackDuple != null) {
 744                    // Packets to the server should have responses from the server
 745                    if (packetCallbackDuple.first.toServer(account)) {
 746                        if (packet.fromServer(account)) {
 747                            callback = packetCallbackDuple.second;
 748                            packetCallbacks.remove(packet.getId());
 749                        } else {
 750                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 751                        }
 752                    } else {
 753                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 754                            callback = packetCallbackDuple.second;
 755                            packetCallbacks.remove(packet.getId());
 756                        } else {
 757                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 758                        }
 759                    }
 760                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 761                    callback = this.unregisteredIqListener;
 762                }
 763            }
 764            if (callback != null) {
 765                try {
 766                    callback.onIqPacketReceived(account, packet);
 767                } catch (StateChangingError error) {
 768                    throw new StateChangingException(error.state);
 769                }
 770            }
 771        }
 772    }
 773
 774    private void processMessage(final Tag currentTag) throws IOException {
 775        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 776        if (!packet.valid()) {
 777            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 778            return;
 779        }
 780        this.messageListener.onMessagePacketReceived(account, packet);
 781    }
 782
 783    private void processPresence(final Tag currentTag) throws IOException {
 784        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 785        if (!packet.valid()) {
 786            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 787            return;
 788        }
 789        this.presenceListener.onPresencePacketReceived(account, packet);
 790    }
 791
 792    private void sendStartTLS() throws IOException {
 793        final Tag startTLS = Tag.empty("starttls");
 794        startTLS.setAttribute("xmlns", Namespace.TLS);
 795        tagWriter.writeTag(startTLS);
 796    }
 797
 798    private void switchOverToTls() throws XmlPullParserException, IOException {
 799        tagReader.readTag();
 800        final Socket socket = this.socket;
 801        final SSLSocket sslSocket = upgradeSocketToTls(socket);
 802        tagReader.setInputStream(sslSocket.getInputStream());
 803        tagWriter.setOutputStream(sslSocket.getOutputStream());
 804        sendStartStream();
 805        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 806        features.encryptionEnabled = true;
 807        final Tag tag = tagReader.readTag();
 808        if (tag != null && tag.isStart("stream")) {
 809            SSLSocketHelper.log(account, sslSocket);
 810            processStream();
 811        } else {
 812            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 813        }
 814        sslSocket.close();
 815    }
 816
 817    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
 818        final SSLSocketFactory sslSocketFactory;
 819        try {
 820            sslSocketFactory = getSSLSocketFactory();
 821        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
 822            throw new StateChangingException(Account.State.TLS_ERROR);
 823        }
 824        final InetAddress address = socket.getInetAddress();
 825        final SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 826        SSLSocketHelper.setSecurity(sslSocket);
 827        SSLSocketHelper.setHostname(sslSocket, IDN.toASCII(account.getServer()));
 828        SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 829        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
 830        try {
 831            if (!xmppDomainVerifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 832                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate domain verification failed");
 833                FileBackend.close(sslSocket);
 834                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
 835            }
 836        } catch (final SSLPeerUnverifiedException e) {
 837            FileBackend.close(sslSocket);
 838            throw new StateChangingException(Account.State.TLS_ERROR);
 839        }
 840        return sslSocket;
 841    }
 842
 843    private void processStreamFeatures(final Tag currentTag) throws IOException {
 844        this.streamFeatures = tagReader.readElement(currentTag);
 845        final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 846        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 847        if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 848            sendStartTLS();
 849        } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 850            if (isSecure) {
 851                register();
 852            } else {
 853                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find STARTTLS for registration process " + XmlHelper.printElementNames(this.streamFeatures));
 854                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 855            }
 856        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 857            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 858        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 859            authenticate();
 860        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 861            if (Config.EXTENDED_SM_LOGGING) {
 862                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 863            }
 864            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 865            this.mSmCatchupMessageCounter.set(0);
 866            this.mWaitingForSmCatchup.set(true);
 867            this.tagWriter.writeStanzaAsync(resume);
 868        } else if (needsBinding) {
 869            if (this.streamFeatures.hasChild("bind") && isSecure) {
 870                sendBindRequest();
 871            } else {
 872                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find bind feature " + XmlHelper.printElementNames(this.streamFeatures));
 873                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 874            }
 875        }
 876    }
 877
 878    private void authenticate() throws IOException {
 879        final List<String> mechanisms = extractMechanisms(streamFeatures.findChild("mechanisms"));
 880        final Element auth = new Element("auth", Namespace.SASL);
 881        if (mechanisms.contains(External.MECHANISM) && account.getPrivateKeyAlias() != null) {
 882            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 883        } else if (mechanisms.contains(ScramSha512.MECHANISM)) {
 884            saslMechanism = new ScramSha512(tagWriter, account, mXmppConnectionService.getRNG());
 885        } else if (mechanisms.contains(ScramSha256.MECHANISM)) {
 886            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 887        } else if (mechanisms.contains(ScramSha1.MECHANISM)) {
 888            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 889        } else if (mechanisms.contains(Plain.MECHANISM) && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
 890            saslMechanism = new Plain(tagWriter, account);
 891        } else if (mechanisms.contains(DigestMd5.MECHANISM)) {
 892            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 893        } else if (mechanisms.contains(Anonymous.MECHANISM)) {
 894            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 895        }
 896        if (saslMechanism != null) {
 897            final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 898            if (pinnedMechanism > saslMechanism.getPriority()) {
 899                Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 900                        " has lower priority (" + saslMechanism.getPriority() +
 901                        ") than pinned priority (" + pinnedMechanism +
 902                        "). Possible downgrade attack?");
 903                throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 904            }
 905            Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 906            auth.setAttribute("mechanism", saslMechanism.getMechanism());
 907            if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 908                auth.setContent(saslMechanism.getClientFirstMessage());
 909            }
 910            tagWriter.writeElement(auth);
 911        } else {
 912            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find supported SASL mechanism in " + mechanisms);
 913            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 914        }
 915    }
 916
 917    private List<String> extractMechanisms(final Element stream) {
 918        final ArrayList<String> mechanisms = new ArrayList<>(stream
 919                .getChildren().size());
 920        for (final Element child : stream.getChildren()) {
 921            mechanisms.add(child.getContent());
 922        }
 923        return mechanisms;
 924    }
 925
 926
 927    private void register() {
 928        final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
 929        if (preAuth != null && features.invite()) {
 930            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
 931            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
 932            sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
 933                if (response.getType() == IqPacket.TYPE.RESULT) {
 934                    sendRegistryRequest();
 935                } else {
 936                    final String error = response.getErrorCondition();
 937                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to pre auth. " + error);
 938                    throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
 939                }
 940            }, true);
 941        } else {
 942            sendRegistryRequest();
 943        }
 944    }
 945
 946    private void sendRegistryRequest() {
 947        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 948        register.query(Namespace.REGISTER);
 949        register.setTo(account.getDomain());
 950        sendUnmodifiedIqPacket(register, (account, packet) -> {
 951            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 952                return;
 953            }
 954            if (packet.getType() == IqPacket.TYPE.ERROR) {
 955                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 956            }
 957            final Element query = packet.query(Namespace.REGISTER);
 958            if (query.hasChild("username") && (query.hasChild("password"))) {
 959                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 960                final Element username = new Element("username").setContent(account.getUsername());
 961                final Element password = new Element("password").setContent(account.getPassword());
 962                register1.query(Namespace.REGISTER).addChild(username);
 963                register1.query().addChild(password);
 964                register1.setFrom(account.getJid().asBareJid());
 965                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 966            } else if (query.hasChild("x", Namespace.DATA)) {
 967                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 968                final Element blob = query.findChild("data", "urn:xmpp:bob");
 969                final String id = packet.getId();
 970                InputStream is;
 971                if (blob != null) {
 972                    try {
 973                        final String base64Blob = blob.getContent();
 974                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 975                        is = new ByteArrayInputStream(strBlob);
 976                    } catch (Exception e) {
 977                        is = null;
 978                    }
 979                } else {
 980                    final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 981                    try {
 982                        final String url = data.getValue("url");
 983                        final String fallbackUrl = data.getValue("captcha-fallback-url");
 984                        if (url != null) {
 985                            is = HttpConnectionManager.open(url, useTor);
 986                        } else if (fallbackUrl != null) {
 987                            is = HttpConnectionManager.open(fallbackUrl, useTor);
 988                        } else {
 989                            is = null;
 990                        }
 991                    } catch (final IOException e) {
 992                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to fetch captcha", e);
 993                        is = null;
 994                    }
 995                }
 996
 997                if (is != null) {
 998                    Bitmap captcha = BitmapFactory.decodeStream(is);
 999                    try {
1000                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
1001                            return;
1002                        }
1003                    } catch (Exception e) {
1004                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1005                    }
1006                }
1007                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1008            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
1009                final String instructions = query.findChildContent("instructions");
1010                final Element oob = query.findChild("x", Namespace.OOB);
1011                final String url = oob == null ? null : oob.findChildContent("url");
1012                if (url != null) {
1013                    setAccountCreationFailed(url);
1014                } else if (instructions != null) {
1015                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1016                    if (matcher.find()) {
1017                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1018                    }
1019                }
1020                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1021            }
1022        }, true);
1023    }
1024
1025    private void setAccountCreationFailed(final String url) {
1026        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1027        if (httpUrl != null && httpUrl.isHttps()) {
1028            this.redirectionUrl = httpUrl;
1029            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1030        }
1031        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1032    }
1033
1034    public HttpUrl getRedirectionUrl() {
1035        return this.redirectionUrl;
1036    }
1037
1038    public void resetEverything() {
1039        resetAttemptCount(true);
1040        resetStreamId();
1041        clearIqCallbacks();
1042        this.stanzasSent = 0;
1043        mStanzaQueue.clear();
1044        this.redirectionUrl = null;
1045        synchronized (this.disco) {
1046            disco.clear();
1047        }
1048        synchronized (this.commands) {
1049            this.commands.clear();
1050        }
1051    }
1052
1053    private void sendBindRequest() {
1054        try {
1055            mXmppConnectionService.restoredFromDatabaseLatch.await();
1056        } catch (InterruptedException e) {
1057            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1058            return;
1059        }
1060        clearIqCallbacks();
1061        if (account.getJid().isBareJid()) {
1062            account.setResource(this.createNewResource());
1063        } else {
1064            fixResource(mXmppConnectionService, account);
1065        }
1066        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1067        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1068        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1069        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1070            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1071                return;
1072            }
1073            final Element bind = packet.findChild("bind");
1074            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1075                isBound = true;
1076                final Element jid = bind.findChild("jid");
1077                if (jid != null && jid.getContent() != null) {
1078                    try {
1079                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1080                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1081                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1082                            throw new StateChangingError(Account.State.BIND_FAILURE);
1083                        }
1084                        if (account.setJid(assignedJid)) {
1085                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1086                            mXmppConnectionService.databaseBackend.updateAccount(account);
1087                        }
1088                        if (streamFeatures.hasChild("session")
1089                                && !streamFeatures.findChild("session").hasChild("optional")) {
1090                            sendStartSession();
1091                        } else {
1092                            sendPostBindInitialization();
1093                        }
1094                        return;
1095                    } catch (final IllegalArgumentException e) {
1096                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1097                    }
1098                } else {
1099                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1100                }
1101            } else {
1102                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1103            }
1104            final Element error = packet.findChild("error");
1105            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1106                account.setResource(createNewResource());
1107            }
1108            throw new StateChangingError(Account.State.BIND_FAILURE);
1109        }, true);
1110    }
1111
1112    private void clearIqCallbacks() {
1113        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1114        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1115        synchronized (this.packetCallbacks) {
1116            if (this.packetCallbacks.size() == 0) {
1117                return;
1118            }
1119            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1120            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1121            while (iterator.hasNext()) {
1122                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1123                callbacks.add(entry.second);
1124                iterator.remove();
1125            }
1126        }
1127        for (OnIqPacketReceived callback : callbacks) {
1128            try {
1129                callback.onIqPacketReceived(account, failurePacket);
1130            } catch (StateChangingError error) {
1131                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1132                //ignore
1133            }
1134        }
1135        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1136    }
1137
1138    public void sendDiscoTimeout() {
1139        if (mWaitForDisco.compareAndSet(true, false)) {
1140            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1141            finalizeBind();
1142        }
1143    }
1144
1145    private void sendStartSession() {
1146        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1147        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1148        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1149        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1150            if (packet.getType() == IqPacket.TYPE.RESULT) {
1151                sendPostBindInitialization();
1152            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1153                throw new StateChangingError(Account.State.SESSION_FAILURE);
1154            }
1155        }, true);
1156    }
1157
1158    private void sendPostBindInitialization() {
1159        smVersion = 0;
1160        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1161            smVersion = 3;
1162        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1163            smVersion = 2;
1164        }
1165        if (smVersion != 0) {
1166            synchronized (this.mStanzaQueue) {
1167                final EnablePacket enable = new EnablePacket(smVersion);
1168                tagWriter.writeStanzaAsync(enable);
1169                stanzasSent = 0;
1170                mStanzaQueue.clear();
1171            }
1172        }
1173        features.carbonsEnabled = false;
1174        features.blockListRequested = false;
1175        synchronized (this.disco) {
1176            this.disco.clear();
1177        }
1178        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1179        mPendingServiceDiscoveries.set(0);
1180        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain().toEscapedString())) {
1181            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1182            mWaitForDisco.set(false);
1183        } else {
1184            mWaitForDisco.set(true);
1185        }
1186        lastDiscoStarted = SystemClock.elapsedRealtime();
1187        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1188        Element caps = streamFeatures.findChild("c");
1189        final String hash = caps == null ? null : caps.getAttribute("hash");
1190        final String ver = caps == null ? null : caps.getAttribute("ver");
1191        ServiceDiscoveryResult discoveryResult = null;
1192        if (hash != null && ver != null) {
1193            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1194        }
1195        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1196        if (requestDiscoItemsFirst) {
1197            sendServiceDiscoveryItems(account.getDomain());
1198        }
1199        if (discoveryResult == null) {
1200            sendServiceDiscoveryInfo(account.getDomain());
1201        } else {
1202            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1203            disco.put(account.getDomain(), discoveryResult);
1204        }
1205        discoverMamPreferences();
1206        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1207        if (!requestDiscoItemsFirst) {
1208            sendServiceDiscoveryItems(account.getDomain());
1209        }
1210
1211        if (!mWaitForDisco.get()) {
1212            finalizeBind();
1213        }
1214        this.lastSessionStarted = SystemClock.elapsedRealtime();
1215    }
1216
1217    private void sendServiceDiscoveryInfo(final Jid jid) {
1218        mPendingServiceDiscoveries.incrementAndGet();
1219        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1220        iq.setTo(jid);
1221        iq.query("http://jabber.org/protocol/disco#info");
1222        this.sendIqPacket(iq, (account, packet) -> {
1223            if (packet.getType() == IqPacket.TYPE.RESULT) {
1224                boolean advancedStreamFeaturesLoaded;
1225                synchronized (XmppConnection.this.disco) {
1226                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1227                    if (jid.equals(account.getDomain())) {
1228                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1229                    }
1230                    disco.put(jid, result);
1231                    advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain())
1232                            && disco.containsKey(account.getJid().asBareJid());
1233                }
1234                if (advancedStreamFeaturesLoaded && (jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid()))) {
1235                    enableAdvancedStreamFeatures();
1236                }
1237            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1238                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1239                final boolean serverOrAccount = jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid());
1240                final boolean advancedStreamFeaturesLoaded;
1241                if (serverOrAccount) {
1242                    synchronized (XmppConnection.this.disco) {
1243                        disco.put(jid, ServiceDiscoveryResult.empty());
1244                        advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain()) && disco.containsKey(account.getJid().asBareJid());
1245                    }
1246                } else {
1247                    advancedStreamFeaturesLoaded = false;
1248                }
1249                if (advancedStreamFeaturesLoaded) {
1250                    enableAdvancedStreamFeatures();
1251                }
1252            }
1253            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1254                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1255                        && mWaitForDisco.compareAndSet(true, false)) {
1256                    finalizeBind();
1257                }
1258            }
1259        });
1260    }
1261
1262    private void discoverMamPreferences() {
1263        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1264        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1265        sendIqPacket(request, (account, response) -> {
1266            if (response.getType() == IqPacket.TYPE.RESULT) {
1267                Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1268                isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1269            }
1270        });
1271    }
1272
1273    private void discoverCommands() {
1274        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1275        request.setTo(account.getDomain());
1276        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1277        sendIqPacket(request, (account, response) -> {
1278            if (response.getType() == IqPacket.TYPE.RESULT) {
1279                final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1280                if (query == null) {
1281                    return;
1282                }
1283                final HashMap<String, Jid> commands = new HashMap<>();
1284                for (final Element child : query.getChildren()) {
1285                    if ("item".equals(child.getName())) {
1286                        final String node = child.getAttribute("node");
1287                        final Jid jid = child.getAttributeAsJid("jid");
1288                        if (node != null && jid != null) {
1289                            commands.put(node, jid);
1290                        }
1291                    }
1292                }
1293                Log.d(Config.LOGTAG, commands.toString());
1294                synchronized (this.commands) {
1295                    this.commands.clear();
1296                    this.commands.putAll(commands);
1297                }
1298            }
1299        });
1300    }
1301
1302    public boolean isMamPreferenceAlways() {
1303        return isMamPreferenceAlways;
1304    }
1305
1306    private void finalizeBind() {
1307        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1308        if (bindListener != null) {
1309            bindListener.onBind(account);
1310        }
1311        changeStatus(Account.State.ONLINE);
1312    }
1313
1314    private void enableAdvancedStreamFeatures() {
1315        if (getFeatures().blocking() && !features.blockListRequested) {
1316            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1317            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1318        }
1319        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1320            listener.onAdvancedStreamFeaturesAvailable(account);
1321        }
1322        if (getFeatures().carbons() && !features.carbonsEnabled) {
1323            sendEnableCarbons();
1324        }
1325        if (getFeatures().commands()) {
1326            discoverCommands();
1327        }
1328    }
1329
1330    private void sendServiceDiscoveryItems(final Jid server) {
1331        mPendingServiceDiscoveries.incrementAndGet();
1332        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1333        iq.setTo(server.getDomain());
1334        iq.query("http://jabber.org/protocol/disco#items");
1335        this.sendIqPacket(iq, (account, packet) -> {
1336            if (packet.getType() == IqPacket.TYPE.RESULT) {
1337                final HashSet<Jid> items = new HashSet<>();
1338                final List<Element> elements = packet.query().getChildren();
1339                for (final Element element : elements) {
1340                    if (element.getName().equals("item")) {
1341                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1342                        if (jid != null && !jid.equals(account.getDomain())) {
1343                            items.add(jid);
1344                        }
1345                    }
1346                }
1347                for (Jid jid : items) {
1348                    sendServiceDiscoveryInfo(jid);
1349                }
1350            } else {
1351                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1352            }
1353            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1354                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1355                        && mWaitForDisco.compareAndSet(true, false)) {
1356                    finalizeBind();
1357                }
1358            }
1359        });
1360    }
1361
1362    private void sendEnableCarbons() {
1363        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1364        iq.addChild("enable", "urn:xmpp:carbons:2");
1365        this.sendIqPacket(iq, (account, packet) -> {
1366            if (!packet.hasChild("error")) {
1367                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1368                        + ": successfully enabled carbons");
1369                features.carbonsEnabled = true;
1370            } else {
1371                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1372                        + ": error enableing carbons " + packet.toString());
1373            }
1374        });
1375    }
1376
1377    private void processStreamError(final Tag currentTag) throws IOException {
1378        final Element streamError = tagReader.readElement(currentTag);
1379        if (streamError == null) {
1380            return;
1381        }
1382        if (streamError.hasChild("conflict")) {
1383            account.setResource(createNewResource());
1384            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1385            throw new IOException();
1386        } else if (streamError.hasChild("host-unknown")) {
1387            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1388        } else if (streamError.hasChild("policy-violation")) {
1389            this.lastConnect = SystemClock.elapsedRealtime();
1390            final String text = streamError.findChildContent("text");
1391            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1392            failPendingMessages(text);
1393            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1394        } else {
1395            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1396            throw new StateChangingException(Account.State.STREAM_ERROR);
1397        }
1398    }
1399
1400    private void failPendingMessages(final String error) {
1401        synchronized (this.mStanzaQueue) {
1402            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1403                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1404                if (stanza instanceof MessagePacket) {
1405                    final MessagePacket packet = (MessagePacket) stanza;
1406                    final String id = packet.getId();
1407                    final Jid to = packet.getTo();
1408                    mXmppConnectionService.markMessage(account,
1409                            to.asBareJid(),
1410                            id,
1411                            Message.STATUS_SEND_FAILED,
1412                            error);
1413                }
1414            }
1415        }
1416    }
1417
1418    private void sendStartStream() throws IOException {
1419        final Tag stream = Tag.start("stream:stream");
1420        stream.setAttribute("to", account.getServer());
1421        stream.setAttribute("version", "1.0");
1422        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1423        stream.setAttribute("xmlns", "jabber:client");
1424        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1425        tagWriter.writeTag(stream);
1426    }
1427
1428    private String createNewResource() {
1429        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1430    }
1431
1432    private String nextRandomId() {
1433        return nextRandomId(false);
1434    }
1435
1436    private String nextRandomId(boolean s) {
1437        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1438    }
1439
1440    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1441        packet.setFrom(account.getJid());
1442        return this.sendUnmodifiedIqPacket(packet, callback, false);
1443    }
1444
1445    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1446        if (packet.getId() == null) {
1447            packet.setAttribute("id", nextRandomId());
1448        }
1449        if (callback != null) {
1450            synchronized (this.packetCallbacks) {
1451                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1452            }
1453        }
1454        this.sendPacket(packet, force);
1455        return packet.getId();
1456    }
1457
1458    public void sendMessagePacket(final MessagePacket packet) {
1459        this.sendPacket(packet);
1460    }
1461
1462    public void sendPresencePacket(final PresencePacket packet) {
1463        this.sendPacket(packet);
1464    }
1465
1466    private synchronized void sendPacket(final AbstractStanza packet) {
1467        sendPacket(packet, false);
1468    }
1469
1470    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1471        if (stanzasSent == Integer.MAX_VALUE) {
1472            resetStreamId();
1473            disconnect(true);
1474            return;
1475        }
1476        synchronized (this.mStanzaQueue) {
1477            if (force || isBound) {
1478                tagWriter.writeStanzaAsync(packet);
1479            } else {
1480                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1481            }
1482            if (packet instanceof AbstractAcknowledgeableStanza) {
1483                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1484
1485                if (this.mStanzaQueue.size() != 0) {
1486                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1487                    if (currentHighestKey != stanzasSent) {
1488                        throw new AssertionError("Stanza count messed up");
1489                    }
1490                }
1491
1492                ++stanzasSent;
1493                this.mStanzaQueue.append(stanzasSent, stanza);
1494                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1495                    if (Config.EXTENDED_SM_LOGGING) {
1496                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1497                    }
1498                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1499                }
1500            }
1501        }
1502    }
1503
1504    public void sendPing() {
1505        if (!r()) {
1506            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1507            iq.setFrom(account.getJid());
1508            iq.addChild("ping", Namespace.PING);
1509            this.sendIqPacket(iq, null);
1510        }
1511        this.lastPingSent = SystemClock.elapsedRealtime();
1512    }
1513
1514    public void setOnMessagePacketReceivedListener(
1515            final OnMessagePacketReceived listener) {
1516        this.messageListener = listener;
1517    }
1518
1519    public void setOnUnregisteredIqPacketReceivedListener(
1520            final OnIqPacketReceived listener) {
1521        this.unregisteredIqListener = listener;
1522    }
1523
1524    public void setOnPresencePacketReceivedListener(
1525            final OnPresencePacketReceived listener) {
1526        this.presenceListener = listener;
1527    }
1528
1529    public void setOnJinglePacketReceivedListener(
1530            final OnJinglePacketReceived listener) {
1531        this.jingleListener = listener;
1532    }
1533
1534    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1535        this.statusListener = listener;
1536    }
1537
1538    public void setOnBindListener(final OnBindListener listener) {
1539        this.bindListener = listener;
1540    }
1541
1542    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1543        this.acknowledgedListener = listener;
1544    }
1545
1546    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1547        this.advancedStreamFeaturesLoadedListeners.add(listener);
1548    }
1549
1550    private void forceCloseSocket() {
1551        FileBackend.close(this.socket);
1552        FileBackend.close(this.tagReader);
1553    }
1554
1555    public void interrupt() {
1556        if (this.mThread != null) {
1557            this.mThread.interrupt();
1558        }
1559    }
1560
1561    public void disconnect(final boolean force) {
1562        interrupt();
1563        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1564        if (force) {
1565            forceCloseSocket();
1566        } else {
1567            final TagWriter currentTagWriter = this.tagWriter;
1568            if (currentTagWriter.isActive()) {
1569                currentTagWriter.finish();
1570                final Socket currentSocket = this.socket;
1571                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1572                try {
1573                    currentTagWriter.await(1, TimeUnit.SECONDS);
1574                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1575                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1576                    if (streamCountDownLatch != null) {
1577                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1578                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1579                        } else {
1580                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1581                        }
1582                    }
1583                } catch (InterruptedException e) {
1584                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1585                } catch (final IOException e) {
1586                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1587                } finally {
1588                    FileBackend.close(currentSocket);
1589                }
1590            } else {
1591                forceCloseSocket();
1592            }
1593        }
1594    }
1595
1596    private void resetStreamId() {
1597        this.streamId = null;
1598    }
1599
1600    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1601        synchronized (this.disco) {
1602            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1603            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1604                if (cursor.getValue().getFeatures().contains(feature)) {
1605                    items.add(cursor);
1606                }
1607            }
1608            return items;
1609        }
1610    }
1611
1612    public Jid findDiscoItemByFeature(final String feature) {
1613        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1614        if (items.size() >= 1) {
1615            return items.get(0).getKey();
1616        }
1617        return null;
1618    }
1619
1620    public boolean r() {
1621        if (getFeatures().sm()) {
1622            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1623            return true;
1624        } else {
1625            return false;
1626        }
1627    }
1628
1629    public List<String> getMucServersWithholdAccount() {
1630        final List<String> servers = getMucServers();
1631        servers.remove(account.getDomain().toEscapedString());
1632        return servers;
1633    }
1634
1635    public List<String> getMucServers() {
1636        List<String> servers = new ArrayList<>();
1637        synchronized (this.disco) {
1638            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1639                final ServiceDiscoveryResult value = cursor.getValue();
1640                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1641                        && value.hasIdentity("conference", "text")
1642                        && !value.getFeatures().contains("jabber:iq:gateway")
1643                        && !value.hasIdentity("conference", "irc")) {
1644                    servers.add(cursor.getKey().toString());
1645                }
1646            }
1647        }
1648        return servers;
1649    }
1650
1651    public String getMucServer() {
1652        List<String> servers = getMucServers();
1653        return servers.size() > 0 ? servers.get(0) : null;
1654    }
1655
1656    public int getTimeToNextAttempt() {
1657        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1658        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1659        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1660        return interval - secondsSinceLast;
1661    }
1662
1663    public int getAttempt() {
1664        return this.attempt;
1665    }
1666
1667    public Features getFeatures() {
1668        return this.features;
1669    }
1670
1671    public long getLastSessionEstablished() {
1672        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1673        return System.currentTimeMillis() - diff;
1674    }
1675
1676    public long getLastConnect() {
1677        return this.lastConnect;
1678    }
1679
1680    public long getLastPingSent() {
1681        return this.lastPingSent;
1682    }
1683
1684    public long getLastDiscoStarted() {
1685        return this.lastDiscoStarted;
1686    }
1687
1688    public long getLastPacketReceived() {
1689        return this.lastPacketReceived;
1690    }
1691
1692    public void sendActive() {
1693        this.sendPacket(new ActivePacket());
1694    }
1695
1696    public void sendInactive() {
1697        this.sendPacket(new InactivePacket());
1698    }
1699
1700    public void resetAttemptCount(boolean resetConnectTime) {
1701        this.attempt = 0;
1702        if (resetConnectTime) {
1703            this.lastConnect = 0;
1704        }
1705    }
1706
1707    public void setInteractive(boolean interactive) {
1708        this.mInteractive = interactive;
1709    }
1710
1711    public Identity getServerIdentity() {
1712        synchronized (this.disco) {
1713            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1714            if (result == null) {
1715                return Identity.UNKNOWN;
1716            }
1717            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1718                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1719                    switch (id.getName()) {
1720                        case "Prosody":
1721                            return Identity.PROSODY;
1722                        case "ejabberd":
1723                            return Identity.EJABBERD;
1724                        case "Slack-XMPP":
1725                            return Identity.SLACK;
1726                    }
1727                }
1728            }
1729        }
1730        return Identity.UNKNOWN;
1731    }
1732
1733    private IqGenerator getIqGenerator() {
1734        return mXmppConnectionService.getIqGenerator();
1735    }
1736
1737    public enum Identity {
1738        FACEBOOK,
1739        SLACK,
1740        EJABBERD,
1741        PROSODY,
1742        NIMBUZZ,
1743        UNKNOWN
1744    }
1745
1746    private class MyKeyManager implements X509KeyManager {
1747        @Override
1748        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1749            return account.getPrivateKeyAlias();
1750        }
1751
1752        @Override
1753        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1754            return null;
1755        }
1756
1757        @Override
1758        public X509Certificate[] getCertificateChain(String alias) {
1759            Log.d(Config.LOGTAG, "getting certificate chain");
1760            try {
1761                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1762            } catch (Exception e) {
1763                Log.d(Config.LOGTAG, e.getMessage());
1764                return new X509Certificate[0];
1765            }
1766        }
1767
1768        @Override
1769        public String[] getClientAliases(String s, Principal[] principals) {
1770            final String alias = account.getPrivateKeyAlias();
1771            return alias != null ? new String[]{alias} : new String[0];
1772        }
1773
1774        @Override
1775        public String[] getServerAliases(String s, Principal[] principals) {
1776            return new String[0];
1777        }
1778
1779        @Override
1780        public PrivateKey getPrivateKey(String alias) {
1781            try {
1782                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1783            } catch (Exception e) {
1784                return null;
1785            }
1786        }
1787    }
1788
1789    private static class StateChangingError extends Error {
1790        private final Account.State state;
1791
1792        public StateChangingError(Account.State state) {
1793            this.state = state;
1794        }
1795    }
1796
1797    private static class StateChangingException extends IOException {
1798        private final Account.State state;
1799
1800        public StateChangingException(Account.State state) {
1801            this.state = state;
1802        }
1803    }
1804
1805    public class Features {
1806        XmppConnection connection;
1807        private boolean carbonsEnabled = false;
1808        private boolean encryptionEnabled = false;
1809        private boolean blockListRequested = false;
1810
1811        public Features(final XmppConnection connection) {
1812            this.connection = connection;
1813        }
1814
1815        private boolean hasDiscoFeature(final Jid server, final String feature) {
1816            synchronized (XmppConnection.this.disco) {
1817                return connection.disco.containsKey(server) &&
1818                        connection.disco.get(server).getFeatures().contains(feature);
1819            }
1820        }
1821
1822        public boolean carbons() {
1823            return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
1824        }
1825
1826        public boolean commands() {
1827            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
1828        }
1829
1830        public boolean easyOnboardingInvites() {
1831            synchronized (commands) {
1832                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
1833            }
1834        }
1835
1836        public boolean bookmarksConversion() {
1837            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1838        }
1839
1840        public boolean avatarConversion() {
1841            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1842        }
1843
1844        public boolean blocking() {
1845            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
1846        }
1847
1848        public boolean spamReporting() {
1849            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
1850        }
1851
1852        public boolean flexibleOfflineMessageRetrieval() {
1853            return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1854        }
1855
1856        public boolean register() {
1857            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
1858        }
1859
1860        public boolean invite() {
1861            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1862        }
1863
1864        public boolean sm() {
1865            return streamId != null
1866                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1867        }
1868
1869        public boolean csi() {
1870            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1871        }
1872
1873        public boolean pep() {
1874            synchronized (XmppConnection.this.disco) {
1875                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1876                return info != null && info.hasIdentity("pubsub", "pep");
1877            }
1878        }
1879
1880        public boolean pepPersistent() {
1881            synchronized (XmppConnection.this.disco) {
1882                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1883                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1884            }
1885        }
1886
1887        public boolean pepPublishOptions() {
1888            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1889        }
1890
1891        public boolean pepOmemoWhitelisted() {
1892            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1893        }
1894
1895        public boolean mam() {
1896            return MessageArchiveService.Version.has(getAccountFeatures());
1897        }
1898
1899        public List<String> getAccountFeatures() {
1900            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1901            return result == null ? Collections.emptyList() : result.getFeatures();
1902        }
1903
1904        public boolean push() {
1905            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1906                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
1907        }
1908
1909        public boolean rosterVersioning() {
1910            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1911        }
1912
1913        public void setBlockListRequested(boolean value) {
1914            this.blockListRequested = value;
1915        }
1916
1917        public boolean httpUpload(long filesize) {
1918            if (Config.DISABLE_HTTP_UPLOAD) {
1919                return false;
1920            } else {
1921                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1922                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1923                    if (items.size() > 0) {
1924                        try {
1925                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1926                            if (filesize <= maxsize) {
1927                                return true;
1928                            } else {
1929                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1930                                return false;
1931                            }
1932                        } catch (Exception e) {
1933                            return true;
1934                        }
1935                    }
1936                }
1937                return false;
1938            }
1939        }
1940
1941        public boolean useLegacyHttpUpload() {
1942            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1943        }
1944
1945        public long getMaxHttpUploadSize() {
1946            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1947                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1948                if (items.size() > 0) {
1949                    try {
1950                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1951                    } catch (Exception e) {
1952                        //ignored
1953                    }
1954                }
1955            }
1956            return -1;
1957        }
1958
1959        public boolean stanzaIds() {
1960            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1961        }
1962
1963        public boolean bookmarks2() {
1964            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
1965        }
1966
1967        public boolean externalServiceDiscovery() {
1968            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
1969        }
1970    }
1971}