XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
   4
   5import android.content.Context;
   6import android.graphics.Bitmap;
   7import android.graphics.BitmapFactory;
   8import android.os.Build;
   9import android.os.SystemClock;
  10import android.security.KeyChain;
  11import android.util.Base64;
  12import android.util.Log;
  13import android.util.Pair;
  14import android.util.SparseArray;
  15
  16import androidx.annotation.NonNull;
  17import androidx.annotation.Nullable;
  18
  19import com.google.common.base.MoreObjects;
  20import com.google.common.base.Optional;
  21import com.google.common.base.Preconditions;
  22import com.google.common.base.Strings;
  23import com.google.common.collect.ImmutableList;
  24
  25import eu.siacs.conversations.Config;
  26import eu.siacs.conversations.R;
  27import eu.siacs.conversations.crypto.XmppDomainVerifier;
  28import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  29import eu.siacs.conversations.crypto.sasl.ChannelBinding;
  30import eu.siacs.conversations.crypto.sasl.ChannelBindingMechanism;
  31import eu.siacs.conversations.crypto.sasl.HashedToken;
  32import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  33import eu.siacs.conversations.entities.Account;
  34import eu.siacs.conversations.entities.Message;
  35import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  36import eu.siacs.conversations.generator.IqGenerator;
  37import eu.siacs.conversations.http.HttpConnectionManager;
  38import eu.siacs.conversations.persistance.FileBackend;
  39import eu.siacs.conversations.services.MemorizingTrustManager;
  40import eu.siacs.conversations.services.MessageArchiveService;
  41import eu.siacs.conversations.services.NotificationService;
  42import eu.siacs.conversations.services.XmppConnectionService;
  43import eu.siacs.conversations.utils.AccountUtils;
  44import eu.siacs.conversations.utils.CryptoHelper;
  45import eu.siacs.conversations.utils.Patterns;
  46import eu.siacs.conversations.utils.PhoneHelper;
  47import eu.siacs.conversations.utils.Resolver;
  48import eu.siacs.conversations.utils.SSLSockets;
  49import eu.siacs.conversations.utils.SocksSocketFactory;
  50import eu.siacs.conversations.utils.XmlHelper;
  51import eu.siacs.conversations.xml.Element;
  52import eu.siacs.conversations.xml.LocalizedContent;
  53import eu.siacs.conversations.xml.Namespace;
  54import eu.siacs.conversations.xml.Tag;
  55import eu.siacs.conversations.xml.TagWriter;
  56import eu.siacs.conversations.xml.XmlReader;
  57import eu.siacs.conversations.xmpp.bind.Bind2;
  58import eu.siacs.conversations.xmpp.forms.Data;
  59import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  60import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  61import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  62import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  63import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  64import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  65import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  66import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  67import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  68import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  69import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
  70import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
  71import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
  72
  73import okhttp3.HttpUrl;
  74
  75import org.xmlpull.v1.XmlPullParserException;
  76
  77import java.io.ByteArrayInputStream;
  78import java.io.IOException;
  79import java.io.InputStream;
  80import java.net.ConnectException;
  81import java.net.IDN;
  82import java.net.InetAddress;
  83import java.net.InetSocketAddress;
  84import java.net.Socket;
  85import java.net.UnknownHostException;
  86import java.security.KeyManagementException;
  87import java.security.NoSuchAlgorithmException;
  88import java.security.Principal;
  89import java.security.PrivateKey;
  90import java.security.cert.X509Certificate;
  91import java.util.ArrayList;
  92import java.util.Arrays;
  93import java.util.Collection;
  94import java.util.Collections;
  95import java.util.HashMap;
  96import java.util.HashSet;
  97import java.util.Hashtable;
  98import java.util.Iterator;
  99import java.util.List;
 100import java.util.Map.Entry;
 101import java.util.Set;
 102import java.util.concurrent.CountDownLatch;
 103import java.util.concurrent.TimeUnit;
 104import java.util.concurrent.atomic.AtomicBoolean;
 105import java.util.concurrent.atomic.AtomicInteger;
 106import java.util.regex.Matcher;
 107
 108import javax.net.ssl.KeyManager;
 109import javax.net.ssl.SSLContext;
 110import javax.net.ssl.SSLPeerUnverifiedException;
 111import javax.net.ssl.SSLSocket;
 112import javax.net.ssl.SSLSocketFactory;
 113import javax.net.ssl.X509KeyManager;
 114import javax.net.ssl.X509TrustManager;
 115
 116public class XmppConnection implements Runnable {
 117
 118    private static final int PACKET_IQ = 0;
 119    private static final int PACKET_MESSAGE = 1;
 120    private static final int PACKET_PRESENCE = 2;
 121    public final OnIqPacketReceived registrationResponseListener =
 122            (account, packet) -> {
 123                if (packet.getType() == IqPacket.TYPE.RESULT) {
 124                    account.setOption(Account.OPTION_REGISTER, false);
 125                    Log.d(
 126                            Config.LOGTAG,
 127                            account.getJid().asBareJid()
 128                                    + ": successfully registered new account on server");
 129                    throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 130                } else {
 131                    final List<String> PASSWORD_TOO_WEAK_MSGS =
 132                            Arrays.asList(
 133                                    "The password is too weak", "Please use a longer password.");
 134                    Element error = packet.findChild("error");
 135                    Account.State state = Account.State.REGISTRATION_FAILED;
 136                    if (error != null) {
 137                        if (error.hasChild("conflict")) {
 138                            state = Account.State.REGISTRATION_CONFLICT;
 139                        } else if (error.hasChild("resource-constraint")
 140                                && "wait".equals(error.getAttribute("type"))) {
 141                            state = Account.State.REGISTRATION_PLEASE_WAIT;
 142                        } else if (error.hasChild("not-acceptable")
 143                                && PASSWORD_TOO_WEAK_MSGS.contains(
 144                                        error.findChildContent("text"))) {
 145                            state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 146                        }
 147                    }
 148                    throw new StateChangingError(state);
 149                }
 150            };
 151    protected final Account account;
 152    private final Features features = new Features(this);
 153    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 154    private final HashMap<String, Jid> commands = new HashMap<>();
 155    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 156    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks =
 157            new Hashtable<>();
 158    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners =
 159            new HashSet<>();
 160    private final XmppConnectionService mXmppConnectionService;
 161    private Socket socket;
 162    private XmlReader tagReader;
 163    private TagWriter tagWriter = new TagWriter();
 164    private boolean shouldAuthenticate = true;
 165    private boolean inSmacksSession = false;
 166    private boolean quickStartInProgress = false;
 167    private boolean isBound = false;
 168    private Element streamFeatures;
 169    private Element boundStreamFeatures;
 170    private StreamId streamId = null;
 171    private int stanzasReceived = 0;
 172    private int stanzasSent = 0;
 173    private int stanzasSentBeforeAuthentication;
 174    private long lastPacketReceived = 0;
 175    private long lastPingSent = 0;
 176    private long lastConnect = 0;
 177    private long lastSessionStarted = 0;
 178    private long lastDiscoStarted = 0;
 179    private boolean isMamPreferenceAlways = false;
 180    private final AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 181    private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 182    private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 183    private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 184    private boolean mInteractive = false;
 185    private int attempt = 0;
 186    private OnPresencePacketReceived presenceListener = null;
 187    private OnJinglePacketReceived jingleListener = null;
 188    private OnIqPacketReceived unregisteredIqListener = null;
 189    private OnMessagePacketReceived messageListener = null;
 190    private OnStatusChanged statusListener = null;
 191    private OnBindListener bindListener = null;
 192    private OnMessageAcknowledged acknowledgedListener = null;
 193    private LoginInfo loginInfo;
 194    private HashedToken.Mechanism hashTokenRequest;
 195    private HttpUrl redirectionUrl = null;
 196    private String verifiedHostname = null;
 197    private Resolver.Result currentResolverResult;
 198    private Resolver.Result seeOtherHostResolverResult;
 199    private volatile Thread mThread;
 200    private CountDownLatch mStreamCountDownLatch;
 201
 202    public XmppConnection(final Account account, final XmppConnectionService service) {
 203        this.account = account;
 204        this.mXmppConnectionService = service;
 205    }
 206
 207    private static void fixResource(Context context, Account account) {
 208        String resource = account.getResource();
 209        int fixedPartLength =
 210                context.getString(R.string.app_name).length() + 1; // include the trailing dot
 211        int randomPartLength = 4; // 3 bytes
 212        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 213            if (validBase64(
 214                    resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 215                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 216            }
 217        }
 218    }
 219
 220    private static boolean validBase64(String input) {
 221        try {
 222            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 223        } catch (Throwable throwable) {
 224            return false;
 225        }
 226    }
 227
 228    private void changeStatus(final Account.State nextStatus) {
 229        synchronized (this) {
 230            if (Thread.currentThread().isInterrupted()) {
 231                Log.d(
 232                        Config.LOGTAG,
 233                        account.getJid().asBareJid()
 234                                + ": not changing status to "
 235                                + nextStatus
 236                                + " because thread was interrupted");
 237                return;
 238            }
 239            if (account.getStatus() != nextStatus) {
 240                if (nextStatus == Account.State.OFFLINE
 241                        && account.getStatus() != Account.State.CONNECTING
 242                        && account.getStatus() != Account.State.ONLINE
 243                        && account.getStatus() != Account.State.DISABLED
 244                        && account.getStatus() != Account.State.LOGGED_OUT) {
 245                    return;
 246                }
 247                if (nextStatus == Account.State.ONLINE) {
 248                    this.attempt = 0;
 249                }
 250                account.setStatus(nextStatus);
 251            } else {
 252                return;
 253            }
 254        }
 255        if (statusListener != null) {
 256            statusListener.onStatusChanged(account);
 257        }
 258    }
 259
 260    public Jid getJidForCommand(final String node) {
 261        synchronized (this.commands) {
 262            return this.commands.get(node);
 263        }
 264    }
 265
 266    public void prepareNewConnection() {
 267        this.lastConnect = SystemClock.elapsedRealtime();
 268        this.lastPingSent = SystemClock.elapsedRealtime();
 269        this.lastDiscoStarted = Long.MAX_VALUE;
 270        this.mWaitingForSmCatchup.set(false);
 271        this.changeStatus(Account.State.CONNECTING);
 272    }
 273
 274    public boolean isWaitingForSmCatchup() {
 275        return mWaitingForSmCatchup.get();
 276    }
 277
 278    public void incrementSmCatchupMessageCounter() {
 279        this.mSmCatchupMessageCounter.incrementAndGet();
 280    }
 281
 282    protected void connect() {
 283        if (mXmppConnectionService.areMessagesInitialized()) {
 284            mXmppConnectionService.resetSendingToWaiting(account);
 285        }
 286        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 287        this.loginInfo = null;
 288        this.features.encryptionEnabled = false;
 289        this.inSmacksSession = false;
 290        this.quickStartInProgress = false;
 291        this.isBound = false;
 292        this.attempt++;
 293        this.verifiedHostname =
 294                null; // will be set if user entered hostname is being used or hostname was verified
 295        // with dnssec
 296        try {
 297            Socket localSocket;
 298            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 299            this.changeStatus(Account.State.CONNECTING);
 300            final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 301            final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 302            if (useTor) {
 303                String destination;
 304                if (account.getHostname().isEmpty() || account.isOnion()) {
 305                    destination = account.getServer();
 306                } else {
 307                    destination = account.getHostname();
 308                    this.verifiedHostname = destination;
 309                }
 310
 311                final int port = account.getPort();
 312                final boolean directTls = Resolver.useDirectTls(port);
 313
 314                Log.d(
 315                        Config.LOGTAG,
 316                        account.getJid().asBareJid()
 317                                + ": connect to "
 318                                + destination
 319                                + " via Tor. directTls="
 320                                + directTls);
 321                localSocket = SocksSocketFactory.createSocketOverTor(destination, port);
 322
 323                if (directTls) {
 324                    localSocket = upgradeSocketToTls(localSocket);
 325                    features.encryptionEnabled = true;
 326                }
 327
 328                try {
 329                    startXmpp(localSocket);
 330                } catch (final InterruptedException e) {
 331                    Log.d(
 332                            Config.LOGTAG,
 333                            account.getJid().asBareJid()
 334                                    + ": thread was interrupted before beginning stream");
 335                    return;
 336                } catch (final Exception e) {
 337                    throw new IOException("Could not start stream", e);
 338                }
 339            } else {
 340                final String domain = account.getServer();
 341                final List<Resolver.Result> results;
 342                final boolean hardcoded = extended && !account.getHostname().isEmpty();
 343                if (hardcoded) {
 344                    results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
 345                } else {
 346                    results = Resolver.resolve(domain);
 347                }
 348                if (Thread.currentThread().isInterrupted()) {
 349                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 350                    return;
 351                }
 352                if (results.size() == 0) {
 353                    Log.e(
 354                            Config.LOGTAG,
 355                            account.getJid().asBareJid() + ": Resolver results were empty");
 356                    return;
 357                }
 358                final Resolver.Result storedBackupResult;
 359                if (hardcoded) {
 360                    storedBackupResult = null;
 361                } else {
 362                    storedBackupResult =
 363                            mXmppConnectionService.databaseBackend.findResolverResult(domain);
 364                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 365                        results.add(storedBackupResult);
 366                        Log.d(
 367                                Config.LOGTAG,
 368                                account.getJid().asBareJid()
 369                                        + ": loaded backup resolver result from db: "
 370                                        + storedBackupResult);
 371                    }
 372                }
 373                final StreamId streamId = this.streamId;
 374                final Resolver.Result resumeLocation = streamId == null ? null : streamId.location;
 375                if (resumeLocation != null) {
 376                    Log.d(
 377                            Config.LOGTAG,
 378                            account.getJid().asBareJid()
 379                                    + ": injected resume location on position 0");
 380                    results.add(0, resumeLocation);
 381                }
 382                final Resolver.Result seeOtherHost = this.seeOtherHostResolverResult;
 383                if (seeOtherHost != null) {
 384                    Log.d(
 385                            Config.LOGTAG,
 386                            account.getJid().asBareJid()
 387                                    + ": injected see-other-host on position 0");
 388                    results.add(0, seeOtherHost);
 389                }
 390                for (final Iterator<Resolver.Result> iterator = results.iterator();
 391                        iterator.hasNext(); ) {
 392                    final Resolver.Result result = iterator.next();
 393                    if (Thread.currentThread().isInterrupted()) {
 394                        Log.d(
 395                                Config.LOGTAG,
 396                                account.getJid().asBareJid() + ": Thread was interrupted");
 397                        return;
 398                    }
 399                    try {
 400                        // if tls is true, encryption is implied and must not be started
 401                        features.encryptionEnabled = result.isDirectTls();
 402                        verifiedHostname =
 403                                result.isAuthenticated() ? result.getHostname().toString() : null;
 404                        final InetSocketAddress addr;
 405                        if (result.getIp() != null) {
 406                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 407                            Log.d(
 408                                    Config.LOGTAG,
 409                                    account.getJid().asBareJid().toString()
 410                                            + ": using values from resolver "
 411                                            + (result.getHostname() == null
 412                                                    ? ""
 413                                                    : result.getHostname().toString() + "/")
 414                                            + result.getIp().getHostAddress()
 415                                            + ":"
 416                                            + result.getPort()
 417                                            + " tls: "
 418                                            + features.encryptionEnabled);
 419                        } else {
 420                            addr =
 421                                    new InetSocketAddress(
 422                                            IDN.toASCII(result.getHostname().toString()),
 423                                            result.getPort());
 424                            Log.d(
 425                                    Config.LOGTAG,
 426                                    account.getJid().asBareJid().toString()
 427                                            + ": using values from resolver "
 428                                            + result.getHostname().toString()
 429                                            + ":"
 430                                            + result.getPort()
 431                                            + " tls: "
 432                                            + features.encryptionEnabled);
 433                        }
 434
 435                        localSocket = new Socket();
 436                        localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 437
 438                        if (features.encryptionEnabled) {
 439                            localSocket = upgradeSocketToTls(localSocket);
 440                        }
 441
 442                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 443                        if (startXmpp(localSocket)) {
 444                            localSocket.setSoTimeout(
 445                                    0); // reset to 0; once the connection is established we don’t
 446                            // want this
 447                            if (!hardcoded && !result.equals(storedBackupResult)) {
 448                                mXmppConnectionService.databaseBackend.saveResolverResult(
 449                                        domain, result);
 450                            }
 451                            this.currentResolverResult = result;
 452                            this.seeOtherHostResolverResult = null;
 453                            break; // successfully connected to server that speaks xmpp
 454                        } else {
 455                            FileBackend.close(localSocket);
 456                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 457                        }
 458                    } catch (final StateChangingException e) {
 459                        if (!iterator.hasNext()) {
 460                            throw e;
 461                        }
 462                    } catch (InterruptedException e) {
 463                        Log.d(
 464                                Config.LOGTAG,
 465                                account.getJid().asBareJid()
 466                                        + ": thread was interrupted before beginning stream");
 467                        return;
 468                    } catch (final Throwable e) {
 469                        Log.d(
 470                                Config.LOGTAG,
 471                                account.getJid().asBareJid().toString()
 472                                        + ": "
 473                                        + e.getMessage()
 474                                        + "("
 475                                        + e.getClass().getName()
 476                                        + ")");
 477                        if (!iterator.hasNext()) {
 478                            throw new UnknownHostException();
 479                        }
 480                    }
 481                }
 482            }
 483            processStream();
 484        } catch (final SecurityException e) {
 485            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 486        } catch (final StateChangingException e) {
 487            this.changeStatus(e.state);
 488        } catch (final UnknownHostException
 489                | ConnectException
 490                | SocksSocketFactory.HostNotFoundException e) {
 491            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 492        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 493            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 494        } catch (final IOException | XmlPullParserException e) {
 495            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 496            this.changeStatus(Account.State.OFFLINE);
 497            this.attempt = Math.max(0, this.attempt - 1);
 498        } finally {
 499            if (!Thread.currentThread().isInterrupted()) {
 500                forceCloseSocket();
 501            } else {
 502                Log.d(
 503                        Config.LOGTAG,
 504                        account.getJid().asBareJid()
 505                                + ": not force closing socket because thread was interrupted");
 506            }
 507        }
 508    }
 509
 510    /**
 511     * Starts xmpp protocol, call after connecting to socket
 512     *
 513     * @return true if server returns with valid xmpp, false otherwise
 514     */
 515    private boolean startXmpp(final Socket socket) throws Exception {
 516        if (Thread.currentThread().isInterrupted()) {
 517            throw new InterruptedException();
 518        }
 519        this.socket = socket;
 520        tagReader = new XmlReader();
 521        if (tagWriter != null) {
 522            tagWriter.forceClose();
 523        }
 524        tagWriter = new TagWriter();
 525        tagWriter.setOutputStream(socket.getOutputStream());
 526        tagReader.setInputStream(socket.getInputStream());
 527        tagWriter.beginDocument();
 528        final boolean quickStart;
 529        if (socket instanceof SSLSocket) {
 530            final SSLSocket sslSocket = (SSLSocket) socket;
 531            SSLSockets.log(account, sslSocket);
 532            quickStart = establishStream(SSLSockets.version(sslSocket));
 533        } else {
 534            quickStart = establishStream(SSLSockets.Version.NONE);
 535        }
 536        final Tag tag = tagReader.readTag();
 537        if (Thread.currentThread().isInterrupted()) {
 538            throw new InterruptedException();
 539        }
 540        final boolean success = tag != null && tag.isStart("stream", Namespace.STREAMS);
 541        if (success && quickStart) {
 542            this.quickStartInProgress = true;
 543        }
 544        return success;
 545    }
 546
 547    private SSLSocketFactory getSSLSocketFactory()
 548            throws NoSuchAlgorithmException, KeyManagementException {
 549        final SSLContext sc = SSLSockets.getSSLContext();
 550        final MemorizingTrustManager trustManager =
 551                this.mXmppConnectionService.getMemorizingTrustManager();
 552        final KeyManager[] keyManager;
 553        if (account.getPrivateKeyAlias() != null) {
 554            keyManager = new KeyManager[] {new MyKeyManager()};
 555        } else {
 556            keyManager = null;
 557        }
 558        final String domain = account.getServer();
 559        sc.init(
 560                keyManager,
 561                new X509TrustManager[] {
 562                    mInteractive
 563                            ? trustManager.getInteractive(domain)
 564                            : trustManager.getNonInteractive(domain)
 565                },
 566                SECURE_RANDOM);
 567        return sc.getSocketFactory();
 568    }
 569
 570    @Override
 571    public void run() {
 572        synchronized (this) {
 573            this.mThread = Thread.currentThread();
 574            if (this.mThread.isInterrupted()) {
 575                Log.d(
 576                        Config.LOGTAG,
 577                        account.getJid().asBareJid()
 578                                + ": aborting connect because thread was interrupted");
 579                return;
 580            }
 581            forceCloseSocket();
 582        }
 583        connect();
 584    }
 585
 586    private void processStream() throws XmlPullParserException, IOException {
 587        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 588        this.mStreamCountDownLatch = streamCountDownLatch;
 589        Tag nextTag = tagReader.readTag();
 590        while (nextTag != null && !nextTag.isEnd("stream")) {
 591            if (nextTag.isStart("error")) {
 592                processStreamError(nextTag);
 593            } else if (nextTag.isStart("features", Namespace.STREAMS)) {
 594                processStreamFeatures(nextTag);
 595            } else if (nextTag.isStart("proceed", Namespace.TLS)) {
 596                switchOverToTls();
 597            } else if (nextTag.isStart("failure", Namespace.TLS)) {
 598                throw new StateChangingException(Account.State.TLS_ERROR);
 599            } else if (account.isOptionSet(Account.OPTION_REGISTER)
 600                    && nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
 601                processIq(nextTag);
 602            } else if (!isSecure() || this.loginInfo == null) {
 603                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 604            } else if (nextTag.isStart("success")) {
 605                final Element success = tagReader.readElement(nextTag);
 606                if (processSuccess(success)) {
 607                    break;
 608                }
 609            } else if (nextTag.isStart("failure")) {
 610                final Element failure = tagReader.readElement(nextTag);
 611                processFailure(failure);
 612            } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
 613                // two step sasl2 - we don’t support this yet
 614                throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
 615            } else if (nextTag.isStart("challenge")) {
 616                final Element challenge = tagReader.readElement(nextTag);
 617                processChallenge(challenge);
 618            } else if (this.streamId != null
 619                    && nextTag.isStart("resumed", Namespace.STREAM_MANAGEMENT)) {
 620                final Element resumed = tagReader.readElement(nextTag);
 621                processResumed(resumed);
 622            } else if (nextTag.isStart("failed", Namespace.STREAM_MANAGEMENT)) {
 623                final Element failed = tagReader.readElement(nextTag);
 624                processFailed(failed, true);
 625            } else if (nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
 626                processIq(nextTag);
 627            } else if (!isBound) {
 628                Log.d(
 629                        Config.LOGTAG,
 630                        account.getJid().asBareJid()
 631                                + ": server sent unexpected"
 632                                + nextTag.identifier());
 633                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 634            } else if (nextTag.isStart("message", Namespace.JABBER_CLIENT)) {
 635                processMessage(nextTag);
 636            } else if (nextTag.isStart("presence", Namespace.JABBER_CLIENT)) {
 637                processPresence(nextTag);
 638            } else if (nextTag.isStart("enabled", Namespace.STREAM_MANAGEMENT)) {
 639                final Element enabled = tagReader.readElement(nextTag);
 640                processEnabled(enabled);
 641            } else if (nextTag.isStart("r", Namespace.STREAM_MANAGEMENT)) {
 642                tagReader.readElement(nextTag);
 643                if (Config.EXTENDED_SM_LOGGING) {
 644                    Log.d(
 645                            Config.LOGTAG,
 646                            account.getJid().asBareJid()
 647                                    + ": acknowledging stanza #"
 648                                    + this.stanzasReceived);
 649                }
 650                final AckPacket ack = new AckPacket(this.stanzasReceived);
 651                tagWriter.writeStanzaAsync(ack);
 652            } else if (nextTag.isStart("a", Namespace.STREAM_MANAGEMENT)) {
 653                boolean accountUiNeedsRefresh = false;
 654                synchronized (NotificationService.CATCHUP_LOCK) {
 655                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 656                        final int messageCount = mSmCatchupMessageCounter.get();
 657                        final int pendingIQs = packetCallbacks.size();
 658                        Log.d(
 659                                Config.LOGTAG,
 660                                account.getJid().asBareJid()
 661                                        + ": SM catchup complete (messages="
 662                                        + messageCount
 663                                        + ", pending IQs="
 664                                        + pendingIQs
 665                                        + ")");
 666                        accountUiNeedsRefresh = true;
 667                        if (messageCount > 0) {
 668                            mXmppConnectionService
 669                                    .getNotificationService()
 670                                    .finishBacklog(true, account);
 671                        }
 672                    }
 673                }
 674                if (accountUiNeedsRefresh) {
 675                    mXmppConnectionService.updateAccountUi();
 676                }
 677                final Element ack = tagReader.readElement(nextTag);
 678                lastPacketReceived = SystemClock.elapsedRealtime();
 679                final boolean acknowledgedMessages;
 680                synchronized (this.mStanzaQueue) {
 681                    final Optional<Integer> serverSequence = ack.getOptionalIntAttribute("h");
 682                    if (serverSequence.isPresent()) {
 683                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence.get());
 684                    } else {
 685                        acknowledgedMessages = false;
 686                        Log.d(
 687                                Config.LOGTAG,
 688                                account.getJid().asBareJid()
 689                                        + ": server send ack without sequence number");
 690                    }
 691                }
 692                if (acknowledgedMessages) {
 693                    mXmppConnectionService.updateConversationUi();
 694                }
 695            } else {
 696                Log.e(
 697                        Config.LOGTAG,
 698                        account.getJid().asBareJid()
 699                                + ": Encountered unknown stream element"
 700                                + nextTag.identifier());
 701                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 702            }
 703            nextTag = tagReader.readTag();
 704        }
 705        if (nextTag != null && nextTag.isEnd("stream")) {
 706            streamCountDownLatch.countDown();
 707        }
 708    }
 709
 710    private void processChallenge(final Element challenge) throws IOException {
 711        final SaslMechanism.Version version;
 712        try {
 713            version = SaslMechanism.Version.of(challenge);
 714        } catch (final IllegalArgumentException e) {
 715            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 716        }
 717        final Element response;
 718        if (version == SaslMechanism.Version.SASL) {
 719            response = new Element("response", Namespace.SASL);
 720        } else if (version == SaslMechanism.Version.SASL_2) {
 721            response = new Element("response", Namespace.SASL_2);
 722        } else {
 723            throw new AssertionError("Missing implementation for " + version);
 724        }
 725        try {
 726            response.setContent(
 727                    this.loginInfo.saslMechanism.getResponse(
 728                            challenge.getContent(), sslSocketOrNull(socket)));
 729        } catch (final SaslMechanism.AuthenticationException e) {
 730            // TODO: Send auth abort tag.
 731            Log.e(Config.LOGTAG, e.toString());
 732            throw new StateChangingException(Account.State.UNAUTHORIZED);
 733        }
 734        tagWriter.writeElement(response);
 735    }
 736
 737    private boolean processSuccess(final Element success)
 738            throws IOException, XmlPullParserException {
 739        final SaslMechanism.Version version;
 740        try {
 741            version = SaslMechanism.Version.of(success);
 742        } catch (final IllegalArgumentException e) {
 743            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 744        }
 745        final LoginInfo currentLoginInfo = this.loginInfo;
 746        final SaslMechanism currentSaslMechanism = LoginInfo.mechanism(currentLoginInfo);
 747        if (currentLoginInfo == null || currentSaslMechanism == null) {
 748            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 749        }
 750        final String challenge;
 751        if (version == SaslMechanism.Version.SASL) {
 752            challenge = success.getContent();
 753        } else if (version == SaslMechanism.Version.SASL_2) {
 754            challenge = success.findChildContent("additional-data");
 755        } else {
 756            throw new AssertionError("Missing implementation for " + version);
 757        }
 758        try {
 759            currentSaslMechanism.getResponse(challenge, sslSocketOrNull(socket));
 760        } catch (final SaslMechanism.AuthenticationException e) {
 761            Log.e(Config.LOGTAG, String.valueOf(e));
 762            throw new StateChangingException(Account.State.UNAUTHORIZED);
 763        }
 764        Log.d(
 765                Config.LOGTAG,
 766                account.getJid().asBareJid().toString() + ": logged in (using " + version + ")");
 767        if (SaslMechanism.pin(currentSaslMechanism)) {
 768            account.setPinnedMechanism(currentSaslMechanism);
 769        }
 770        if (version == SaslMechanism.Version.SASL_2) {
 771            final String authorizationIdentifier =
 772                    success.findChildContent("authorization-identifier");
 773            final Jid authorizationJid;
 774            try {
 775                authorizationJid =
 776                        Strings.isNullOrEmpty(authorizationIdentifier)
 777                                ? null
 778                                : Jid.ofEscaped(authorizationIdentifier);
 779            } catch (final IllegalArgumentException e) {
 780                Log.d(
 781                        Config.LOGTAG,
 782                        account.getJid().asBareJid()
 783                                + ": SASL 2.0 authorization identifier was not a valid jid");
 784                throw new StateChangingException(Account.State.BIND_FAILURE);
 785            }
 786            if (authorizationJid == null) {
 787                throw new StateChangingException(Account.State.BIND_FAILURE);
 788            }
 789            Log.d(
 790                    Config.LOGTAG,
 791                    account.getJid().asBareJid()
 792                            + ": SASL 2.0 authorization identifier was "
 793                            + authorizationJid);
 794            if (!account.getJid().getDomain().equals(authorizationJid.getDomain())) {
 795                Log.d(
 796                        Config.LOGTAG,
 797                        account.getJid().asBareJid()
 798                                + ": server tried to re-assign domain to "
 799                                + authorizationJid.getDomain());
 800                throw new StateChangingError(Account.State.BIND_FAILURE);
 801            }
 802            if (authorizationJid.isFullJid() && account.setJid(authorizationJid)) {
 803                Log.d(
 804                        Config.LOGTAG,
 805                        account.getJid().asBareJid()
 806                                + ": jid changed during SASL 2.0. updating database");
 807            }
 808            final Element bound = success.findChild("bound", Namespace.BIND2);
 809            final Element resumed = success.findChild("resumed", Namespace.STREAM_MANAGEMENT);
 810            final Element failed = success.findChild("failed", Namespace.STREAM_MANAGEMENT);
 811            final Element tokenWrapper = success.findChild("token", Namespace.FAST);
 812            final String token = tokenWrapper == null ? null : tokenWrapper.getAttribute("token");
 813            if (bound != null && resumed != null) {
 814                Log.d(
 815                        Config.LOGTAG,
 816                        account.getJid().asBareJid()
 817                                + ": server sent bound and resumed in SASL2 success");
 818                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 819            }
 820            if (resumed != null && streamId != null) {
 821                if (this.boundStreamFeatures != null) {
 822                    this.streamFeatures = this.boundStreamFeatures;
 823                    Log.d(
 824                            Config.LOGTAG,
 825                            "putting previous stream features back in place: "
 826                                    + XmlHelper.printElementNames(this.boundStreamFeatures));
 827                }
 828                processResumed(resumed);
 829            } else if (failed != null) {
 830                processFailed(failed, false); // wait for new stream features
 831            }
 832            if (bound != null) {
 833                clearIqCallbacks();
 834                this.isBound = true;
 835                processNopStreamFeatures();
 836                this.boundStreamFeatures = this.streamFeatures;
 837                final Element streamManagementEnabled =
 838                        bound.findChild("enabled", Namespace.STREAM_MANAGEMENT);
 839                final Element carbonsEnabled = bound.findChild("enabled", Namespace.CARBONS);
 840                final boolean waitForDisco;
 841                if (streamManagementEnabled != null) {
 842                    resetOutboundStanzaQueue();
 843                    processEnabled(streamManagementEnabled);
 844                    waitForDisco = true;
 845                } else {
 846                    // if we did not enable stream management in bind do it now
 847                    waitForDisco = enableStreamManagement();
 848                }
 849                final boolean negotiatedCarbons;
 850                if (carbonsEnabled != null) {
 851                    negotiatedCarbons = true;
 852                    Log.d(
 853                            Config.LOGTAG,
 854                            account.getJid().asBareJid()
 855                                    + ": successfully enabled carbons (via Bind 2.0)");
 856                    features.carbonsEnabled = true;
 857                } else if (loginInfo.inlineBindFeatures.contains(Namespace.CARBONS)) {
 858                    negotiatedCarbons = true;
 859                    Log.d(
 860                            Config.LOGTAG,
 861                            account.getJid().asBareJid()
 862                                    + ": successfully enabled carbons (via Bind 2.0/implicit)");
 863                    features.carbonsEnabled = true;
 864                } else {
 865                    negotiatedCarbons = false;
 866                }
 867                sendPostBindInitialization(waitForDisco, negotiatedCarbons);
 868            }
 869            final HashedToken.Mechanism tokenMechanism;
 870            if (SaslMechanism.hashedToken(currentSaslMechanism)) {
 871                tokenMechanism = ((HashedToken) currentSaslMechanism).getTokenMechanism();
 872            } else if (this.hashTokenRequest != null) {
 873                tokenMechanism = this.hashTokenRequest;
 874            } else {
 875                tokenMechanism = null;
 876            }
 877            if (tokenMechanism != null && !Strings.isNullOrEmpty(token)) {
 878                if (ChannelBinding.priority(tokenMechanism.channelBinding)
 879                        >= ChannelBindingMechanism.getPriority(currentSaslMechanism)) {
 880                    this.account.setFastToken(tokenMechanism, token);
 881                    Log.d(
 882                            Config.LOGTAG,
 883                            account.getJid().asBareJid()
 884                                    + ": storing hashed token "
 885                                    + tokenMechanism);
 886                } else {
 887                    Log.d(
 888                            Config.LOGTAG,
 889                            account.getJid().asBareJid()
 890                                    + ": not accepting hashed token "
 891                                    + tokenMechanism.name()
 892                                    + " for log in mechanism "
 893                                    + currentSaslMechanism.getMechanism());
 894                    this.account.resetFastToken();
 895                }
 896            } else if (this.hashTokenRequest != null) {
 897                Log.w(
 898                        Config.LOGTAG,
 899                        account.getJid().asBareJid()
 900                                + ": no response to our hashed token request "
 901                                + this.hashTokenRequest);
 902            }
 903        }
 904        mXmppConnectionService.databaseBackend.updateAccount(account);
 905        this.quickStartInProgress = false;
 906        if (version == SaslMechanism.Version.SASL) {
 907            tagReader.reset();
 908            sendStartStream(false, true);
 909            final Tag tag = tagReader.readTag();
 910            if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
 911                processStream();
 912                return true;
 913            } else {
 914                throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 915            }
 916        } else {
 917            return false;
 918        }
 919    }
 920
 921    private void resetOutboundStanzaQueue() {
 922        synchronized (this.mStanzaQueue) {
 923            final List<AbstractAcknowledgeableStanza> intermediateStanzas = new ArrayList<>();
 924            if (Config.EXTENDED_SM_LOGGING) {
 925                Log.d(
 926                        Config.LOGTAG,
 927                        account.getJid().asBareJid()
 928                                + ": stanzas sent before auth: "
 929                                + this.stanzasSentBeforeAuthentication);
 930            }
 931            for (int i = this.stanzasSentBeforeAuthentication + 1; i <= this.stanzasSent; ++i) {
 932                final AbstractAcknowledgeableStanza stanza = this.mStanzaQueue.get(i);
 933                if (stanza != null) {
 934                    intermediateStanzas.add(stanza);
 935                }
 936            }
 937            this.mStanzaQueue.clear();
 938            for (int i = 0; i < intermediateStanzas.size(); ++i) {
 939                this.mStanzaQueue.put(i, intermediateStanzas.get(i));
 940            }
 941            this.stanzasSent = intermediateStanzas.size();
 942            if (Config.EXTENDED_SM_LOGGING) {
 943                Log.d(
 944                        Config.LOGTAG,
 945                        account.getJid().asBareJid()
 946                                + ": resetting outbound stanza queue to "
 947                                + this.stanzasSent);
 948            }
 949        }
 950    }
 951
 952    private void processNopStreamFeatures() throws IOException {
 953        final Tag tag = tagReader.readTag();
 954        if (tag != null && tag.isStart("features", Namespace.STREAMS)) {
 955            this.streamFeatures = tagReader.readElement(tag);
 956            Log.d(
 957                    Config.LOGTAG,
 958                    account.getJid().asBareJid()
 959                            + ": processed NOP stream features after success: "
 960                            + XmlHelper.printElementNames(this.streamFeatures));
 961        } else {
 962            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received " + tag);
 963            Log.d(
 964                    Config.LOGTAG,
 965                    account.getJid().asBareJid()
 966                            + ": server did not send stream features after SASL2 success");
 967            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 968        }
 969    }
 970
 971    private void processFailure(final Element failure) throws IOException {
 972        final SaslMechanism.Version version;
 973        try {
 974            version = SaslMechanism.Version.of(failure);
 975        } catch (final IllegalArgumentException e) {
 976            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 977        }
 978        Log.d(Config.LOGTAG, failure.toString());
 979        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
 980        if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
 981            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resetting token");
 982            account.resetFastToken();
 983            mXmppConnectionService.databaseBackend.updateAccount(account);
 984        }
 985        if (failure.hasChild("temporary-auth-failure")) {
 986            throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
 987        } else if (failure.hasChild("account-disabled")) {
 988            final String text = failure.findChildContent("text");
 989            if (Strings.isNullOrEmpty(text)) {
 990                throw new StateChangingException(Account.State.UNAUTHORIZED);
 991            }
 992            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 993            if (matcher.find()) {
 994                final HttpUrl url;
 995                try {
 996                    url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
 997                } catch (final IllegalArgumentException e) {
 998                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 999                }
1000                if (url.isHttps()) {
1001                    this.redirectionUrl = url;
1002                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
1003                }
1004            }
1005        }
1006        if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1007            Log.d(
1008                    Config.LOGTAG,
1009                    account.getJid().asBareJid()
1010                            + ": fast authentication failed. falling back to regular authentication");
1011            authenticate();
1012        } else {
1013            throw new StateChangingException(Account.State.UNAUTHORIZED);
1014        }
1015    }
1016
1017    private static SSLSocket sslSocketOrNull(final Socket socket) {
1018        if (socket instanceof SSLSocket) {
1019            return (SSLSocket) socket;
1020        } else {
1021            return null;
1022        }
1023    }
1024
1025    private void processEnabled(final Element enabled) {
1026        final String id;
1027        if (enabled.getAttributeAsBoolean("resume")) {
1028            id = enabled.getAttribute("id");
1029        } else {
1030            id = null;
1031        }
1032        final String locationAttribute = enabled.getAttribute("location");
1033        final Resolver.Result currentResolverResult = this.currentResolverResult;
1034        final Resolver.Result location;
1035        if (Strings.isNullOrEmpty(locationAttribute) || currentResolverResult == null) {
1036            location = null;
1037        } else {
1038            location = currentResolverResult.seeOtherHost(locationAttribute);
1039        }
1040        final StreamId streamId = id == null ? null : new StreamId(id, location);
1041        if (streamId == null) {
1042            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream management enabled");
1043        } else {
1044            Log.d(
1045                    Config.LOGTAG,
1046                    account.getJid().asBareJid()
1047                            + ": stream management enabled. resume at: "
1048                            + streamId.location);
1049        }
1050        this.streamId = streamId;
1051        this.stanzasReceived = 0;
1052        this.inSmacksSession = true;
1053        final RequestPacket r = new RequestPacket();
1054        tagWriter.writeStanzaAsync(r);
1055    }
1056
1057    private void processResumed(final Element resumed) throws StateChangingException {
1058        this.inSmacksSession = true;
1059        this.isBound = true;
1060        this.tagWriter.writeStanzaAsync(new RequestPacket());
1061        lastPacketReceived = SystemClock.elapsedRealtime();
1062        final Optional<Integer> h = resumed.getOptionalIntAttribute("h");
1063        final int serverCount;
1064        if (h.isPresent()) {
1065            serverCount = h.get();
1066        } else {
1067            resetStreamId();
1068            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1069        }
1070        final ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
1071        final boolean acknowledgedMessages;
1072        synchronized (this.mStanzaQueue) {
1073            if (serverCount < stanzasSent) {
1074                Log.d(
1075                        Config.LOGTAG,
1076                        account.getJid().asBareJid() + ": session resumed with lost packages");
1077                stanzasSent = serverCount;
1078            } else {
1079                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": session resumed");
1080            }
1081            acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
1082            for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
1083                failedStanzas.add(mStanzaQueue.valueAt(i));
1084            }
1085            mStanzaQueue.clear();
1086        }
1087        if (acknowledgedMessages) {
1088            mXmppConnectionService.updateConversationUi();
1089        }
1090        Log.d(
1091                Config.LOGTAG,
1092                account.getJid().asBareJid() + ": resending " + failedStanzas.size() + " stanzas");
1093        for (final AbstractAcknowledgeableStanza packet : failedStanzas) {
1094            if (packet instanceof MessagePacket message) {
1095                mXmppConnectionService.markMessage(
1096                        account,
1097                        message.getTo().asBareJid(),
1098                        message.getId(),
1099                        Message.STATUS_UNSEND);
1100            }
1101            sendPacket(packet);
1102        }
1103        changeStatusToOnline();
1104    }
1105
1106    private void changeStatusToOnline() {
1107        Log.d(
1108                Config.LOGTAG,
1109                account.getJid().asBareJid() + ": online with resource " + account.getResource());
1110        changeStatus(Account.State.ONLINE);
1111    }
1112
1113    private void processFailed(final Element failed, final boolean sendBindRequest) {
1114        final Optional<Integer> serverCount = failed.getOptionalIntAttribute("h");
1115        if (serverCount.isPresent()) {
1116            Log.d(
1117                    Config.LOGTAG,
1118                    account.getJid().asBareJid()
1119                            + ": resumption failed but server acknowledged stanza #"
1120                            + serverCount.get());
1121            final boolean acknowledgedMessages;
1122            synchronized (this.mStanzaQueue) {
1123                acknowledgedMessages = acknowledgeStanzaUpTo(serverCount.get());
1124            }
1125            if (acknowledgedMessages) {
1126                mXmppConnectionService.updateConversationUi();
1127            }
1128        } else {
1129            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
1130        }
1131        resetStreamId();
1132        if (sendBindRequest) {
1133            sendBindRequest();
1134        }
1135    }
1136
1137    private boolean acknowledgeStanzaUpTo(final int serverCount) {
1138        if (serverCount > stanzasSent) {
1139            Log.e(
1140                    Config.LOGTAG,
1141                    "server acknowledged more stanzas than we sent. serverCount="
1142                            + serverCount
1143                            + ", ourCount="
1144                            + stanzasSent);
1145        }
1146        boolean acknowledgedMessages = false;
1147        for (int i = 0; i < mStanzaQueue.size(); ++i) {
1148            if (serverCount >= mStanzaQueue.keyAt(i)) {
1149                if (Config.EXTENDED_SM_LOGGING) {
1150                    Log.d(
1151                            Config.LOGTAG,
1152                            account.getJid().asBareJid()
1153                                    + ": server acknowledged stanza #"
1154                                    + mStanzaQueue.keyAt(i));
1155                }
1156                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1157                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
1158                    final MessagePacket packet = (MessagePacket) stanza;
1159                    final String id = packet.getId();
1160                    final Jid to = packet.getTo();
1161                    if (id != null && to != null) {
1162                        acknowledgedMessages |=
1163                                acknowledgedListener.onMessageAcknowledged(account, to, id);
1164                    }
1165                }
1166                mStanzaQueue.removeAt(i);
1167                i--;
1168            }
1169        }
1170        return acknowledgedMessages;
1171    }
1172
1173    private @NonNull Element processPacket(final Tag currentTag, final int packetType)
1174            throws IOException {
1175        final Element element =
1176                switch (packetType) {
1177                    case PACKET_IQ -> new IqPacket();
1178                    case PACKET_MESSAGE -> new MessagePacket();
1179                    case PACKET_PRESENCE -> new PresencePacket();
1180                    default -> throw new AssertionError("Should never encounter invalid type");
1181                };
1182        element.setAttributes(currentTag.getAttributes());
1183        Tag nextTag = tagReader.readTag();
1184        if (nextTag == null) {
1185            throw new IOException("interrupted mid tag");
1186        }
1187        while (!nextTag.isEnd(element.getName())) {
1188            if (!nextTag.isNo()) {
1189                element.addChild(tagReader.readElement(nextTag));
1190            }
1191            nextTag = tagReader.readTag();
1192            if (nextTag == null) {
1193                throw new IOException("interrupted mid tag");
1194            }
1195        }
1196        if (stanzasReceived == Integer.MAX_VALUE) {
1197            resetStreamId();
1198            throw new IOException("time to restart the session. cant handle >2 billion pcks");
1199        }
1200        if (inSmacksSession) {
1201            ++stanzasReceived;
1202        } else if (features.sm()) {
1203            Log.d(
1204                    Config.LOGTAG,
1205                    account.getJid().asBareJid()
1206                            + ": not counting stanza("
1207                            + element.getClass().getSimpleName()
1208                            + "). Not in smacks session.");
1209        }
1210        lastPacketReceived = SystemClock.elapsedRealtime();
1211        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
1212            Log.d(Config.LOGTAG, "[background stanza] " + element);
1213        }
1214        if (element instanceof IqPacket
1215                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
1216                && element.hasChild("jingle", Namespace.JINGLE)) {
1217            return JinglePacket.upgrade((IqPacket) element);
1218        } else {
1219            return element;
1220        }
1221    }
1222
1223    private void processIq(final Tag currentTag) throws IOException {
1224        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
1225        if (!packet.valid()) {
1226            Log.e(
1227                    Config.LOGTAG,
1228                    "encountered invalid iq from='"
1229                            + packet.getFrom()
1230                            + "' to='"
1231                            + packet.getTo()
1232                            + "'");
1233            return;
1234        }
1235        if (packet instanceof JinglePacket jinglePacket && isBound) {
1236            if (this.jingleListener != null) {
1237                this.jingleListener.onJinglePacketReceived(account, jinglePacket);
1238            }
1239        } else {
1240            final OnIqPacketReceived callback = getIqPacketReceivedCallback(packet);
1241            if (callback == null) {
1242                Log.d(
1243                        Config.LOGTAG,
1244                        account.getJid().asBareJid().toString()
1245                                + ": no callback registered for IQ from "
1246                                + packet.getFrom());
1247                return;
1248            }
1249            try {
1250                callback.onIqPacketReceived(account, packet);
1251            } catch (final StateChangingError error) {
1252                throw new StateChangingException(error.state);
1253            }
1254        }
1255    }
1256
1257    private OnIqPacketReceived getIqPacketReceivedCallback(final IqPacket stanza)
1258            throws StateChangingException {
1259        final boolean isRequest =
1260                stanza.getType() == IqPacket.TYPE.GET || stanza.getType() == IqPacket.TYPE.SET;
1261        if (isRequest) {
1262            if (isBound) {
1263                return this.unregisteredIqListener;
1264            } else {
1265                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1266            }
1267        } else {
1268            synchronized (this.packetCallbacks) {
1269                final var pair = packetCallbacks.get(stanza.getId());
1270                if (pair == null) {
1271                    return null;
1272                }
1273                if (pair.first.toServer(account)) {
1274                    if (stanza.fromServer(account)) {
1275                        packetCallbacks.remove(stanza.getId());
1276                        return pair.second;
1277                    } else {
1278                        Log.e(
1279                                Config.LOGTAG,
1280                                account.getJid().asBareJid().toString()
1281                                        + ": ignoring spoofed iq packet");
1282                    }
1283                } else {
1284                    if (stanza.getFrom() != null && stanza.getFrom().equals(pair.first.getTo())) {
1285                        packetCallbacks.remove(stanza.getId());
1286                        return pair.second;
1287                    } else {
1288                        Log.e(
1289                                Config.LOGTAG,
1290                                account.getJid().asBareJid().toString()
1291                                        + ": ignoring spoofed iq packet");
1292                    }
1293                }
1294            }
1295        }
1296        return null;
1297    }
1298
1299    private void processMessage(final Tag currentTag) throws IOException {
1300        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
1301        if (!packet.valid()) {
1302            Log.e(
1303                    Config.LOGTAG,
1304                    "encountered invalid message from='"
1305                            + packet.getFrom()
1306                            + "' to='"
1307                            + packet.getTo()
1308                            + "'");
1309            return;
1310        }
1311        this.messageListener.onMessagePacketReceived(account, packet);
1312    }
1313
1314    private void processPresence(final Tag currentTag) throws IOException {
1315        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
1316        if (!packet.valid()) {
1317            Log.e(
1318                    Config.LOGTAG,
1319                    "encountered invalid presence from='"
1320                            + packet.getFrom()
1321                            + "' to='"
1322                            + packet.getTo()
1323                            + "'");
1324            return;
1325        }
1326        this.presenceListener.onPresencePacketReceived(account, packet);
1327    }
1328
1329    private void sendStartTLS() throws IOException {
1330        final Tag startTLS = Tag.empty("starttls");
1331        startTLS.setAttribute("xmlns", Namespace.TLS);
1332        tagWriter.writeTag(startTLS);
1333    }
1334
1335    private void switchOverToTls() throws XmlPullParserException, IOException {
1336        tagReader.readTag();
1337        final Socket socket = this.socket;
1338        final SSLSocket sslSocket = upgradeSocketToTls(socket);
1339        this.socket = sslSocket;
1340        this.tagReader.setInputStream(sslSocket.getInputStream());
1341        this.tagWriter.setOutputStream(sslSocket.getOutputStream());
1342        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1343        final boolean quickStart;
1344        try {
1345            quickStart = establishStream(SSLSockets.version(sslSocket));
1346        } catch (final InterruptedException e) {
1347            return;
1348        }
1349        if (quickStart) {
1350            this.quickStartInProgress = true;
1351        }
1352        features.encryptionEnabled = true;
1353        final Tag tag = tagReader.readTag();
1354        if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1355            SSLSockets.log(account, sslSocket);
1356            processStream();
1357        } else {
1358            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1359        }
1360        sslSocket.close();
1361    }
1362
1363    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1364        final SSLSocketFactory sslSocketFactory;
1365        try {
1366            sslSocketFactory = getSSLSocketFactory();
1367        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1368            throw new StateChangingException(Account.State.TLS_ERROR);
1369        }
1370        final InetAddress address = socket.getInetAddress();
1371        final SSLSocket sslSocket =
1372                (SSLSocket)
1373                        sslSocketFactory.createSocket(
1374                                socket, address.getHostAddress(), socket.getPort(), true);
1375        SSLSockets.setSecurity(sslSocket);
1376        SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1377        SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1378        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1379        try {
1380            if (!xmppDomainVerifier.verify(
1381                    account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1382                Log.d(
1383                        Config.LOGTAG,
1384                        account.getJid().asBareJid()
1385                                + ": TLS certificate domain verification failed");
1386                FileBackend.close(sslSocket);
1387                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1388            }
1389        } catch (final SSLPeerUnverifiedException e) {
1390            FileBackend.close(sslSocket);
1391            throw new StateChangingException(Account.State.TLS_ERROR);
1392        }
1393        return sslSocket;
1394    }
1395
1396    private void processStreamFeatures(final Tag currentTag) throws IOException {
1397        this.streamFeatures = tagReader.readElement(currentTag);
1398        final boolean isSecure = isSecure();
1399        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1400        if (this.quickStartInProgress) {
1401            if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1402                Log.d(
1403                        Config.LOGTAG,
1404                        account.getJid().asBareJid()
1405                                + ": quick start in progress. ignoring features: "
1406                                + XmlHelper.printElementNames(this.streamFeatures));
1407                if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1408                    return;
1409                }
1410                if (isFastTokenAvailable(
1411                        this.streamFeatures.findChild("authentication", Namespace.SASL_2))) {
1412                    Log.d(
1413                            Config.LOGTAG,
1414                            account.getJid().asBareJid()
1415                                    + ": fast token available; resetting quick start");
1416                    account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1417                    mXmppConnectionService.databaseBackend.updateAccount(account);
1418                }
1419                return;
1420            }
1421            Log.d(
1422                    Config.LOGTAG,
1423                    account.getJid().asBareJid()
1424                            + ": server lost support for SASL 2. quick start not possible");
1425            this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1426            mXmppConnectionService.databaseBackend.updateAccount(account);
1427            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1428        }
1429        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
1430                && !features.encryptionEnabled) {
1431            sendStartTLS();
1432        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1433                && account.isOptionSet(Account.OPTION_REGISTER)) {
1434            if (isSecure) {
1435                register();
1436            } else {
1437                Log.d(
1438                        Config.LOGTAG,
1439                        account.getJid().asBareJid()
1440                                + ": unable to find STARTTLS for registration process "
1441                                + XmlHelper.printElementNames(this.streamFeatures));
1442                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1443            }
1444        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1445                && account.isOptionSet(Account.OPTION_REGISTER)) {
1446            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1447        } else if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)
1448                && shouldAuthenticate
1449                && isSecure) {
1450            authenticate(SaslMechanism.Version.SASL_2);
1451        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1452                && shouldAuthenticate
1453                && isSecure) {
1454            authenticate(SaslMechanism.Version.SASL);
1455        } else if (this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT)
1456                && isSecure
1457                && loginInfo != null
1458                && streamId != null
1459                && !inSmacksSession) {
1460            if (Config.EXTENDED_SM_LOGGING) {
1461                Log.d(
1462                        Config.LOGTAG,
1463                        account.getJid().asBareJid()
1464                                + ": resuming after stanza #"
1465                                + stanzasReceived);
1466            }
1467            final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1468            this.mSmCatchupMessageCounter.set(0);
1469            this.mWaitingForSmCatchup.set(true);
1470            this.tagWriter.writeStanzaAsync(resume);
1471        } else if (needsBinding) {
1472            if (this.streamFeatures.hasChild("bind", Namespace.BIND)
1473                    && isSecure
1474                    && loginInfo != null) {
1475                sendBindRequest();
1476            } else {
1477                Log.d(
1478                        Config.LOGTAG,
1479                        account.getJid().asBareJid()
1480                                + ": unable to find bind feature "
1481                                + XmlHelper.printElementNames(this.streamFeatures));
1482                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1483            }
1484        } else {
1485            Log.d(
1486                    Config.LOGTAG,
1487                    account.getJid().asBareJid()
1488                            + ": received NOP stream features: "
1489                            + XmlHelper.printElementNames(this.streamFeatures));
1490        }
1491    }
1492
1493    private void authenticate() throws IOException {
1494        final boolean isSecure = isSecure();
1495        if (isSecure && this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1496            authenticate(SaslMechanism.Version.SASL_2);
1497        } else if (isSecure && this.streamFeatures.hasChild("mechanisms", Namespace.SASL)) {
1498            authenticate(SaslMechanism.Version.SASL);
1499        } else {
1500            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1501        }
1502    }
1503
1504    private boolean isSecure() {
1505        return features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1506    }
1507
1508    private void authenticate(final SaslMechanism.Version version) throws IOException {
1509        final Element authElement;
1510        if (version == SaslMechanism.Version.SASL) {
1511            authElement = this.streamFeatures.findChild("mechanisms", Namespace.SASL);
1512        } else {
1513            authElement = this.streamFeatures.findChild("authentication", Namespace.SASL_2);
1514        }
1515        final Collection<String> mechanisms = SaslMechanism.mechanisms(authElement);
1516        final Element cbElement =
1517                this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1518        final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1519        final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1520        final SaslMechanism saslMechanism =
1521                factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1522        this.validate(saslMechanism, mechanisms);
1523        final boolean quickStartAvailable;
1524        final String firstMessage =
1525                saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1526        final boolean usingFast = SaslMechanism.hashedToken(saslMechanism);
1527        final Element authenticate;
1528        if (version == SaslMechanism.Version.SASL) {
1529            authenticate = new Element("auth", Namespace.SASL);
1530            if (!Strings.isNullOrEmpty(firstMessage)) {
1531                authenticate.setContent(firstMessage);
1532            }
1533            quickStartAvailable = false;
1534            this.loginInfo = new LoginInfo(saslMechanism, version, Collections.emptyList());
1535        } else if (version == SaslMechanism.Version.SASL_2) {
1536            final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1537            final boolean sm = inline != null && inline.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1538            final HashedToken.Mechanism hashTokenRequest;
1539            if (usingFast) {
1540                hashTokenRequest = null;
1541            } else {
1542                final Element fast =
1543                        inline == null ? null : inline.findChild("fast", Namespace.FAST);
1544                final Collection<String> fastMechanisms = SaslMechanism.mechanisms(fast);
1545                hashTokenRequest =
1546                        HashedToken.Mechanism.best(fastMechanisms, SSLSockets.version(this.socket));
1547            }
1548            final Collection<String> bindFeatures = Bind2.features(inline);
1549            quickStartAvailable =
1550                    sm
1551                            && bindFeatures != null
1552                            && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1553            if (bindFeatures != null) {
1554                try {
1555                    mXmppConnectionService.restoredFromDatabaseLatch.await();
1556                } catch (final InterruptedException e) {
1557                    Log.d(
1558                            Config.LOGTAG,
1559                            account.getJid().asBareJid()
1560                                    + ": interrupted while waiting for DB restore during SASL2 bind");
1561                    return;
1562                }
1563            }
1564            this.loginInfo = new LoginInfo(saslMechanism, version, bindFeatures);
1565            this.hashTokenRequest = hashTokenRequest;
1566            authenticate =
1567                    generateAuthenticationRequest(
1568                            firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1569        } else {
1570            throw new AssertionError("Missing implementation for " + version);
1571        }
1572
1573        if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1574            mXmppConnectionService.databaseBackend.updateAccount(account);
1575        }
1576
1577        Log.d(
1578                Config.LOGTAG,
1579                account.getJid().toString()
1580                        + ": Authenticating with "
1581                        + version
1582                        + "/"
1583                        + LoginInfo.mechanism(this.loginInfo).getMechanism());
1584        authenticate.setAttribute("mechanism", LoginInfo.mechanism(this.loginInfo).getMechanism());
1585        synchronized (this.mStanzaQueue) {
1586            this.stanzasSentBeforeAuthentication = this.stanzasSent;
1587            tagWriter.writeElement(authenticate);
1588        }
1589    }
1590
1591    private static boolean isFastTokenAvailable(final Element authentication) {
1592        final Element inline = authentication == null ? null : authentication.findChild("inline");
1593        return inline != null && inline.hasChild("fast", Namespace.FAST);
1594    }
1595
1596    private void validate(
1597            final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms)
1598            throws StateChangingException {
1599        if (saslMechanism == null) {
1600            Log.d(
1601                    Config.LOGTAG,
1602                    account.getJid().asBareJid()
1603                            + ": unable to find supported SASL mechanism in "
1604                            + mechanisms);
1605            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1606        }
1607        if (SaslMechanism.hashedToken(saslMechanism)) {
1608            return;
1609        }
1610        final int pinnedMechanism = account.getPinnedMechanismPriority();
1611        if (pinnedMechanism > saslMechanism.getPriority()) {
1612            Log.e(
1613                    Config.LOGTAG,
1614                    "Auth failed. Authentication mechanism "
1615                            + saslMechanism.getMechanism()
1616                            + " has lower priority ("
1617                            + saslMechanism.getPriority()
1618                            + ") than pinned priority ("
1619                            + pinnedMechanism
1620                            + "). Possible downgrade attack?");
1621            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1622        }
1623    }
1624
1625    private Element generateAuthenticationRequest(
1626            final String firstMessage, final boolean usingFast) {
1627        return generateAuthenticationRequest(
1628                firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1629    }
1630
1631    private Element generateAuthenticationRequest(
1632            final String firstMessage,
1633            final boolean usingFast,
1634            final HashedToken.Mechanism hashedTokenRequest,
1635            final Collection<String> bind,
1636            final boolean inlineStreamManagement) {
1637        final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1638        if (!Strings.isNullOrEmpty(firstMessage)) {
1639            authenticate.addChild("initial-response").setContent(firstMessage);
1640        }
1641        final Element userAgent = authenticate.addChild("user-agent");
1642        userAgent.setAttribute("id", AccountUtils.publicDeviceId(account));
1643        userAgent
1644                .addChild("software")
1645                .setContent(mXmppConnectionService.getString(R.string.app_name));
1646        if (!PhoneHelper.isEmulator()) {
1647            userAgent
1648                    .addChild("device")
1649                    .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1650        }
1651        // do not include bind if 'inlineStreamManagement' is missing and we have a streamId
1652        // (because we would rather just do a normal SM/resume)
1653        final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1654        if (bind != null && mayAttemptBind) {
1655            authenticate.addChild(generateBindRequest(bind));
1656        }
1657        if (inlineStreamManagement && streamId != null) {
1658            final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1659            this.mSmCatchupMessageCounter.set(0);
1660            this.mWaitingForSmCatchup.set(true);
1661            authenticate.addChild(resume);
1662        }
1663        if (hashedTokenRequest != null) {
1664            authenticate
1665                    .addChild("request-token", Namespace.FAST)
1666                    .setAttribute("mechanism", hashedTokenRequest.name());
1667        }
1668        if (usingFast) {
1669            authenticate.addChild("fast", Namespace.FAST);
1670        }
1671        return authenticate;
1672    }
1673
1674    private Element generateBindRequest(final Collection<String> bindFeatures) {
1675        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1676        final Element bind = new Element("bind", Namespace.BIND2);
1677        bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1678        if (bindFeatures.contains(Namespace.CARBONS)) {
1679            bind.addChild("enable", Namespace.CARBONS);
1680        }
1681        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1682            bind.addChild(new EnablePacket());
1683        }
1684        return bind;
1685    }
1686
1687    private void register() {
1688        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1689        if (preAuth != null && features.invite()) {
1690            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1691            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1692            sendUnmodifiedIqPacket(
1693                    preAuthRequest,
1694                    (account, response) -> {
1695                        if (response.getType() == IqPacket.TYPE.RESULT) {
1696                            sendRegistryRequest();
1697                        } else {
1698                            final String error = response.getErrorCondition();
1699                            Log.d(
1700                                    Config.LOGTAG,
1701                                    account.getJid().asBareJid()
1702                                            + ": failed to pre auth. "
1703                                            + error);
1704                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1705                        }
1706                    },
1707                    true);
1708        } else {
1709            sendRegistryRequest();
1710        }
1711    }
1712
1713    private void sendRegistryRequest() {
1714        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1715        register.query(Namespace.REGISTER);
1716        register.setTo(account.getDomain());
1717        sendUnmodifiedIqPacket(
1718                register,
1719                (account, packet) -> {
1720                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1721                        return;
1722                    }
1723                    if (packet.getType() == IqPacket.TYPE.ERROR) {
1724                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1725                    }
1726                    final Element query = packet.query(Namespace.REGISTER);
1727                    if (query.hasChild("username") && (query.hasChild("password"))) {
1728                        final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1729                        final Element username =
1730                                new Element("username").setContent(account.getUsername());
1731                        final Element password =
1732                                new Element("password").setContent(account.getPassword());
1733                        register1.query(Namespace.REGISTER).addChild(username);
1734                        register1.query().addChild(password);
1735                        register1.setFrom(account.getJid().asBareJid());
1736                        sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1737                    } else if (query.hasChild("x", Namespace.DATA)) {
1738                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1739                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1740                        final String id = packet.getId();
1741                        InputStream is;
1742                        if (blob != null) {
1743                            try {
1744                                final String base64Blob = blob.getContent();
1745                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1746                                is = new ByteArrayInputStream(strBlob);
1747                            } catch (Exception e) {
1748                                is = null;
1749                            }
1750                        } else {
1751                            final boolean useTor =
1752                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1753                            try {
1754                                final String url = data.getValue("url");
1755                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1756                                if (url != null) {
1757                                    is = HttpConnectionManager.open(url, useTor);
1758                                } else if (fallbackUrl != null) {
1759                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1760                                } else {
1761                                    is = null;
1762                                }
1763                            } catch (final IOException e) {
1764                                Log.d(
1765                                        Config.LOGTAG,
1766                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1767                                        e);
1768                                is = null;
1769                            }
1770                        }
1771
1772                        if (is != null) {
1773                            Bitmap captcha = BitmapFactory.decodeStream(is);
1774                            try {
1775                                if (mXmppConnectionService.displayCaptchaRequest(
1776                                        account, id, data, captcha)) {
1777                                    return;
1778                                }
1779                            } catch (Exception e) {
1780                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1781                            }
1782                        }
1783                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1784                    } else if (query.hasChild("instructions")
1785                            || query.hasChild("x", Namespace.OOB)) {
1786                        final String instructions = query.findChildContent("instructions");
1787                        final Element oob = query.findChild("x", Namespace.OOB);
1788                        final String url = oob == null ? null : oob.findChildContent("url");
1789                        if (url != null) {
1790                            setAccountCreationFailed(url);
1791                        } else if (instructions != null) {
1792                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1793                            if (matcher.find()) {
1794                                setAccountCreationFailed(
1795                                        instructions.substring(matcher.start(), matcher.end()));
1796                            }
1797                        }
1798                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1799                    }
1800                },
1801                true);
1802    }
1803
1804    private void setAccountCreationFailed(final String url) {
1805        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1806        if (httpUrl != null && httpUrl.isHttps()) {
1807            this.redirectionUrl = httpUrl;
1808            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1809        }
1810        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1811    }
1812
1813    public HttpUrl getRedirectionUrl() {
1814        return this.redirectionUrl;
1815    }
1816
1817    public void resetEverything() {
1818        resetAttemptCount(true);
1819        resetStreamId();
1820        clearIqCallbacks();
1821        this.stanzasSent = 0;
1822        mStanzaQueue.clear();
1823        this.redirectionUrl = null;
1824        synchronized (this.disco) {
1825            disco.clear();
1826        }
1827        synchronized (this.commands) {
1828            this.commands.clear();
1829        }
1830        this.loginInfo = null;
1831    }
1832
1833    private void sendBindRequest() {
1834        try {
1835            mXmppConnectionService.restoredFromDatabaseLatch.await();
1836        } catch (InterruptedException e) {
1837            Log.d(
1838                    Config.LOGTAG,
1839                    account.getJid().asBareJid()
1840                            + ": interrupted while waiting for DB restore during bind");
1841            return;
1842        }
1843        clearIqCallbacks();
1844        if (account.getJid().isBareJid()) {
1845            account.setResource(this.createNewResource());
1846        } else {
1847            fixResource(mXmppConnectionService, account);
1848        }
1849        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1850        final String resource =
1851                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1852        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1853        this.sendUnmodifiedIqPacket(
1854                iq,
1855                (account, packet) -> {
1856                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1857                        return;
1858                    }
1859                    final Element bind = packet.findChild("bind");
1860                    if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1861                        isBound = true;
1862                        final Element jid = bind.findChild("jid");
1863                        if (jid != null && jid.getContent() != null) {
1864                            try {
1865                                Jid assignedJid = Jid.ofEscaped(jid.getContent());
1866                                if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1867                                    Log.d(
1868                                            Config.LOGTAG,
1869                                            account.getJid().asBareJid()
1870                                                    + ": server tried to re-assign domain to "
1871                                                    + assignedJid.getDomain());
1872                                    throw new StateChangingError(Account.State.BIND_FAILURE);
1873                                }
1874                                if (account.setJid(assignedJid)) {
1875                                    Log.d(
1876                                            Config.LOGTAG,
1877                                            account.getJid().asBareJid()
1878                                                    + ": jid changed during bind. updating database");
1879                                    mXmppConnectionService.databaseBackend.updateAccount(account);
1880                                }
1881                                if (streamFeatures.hasChild("session")
1882                                        && !streamFeatures
1883                                                .findChild("session")
1884                                                .hasChild("optional")) {
1885                                    sendStartSession();
1886                                } else {
1887                                    final boolean waitForDisco = enableStreamManagement();
1888                                    sendPostBindInitialization(waitForDisco, false);
1889                                }
1890                                return;
1891                            } catch (final IllegalArgumentException e) {
1892                                Log.d(
1893                                        Config.LOGTAG,
1894                                        account.getJid().asBareJid()
1895                                                + ": server reported invalid jid ("
1896                                                + jid.getContent()
1897                                                + ") on bind");
1898                            }
1899                        } else {
1900                            Log.d(
1901                                    Config.LOGTAG,
1902                                    account.getJid()
1903                                            + ": disconnecting because of bind failure. (no jid)");
1904                        }
1905                    } else {
1906                        Log.d(
1907                                Config.LOGTAG,
1908                                account.getJid()
1909                                        + ": disconnecting because of bind failure ("
1910                                        + packet);
1911                    }
1912                    final Element error = packet.findChild("error");
1913                    if (packet.getType() == IqPacket.TYPE.ERROR
1914                            && error != null
1915                            && error.hasChild("conflict")) {
1916                        account.setResource(createNewResource());
1917                    }
1918                    throw new StateChangingError(Account.State.BIND_FAILURE);
1919                },
1920                true);
1921    }
1922
1923    private void clearIqCallbacks() {
1924        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1925        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1926        synchronized (this.packetCallbacks) {
1927            if (this.packetCallbacks.size() == 0) {
1928                return;
1929            }
1930            Log.d(
1931                    Config.LOGTAG,
1932                    account.getJid().asBareJid()
1933                            + ": clearing "
1934                            + this.packetCallbacks.size()
1935                            + " iq callbacks");
1936            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1937                    this.packetCallbacks.values().iterator();
1938            while (iterator.hasNext()) {
1939                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1940                callbacks.add(entry.second);
1941                iterator.remove();
1942            }
1943        }
1944        for (OnIqPacketReceived callback : callbacks) {
1945            try {
1946                callback.onIqPacketReceived(account, failurePacket);
1947            } catch (StateChangingError error) {
1948                Log.d(
1949                        Config.LOGTAG,
1950                        account.getJid().asBareJid()
1951                                + ": caught StateChangingError("
1952                                + error.state.toString()
1953                                + ") while clearing callbacks");
1954                // ignore
1955            }
1956        }
1957        Log.d(
1958                Config.LOGTAG,
1959                account.getJid().asBareJid()
1960                        + ": done clearing iq callbacks. "
1961                        + this.packetCallbacks.size()
1962                        + " left");
1963    }
1964
1965    public void sendDiscoTimeout() {
1966        if (mWaitForDisco.compareAndSet(true, false)) {
1967            Log.d(
1968                    Config.LOGTAG,
1969                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1970            finalizeBind();
1971        }
1972    }
1973
1974    private void sendStartSession() {
1975        Log.d(
1976                Config.LOGTAG,
1977                account.getJid().asBareJid() + ": sending legacy session to outdated server");
1978        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1979        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1980        this.sendUnmodifiedIqPacket(
1981                startSession,
1982                (account, packet) -> {
1983                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1984                        final boolean waitForDisco = enableStreamManagement();
1985                        sendPostBindInitialization(waitForDisco, false);
1986                    } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1987                        throw new StateChangingError(Account.State.SESSION_FAILURE);
1988                    }
1989                },
1990                true);
1991    }
1992
1993    private boolean enableStreamManagement() {
1994        final boolean streamManagement =
1995                this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1996        if (streamManagement) {
1997            synchronized (this.mStanzaQueue) {
1998                final EnablePacket enable = new EnablePacket();
1999                tagWriter.writeStanzaAsync(enable);
2000                stanzasSent = 0;
2001                mStanzaQueue.clear();
2002            }
2003            return true;
2004        } else {
2005            return false;
2006        }
2007    }
2008
2009    private void sendPostBindInitialization(
2010            final boolean waitForDisco, final boolean carbonsEnabled) {
2011        features.carbonsEnabled = carbonsEnabled;
2012        features.blockListRequested = false;
2013        synchronized (this.disco) {
2014            this.disco.clear();
2015        }
2016        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
2017        mPendingServiceDiscoveries.set(0);
2018        mWaitForDisco.set(waitForDisco);
2019        lastDiscoStarted = SystemClock.elapsedRealtime();
2020        mXmppConnectionService.scheduleWakeUpCall(
2021                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2022        final Element caps = streamFeatures.findChild("c");
2023        final String hash = caps == null ? null : caps.getAttribute("hash");
2024        final String ver = caps == null ? null : caps.getAttribute("ver");
2025        ServiceDiscoveryResult discoveryResult = null;
2026        if (hash != null && ver != null) {
2027            discoveryResult =
2028                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2029        }
2030        final boolean requestDiscoItemsFirst =
2031                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
2032        if (requestDiscoItemsFirst) {
2033            sendServiceDiscoveryItems(account.getDomain());
2034        }
2035        if (discoveryResult == null) {
2036            sendServiceDiscoveryInfo(account.getDomain());
2037        } else {
2038            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
2039            disco.put(account.getDomain(), discoveryResult);
2040        }
2041        discoverMamPreferences();
2042        sendServiceDiscoveryInfo(account.getJid().asBareJid());
2043        if (!requestDiscoItemsFirst) {
2044            sendServiceDiscoveryItems(account.getDomain());
2045        }
2046
2047        if (!mWaitForDisco.get()) {
2048            finalizeBind();
2049        }
2050        this.lastSessionStarted = SystemClock.elapsedRealtime();
2051    }
2052
2053    private void sendServiceDiscoveryInfo(final Jid jid) {
2054        mPendingServiceDiscoveries.incrementAndGet();
2055        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2056        iq.setTo(jid);
2057        iq.query("http://jabber.org/protocol/disco#info");
2058        this.sendIqPacket(
2059                iq,
2060                (account, packet) -> {
2061                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2062                        boolean advancedStreamFeaturesLoaded;
2063                        synchronized (XmppConnection.this.disco) {
2064                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2065                            if (jid.equals(account.getDomain())) {
2066                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2067                                        result);
2068                            }
2069                            disco.put(jid, result);
2070                            advancedStreamFeaturesLoaded =
2071                                    disco.containsKey(account.getDomain())
2072                                            && disco.containsKey(account.getJid().asBareJid());
2073                        }
2074                        if (advancedStreamFeaturesLoaded
2075                                && (jid.equals(account.getDomain())
2076                                        || jid.equals(account.getJid().asBareJid()))) {
2077                            enableAdvancedStreamFeatures();
2078                        }
2079                    } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2080                        Log.d(
2081                                Config.LOGTAG,
2082                                account.getJid().asBareJid()
2083                                        + ": could not query disco info for "
2084                                        + jid.toString());
2085                        final boolean serverOrAccount =
2086                                jid.equals(account.getDomain())
2087                                        || jid.equals(account.getJid().asBareJid());
2088                        final boolean advancedStreamFeaturesLoaded;
2089                        if (serverOrAccount) {
2090                            synchronized (XmppConnection.this.disco) {
2091                                disco.put(jid, ServiceDiscoveryResult.empty());
2092                                advancedStreamFeaturesLoaded =
2093                                        disco.containsKey(account.getDomain())
2094                                                && disco.containsKey(account.getJid().asBareJid());
2095                            }
2096                        } else {
2097                            advancedStreamFeaturesLoaded = false;
2098                        }
2099                        if (advancedStreamFeaturesLoaded) {
2100                            enableAdvancedStreamFeatures();
2101                        }
2102                    }
2103                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2104                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2105                                && mWaitForDisco.compareAndSet(true, false)) {
2106                            finalizeBind();
2107                        }
2108                    }
2109                });
2110    }
2111
2112    private void discoverMamPreferences() {
2113        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2114        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2115        sendIqPacket(
2116                request,
2117                (account, response) -> {
2118                    if (response.getType() == IqPacket.TYPE.RESULT) {
2119                        Element prefs =
2120                                response.findChild(
2121                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
2122                        isMamPreferenceAlways =
2123                                "always"
2124                                        .equals(
2125                                                prefs == null
2126                                                        ? null
2127                                                        : prefs.getAttribute("default"));
2128                    }
2129                });
2130    }
2131
2132    private void discoverCommands() {
2133        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2134        request.setTo(account.getDomain());
2135        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2136        sendIqPacket(
2137                request,
2138                (account, response) -> {
2139                    if (response.getType() == IqPacket.TYPE.RESULT) {
2140                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2141                        if (query == null) {
2142                            return;
2143                        }
2144                        final HashMap<String, Jid> commands = new HashMap<>();
2145                        for (final Element child : query.getChildren()) {
2146                            if ("item".equals(child.getName())) {
2147                                final String node = child.getAttribute("node");
2148                                final Jid jid = child.getAttributeAsJid("jid");
2149                                if (node != null && jid != null) {
2150                                    commands.put(node, jid);
2151                                }
2152                            }
2153                        }
2154                        synchronized (this.commands) {
2155                            this.commands.clear();
2156                            this.commands.putAll(commands);
2157                        }
2158                    }
2159                });
2160    }
2161
2162    public boolean isMamPreferenceAlways() {
2163        return isMamPreferenceAlways;
2164    }
2165
2166    private void finalizeBind() {
2167        if (bindListener != null) {
2168            bindListener.onBind(account);
2169        }
2170        changeStatusToOnline();
2171    }
2172
2173    private void enableAdvancedStreamFeatures() {
2174        if (getFeatures().blocking() && !features.blockListRequested) {
2175            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2176            this.sendIqPacket(
2177                    getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
2178        }
2179        for (final OnAdvancedStreamFeaturesLoaded listener :
2180                advancedStreamFeaturesLoadedListeners) {
2181            listener.onAdvancedStreamFeaturesAvailable(account);
2182        }
2183        if (getFeatures().carbons() && !features.carbonsEnabled) {
2184            sendEnableCarbons();
2185        }
2186        if (getFeatures().commands()) {
2187            discoverCommands();
2188        }
2189    }
2190
2191    private void sendServiceDiscoveryItems(final Jid server) {
2192        mPendingServiceDiscoveries.incrementAndGet();
2193        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2194        iq.setTo(server.getDomain());
2195        iq.query("http://jabber.org/protocol/disco#items");
2196        this.sendIqPacket(
2197                iq,
2198                (account, packet) -> {
2199                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2200                        final HashSet<Jid> items = new HashSet<>();
2201                        final List<Element> elements = packet.query().getChildren();
2202                        for (final Element element : elements) {
2203                            if (element.getName().equals("item")) {
2204                                final Jid jid =
2205                                        InvalidJid.getNullForInvalid(
2206                                                element.getAttributeAsJid("jid"));
2207                                if (jid != null && !jid.equals(account.getDomain())) {
2208                                    items.add(jid);
2209                                }
2210                            }
2211                        }
2212                        for (Jid jid : items) {
2213                            sendServiceDiscoveryInfo(jid);
2214                        }
2215                    } else {
2216                        Log.d(
2217                                Config.LOGTAG,
2218                                account.getJid().asBareJid()
2219                                        + ": could not query disco items of "
2220                                        + server);
2221                    }
2222                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2223                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2224                                && mWaitForDisco.compareAndSet(true, false)) {
2225                            finalizeBind();
2226                        }
2227                    }
2228                });
2229    }
2230
2231    private void sendEnableCarbons() {
2232        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2233        iq.addChild("enable", Namespace.CARBONS);
2234        this.sendIqPacket(
2235                iq,
2236                (account, packet) -> {
2237                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2238                        Log.d(
2239                                Config.LOGTAG,
2240                                account.getJid().asBareJid() + ": successfully enabled carbons");
2241                        features.carbonsEnabled = true;
2242                    } else {
2243                        Log.d(
2244                                Config.LOGTAG,
2245                                account.getJid().asBareJid()
2246                                        + ": could not enable carbons "
2247                                        + packet);
2248                    }
2249                });
2250    }
2251
2252    private void processStreamError(final Tag currentTag) throws IOException {
2253        final Element streamError = tagReader.readElement(currentTag);
2254        if (streamError == null) {
2255            return;
2256        }
2257        if (streamError.hasChild("conflict")) {
2258            account.setResource(createNewResource());
2259            Log.d(
2260                    Config.LOGTAG,
2261                    account.getJid().asBareJid()
2262                            + ": switching resource due to conflict ("
2263                            + account.getResource()
2264                            + ")");
2265            throw new IOException();
2266        } else if (streamError.hasChild("host-unknown")) {
2267            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2268        } else if (streamError.hasChild("policy-violation")) {
2269            this.lastConnect = SystemClock.elapsedRealtime();
2270            final String text = streamError.findChildContent("text");
2271            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2272            failPendingMessages(text);
2273            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2274        } else if (streamError.hasChild("see-other-host")) {
2275            final String seeOtherHost = streamError.findChildContent("see-other-host");
2276            final Resolver.Result currentResolverResult = this.currentResolverResult;
2277            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2278                Log.d(
2279                        Config.LOGTAG,
2280                        account.getJid().asBareJid() + ": stream error " + streamError);
2281                throw new StateChangingException(Account.State.STREAM_ERROR);
2282            }
2283            Log.d(
2284                    Config.LOGTAG,
2285                    account.getJid().asBareJid()
2286                            + ": see other host: "
2287                            + seeOtherHost
2288                            + " "
2289                            + currentResolverResult);
2290            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2291            if (seeOtherResult != null) {
2292                this.seeOtherHostResolverResult = seeOtherResult;
2293                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2294            } else {
2295                throw new StateChangingException(Account.State.STREAM_ERROR);
2296            }
2297        } else {
2298            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2299            throw new StateChangingException(Account.State.STREAM_ERROR);
2300        }
2301    }
2302
2303    private void failPendingMessages(final String error) {
2304        synchronized (this.mStanzaQueue) {
2305            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2306                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
2307                if (stanza instanceof MessagePacket) {
2308                    final MessagePacket packet = (MessagePacket) stanza;
2309                    final String id = packet.getId();
2310                    final Jid to = packet.getTo();
2311                    mXmppConnectionService.markMessage(
2312                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2313                }
2314            }
2315        }
2316    }
2317
2318    private boolean establishStream(final SSLSockets.Version sslVersion)
2319            throws IOException, InterruptedException {
2320        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2321        final SaslMechanism quickStartMechanism;
2322        if (secureConnection) {
2323            quickStartMechanism =
2324                    SaslMechanism.ensureAvailable(account.getQuickStartMechanism(), sslVersion);
2325        } else {
2326            quickStartMechanism = null;
2327        }
2328        if (secureConnection
2329                && Config.QUICKSTART_ENABLED
2330                && quickStartMechanism != null
2331                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2332            mXmppConnectionService.restoredFromDatabaseLatch.await();
2333            this.loginInfo =
2334                    new LoginInfo(
2335                            quickStartMechanism,
2336                            SaslMechanism.Version.SASL_2,
2337                            Bind2.QUICKSTART_FEATURES);
2338            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2339            final Element authenticate =
2340                    generateAuthenticationRequest(
2341                            quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2342                            usingFast);
2343            authenticate.setAttribute("mechanism", quickStartMechanism.getMechanism());
2344            sendStartStream(true, false);
2345            synchronized (this.mStanzaQueue) {
2346                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2347                tagWriter.writeElement(authenticate);
2348            }
2349            Log.d(
2350                    Config.LOGTAG,
2351                    account.getJid().toString()
2352                            + ": quick start with "
2353                            + quickStartMechanism.getMechanism());
2354            return true;
2355        } else {
2356            sendStartStream(secureConnection, true);
2357            return false;
2358        }
2359    }
2360
2361    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2362        final Tag stream = Tag.start("stream:stream");
2363        stream.setAttribute("to", account.getServer());
2364        if (from) {
2365            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2366        }
2367        stream.setAttribute("version", "1.0");
2368        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2369        stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2370        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2371        tagWriter.writeTag(stream, flush);
2372    }
2373
2374    private String createNewResource() {
2375        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2376    }
2377
2378    private String nextRandomId() {
2379        return nextRandomId(false);
2380    }
2381
2382    private String nextRandomId(final boolean s) {
2383        return CryptoHelper.random(s ? 3 : 9);
2384    }
2385
2386    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2387        packet.setFrom(account.getJid());
2388        return this.sendUnmodifiedIqPacket(packet, callback, false);
2389    }
2390
2391    public synchronized String sendUnmodifiedIqPacket(
2392            final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2393        if (packet.getId() == null) {
2394            packet.setAttribute("id", nextRandomId());
2395        }
2396        if (callback != null) {
2397            synchronized (this.packetCallbacks) {
2398                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2399            }
2400        }
2401        this.sendPacket(packet, force);
2402        return packet.getId();
2403    }
2404
2405    public void sendMessagePacket(final MessagePacket packet) {
2406        this.sendPacket(packet);
2407    }
2408
2409    public void sendPresencePacket(final PresencePacket packet) {
2410        this.sendPacket(packet);
2411    }
2412
2413    private synchronized void sendPacket(final AbstractStanza packet) {
2414        sendPacket(packet, false);
2415    }
2416
2417    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2418        if (stanzasSent == Integer.MAX_VALUE) {
2419            resetStreamId();
2420            disconnect(true);
2421            return;
2422        }
2423        synchronized (this.mStanzaQueue) {
2424            if (force || isBound) {
2425                tagWriter.writeStanzaAsync(packet);
2426            } else {
2427                Log.d(
2428                        Config.LOGTAG,
2429                        account.getJid().asBareJid()
2430                                + " do not write stanza to unbound stream "
2431                                + packet.toString());
2432            }
2433            if (packet instanceof AbstractAcknowledgeableStanza) {
2434                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
2435
2436                if (this.mStanzaQueue.size() != 0) {
2437                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2438                    if (currentHighestKey != stanzasSent) {
2439                        throw new AssertionError("Stanza count messed up");
2440                    }
2441                }
2442
2443                ++stanzasSent;
2444                if (Config.EXTENDED_SM_LOGGING) {
2445                    Log.d(
2446                            Config.LOGTAG,
2447                            account.getJid().asBareJid()
2448                                    + ": counting outbound "
2449                                    + packet.getName()
2450                                    + " as #"
2451                                    + stanzasSent);
2452                }
2453                this.mStanzaQueue.append(stanzasSent, stanza);
2454                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2455                    if (Config.EXTENDED_SM_LOGGING) {
2456                        Log.d(
2457                                Config.LOGTAG,
2458                                account.getJid().asBareJid()
2459                                        + ": requesting ack for message stanza #"
2460                                        + stanzasSent);
2461                    }
2462                    tagWriter.writeStanzaAsync(new RequestPacket());
2463                }
2464            }
2465        }
2466    }
2467
2468    public void sendPing() {
2469        if (!r()) {
2470            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2471            iq.setFrom(account.getJid());
2472            iq.addChild("ping", Namespace.PING);
2473            this.sendIqPacket(iq, null);
2474        }
2475        this.lastPingSent = SystemClock.elapsedRealtime();
2476    }
2477
2478    public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2479        this.messageListener = listener;
2480    }
2481
2482    public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2483        this.unregisteredIqListener = listener;
2484    }
2485
2486    public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2487        this.presenceListener = listener;
2488    }
2489
2490    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2491        this.jingleListener = listener;
2492    }
2493
2494    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2495        this.statusListener = listener;
2496    }
2497
2498    public void setOnBindListener(final OnBindListener listener) {
2499        this.bindListener = listener;
2500    }
2501
2502    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2503        this.acknowledgedListener = listener;
2504    }
2505
2506    public void addOnAdvancedStreamFeaturesAvailableListener(
2507            final OnAdvancedStreamFeaturesLoaded listener) {
2508        this.advancedStreamFeaturesLoadedListeners.add(listener);
2509    }
2510
2511    private void forceCloseSocket() {
2512        FileBackend.close(this.socket);
2513        FileBackend.close(this.tagReader);
2514    }
2515
2516    public void interrupt() {
2517        if (this.mThread != null) {
2518            this.mThread.interrupt();
2519        }
2520    }
2521
2522    public void disconnect(final boolean force) {
2523        interrupt();
2524        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2525        if (force) {
2526            forceCloseSocket();
2527        } else {
2528            final TagWriter currentTagWriter = this.tagWriter;
2529            if (currentTagWriter.isActive()) {
2530                currentTagWriter.finish();
2531                final Socket currentSocket = this.socket;
2532                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2533                try {
2534                    currentTagWriter.await(1, TimeUnit.SECONDS);
2535                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2536                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2537                    if (streamCountDownLatch != null) {
2538                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2539                            Log.d(
2540                                    Config.LOGTAG,
2541                                    account.getJid().asBareJid() + ": remote ended stream");
2542                        } else {
2543                            Log.d(
2544                                    Config.LOGTAG,
2545                                    account.getJid().asBareJid()
2546                                            + ": remote has not closed socket. force closing");
2547                        }
2548                    }
2549                } catch (InterruptedException e) {
2550                    Log.d(
2551                            Config.LOGTAG,
2552                            account.getJid().asBareJid()
2553                                    + ": interrupted while gracefully closing stream");
2554                } catch (final IOException e) {
2555                    Log.d(
2556                            Config.LOGTAG,
2557                            account.getJid().asBareJid()
2558                                    + ": io exception during disconnect ("
2559                                    + e.getMessage()
2560                                    + ")");
2561                } finally {
2562                    FileBackend.close(currentSocket);
2563                }
2564            } else {
2565                forceCloseSocket();
2566            }
2567        }
2568    }
2569
2570    private void resetStreamId() {
2571        this.streamId = null;
2572        this.boundStreamFeatures = null;
2573    }
2574
2575    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2576        synchronized (this.disco) {
2577            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2578            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2579                if (cursor.getValue().getFeatures().contains(feature)) {
2580                    items.add(cursor);
2581                }
2582            }
2583            return items;
2584        }
2585    }
2586
2587    public Jid findDiscoItemByFeature(final String feature) {
2588        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2589        if (items.size() >= 1) {
2590            return items.get(0).getKey();
2591        }
2592        return null;
2593    }
2594
2595    public boolean r() {
2596        if (getFeatures().sm()) {
2597            this.tagWriter.writeStanzaAsync(new RequestPacket());
2598            return true;
2599        } else {
2600            return false;
2601        }
2602    }
2603
2604    public List<String> getMucServersWithholdAccount() {
2605        final List<String> servers = getMucServers();
2606        servers.remove(account.getDomain().toEscapedString());
2607        return servers;
2608    }
2609
2610    public List<String> getMucServers() {
2611        List<String> servers = new ArrayList<>();
2612        synchronized (this.disco) {
2613            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2614                final ServiceDiscoveryResult value = cursor.getValue();
2615                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2616                        && value.hasIdentity("conference", "text")
2617                        && !value.getFeatures().contains("jabber:iq:gateway")
2618                        && !value.hasIdentity("conference", "irc")) {
2619                    servers.add(cursor.getKey().toString());
2620                }
2621            }
2622        }
2623        return servers;
2624    }
2625
2626    public String getMucServer() {
2627        List<String> servers = getMucServers();
2628        return servers.size() > 0 ? servers.get(0) : null;
2629    }
2630
2631    public int getTimeToNextAttempt(final boolean aggressive) {
2632        final int interval;
2633        if (aggressive) {
2634            interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2635        } else {
2636            final int additionalTime =
2637                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2638            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2639        }
2640        final int secondsSinceLast =
2641                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2642        return interval - secondsSinceLast;
2643    }
2644
2645    public int getAttempt() {
2646        return this.attempt;
2647    }
2648
2649    public Features getFeatures() {
2650        return this.features;
2651    }
2652
2653    public long getLastSessionEstablished() {
2654        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2655        return System.currentTimeMillis() - diff;
2656    }
2657
2658    public long getLastConnect() {
2659        return this.lastConnect;
2660    }
2661
2662    public long getLastPingSent() {
2663        return this.lastPingSent;
2664    }
2665
2666    public long getLastDiscoStarted() {
2667        return this.lastDiscoStarted;
2668    }
2669
2670    public long getLastPacketReceived() {
2671        return this.lastPacketReceived;
2672    }
2673
2674    public void sendActive() {
2675        this.sendPacket(new ActivePacket());
2676    }
2677
2678    public void sendInactive() {
2679        this.sendPacket(new InactivePacket());
2680    }
2681
2682    public void resetAttemptCount(boolean resetConnectTime) {
2683        this.attempt = 0;
2684        if (resetConnectTime) {
2685            this.lastConnect = 0;
2686        }
2687    }
2688
2689    public void setInteractive(boolean interactive) {
2690        this.mInteractive = interactive;
2691    }
2692
2693    private IqGenerator getIqGenerator() {
2694        return mXmppConnectionService.getIqGenerator();
2695    }
2696
2697    private class MyKeyManager implements X509KeyManager {
2698        @Override
2699        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2700            return account.getPrivateKeyAlias();
2701        }
2702
2703        @Override
2704        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2705            return null;
2706        }
2707
2708        @Override
2709        public X509Certificate[] getCertificateChain(String alias) {
2710            Log.d(Config.LOGTAG, "getting certificate chain");
2711            try {
2712                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2713            } catch (final Exception e) {
2714                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2715                return new X509Certificate[0];
2716            }
2717        }
2718
2719        @Override
2720        public String[] getClientAliases(String s, Principal[] principals) {
2721            final String alias = account.getPrivateKeyAlias();
2722            return alias != null ? new String[] {alias} : new String[0];
2723        }
2724
2725        @Override
2726        public String[] getServerAliases(String s, Principal[] principals) {
2727            return new String[0];
2728        }
2729
2730        @Override
2731        public PrivateKey getPrivateKey(String alias) {
2732            try {
2733                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2734            } catch (Exception e) {
2735                return null;
2736            }
2737        }
2738    }
2739
2740    private static class LoginInfo {
2741        public final SaslMechanism saslMechanism;
2742        public final SaslMechanism.Version saslVersion;
2743        public final List<String> inlineBindFeatures;
2744
2745        private LoginInfo(
2746                final SaslMechanism saslMechanism,
2747                final SaslMechanism.Version saslVersion,
2748                final Collection<String> inlineBindFeatures) {
2749            Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2750            Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2751            this.saslMechanism = saslMechanism;
2752            this.saslVersion = saslVersion;
2753            this.inlineBindFeatures =
2754                    inlineBindFeatures == null
2755                            ? Collections.emptyList()
2756                            : ImmutableList.copyOf(inlineBindFeatures);
2757        }
2758
2759        public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2760            return loginInfo == null ? null : loginInfo.saslMechanism;
2761        }
2762    }
2763
2764    private static class StreamId {
2765        public final String id;
2766        public final Resolver.Result location;
2767
2768        private StreamId(String id, Resolver.Result location) {
2769            this.id = id;
2770            this.location = location;
2771        }
2772
2773        @NonNull
2774        @Override
2775        public String toString() {
2776            return MoreObjects.toStringHelper(this)
2777                    .add("id", id)
2778                    .add("location", location)
2779                    .toString();
2780        }
2781    }
2782
2783    private static class StateChangingError extends Error {
2784        private final Account.State state;
2785
2786        public StateChangingError(Account.State state) {
2787            this.state = state;
2788        }
2789    }
2790
2791    private static class StateChangingException extends IOException {
2792        private final Account.State state;
2793
2794        public StateChangingException(Account.State state) {
2795            this.state = state;
2796        }
2797    }
2798
2799    public class Features {
2800        XmppConnection connection;
2801        private boolean carbonsEnabled = false;
2802        private boolean encryptionEnabled = false;
2803        private boolean blockListRequested = false;
2804
2805        public Features(final XmppConnection connection) {
2806            this.connection = connection;
2807        }
2808
2809        private boolean hasDiscoFeature(final Jid server, final String feature) {
2810            synchronized (XmppConnection.this.disco) {
2811                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2812                return sdr != null && sdr.getFeatures().contains(feature);
2813            }
2814        }
2815
2816        public boolean carbons() {
2817            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2818        }
2819
2820        public boolean commands() {
2821            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2822        }
2823
2824        public boolean easyOnboardingInvites() {
2825            synchronized (commands) {
2826                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2827            }
2828        }
2829
2830        public boolean bookmarksConversion() {
2831            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2832                    && pepPublishOptions();
2833        }
2834
2835        public boolean avatarConversion() {
2836            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION)
2837                    && pepPublishOptions();
2838        }
2839
2840        public boolean blocking() {
2841            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2842        }
2843
2844        public boolean spamReporting() {
2845            return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
2846        }
2847
2848        public boolean flexibleOfflineMessageRetrieval() {
2849            return hasDiscoFeature(
2850                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2851        }
2852
2853        public boolean register() {
2854            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2855        }
2856
2857        public boolean invite() {
2858            return connection.streamFeatures != null
2859                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2860        }
2861
2862        public boolean sm() {
2863            return streamId != null
2864                    || (connection.streamFeatures != null
2865                            && connection.streamFeatures.hasChild(
2866                                    "sm", Namespace.STREAM_MANAGEMENT));
2867        }
2868
2869        public boolean csi() {
2870            return connection.streamFeatures != null
2871                    && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2872        }
2873
2874        public boolean pep() {
2875            synchronized (XmppConnection.this.disco) {
2876                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2877                return info != null && info.hasIdentity("pubsub", "pep");
2878            }
2879        }
2880
2881        public boolean pepPersistent() {
2882            synchronized (XmppConnection.this.disco) {
2883                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2884                return info != null
2885                        && info.getFeatures()
2886                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
2887            }
2888        }
2889
2890        public boolean pepPublishOptions() {
2891            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2892        }
2893
2894        public boolean pepOmemoWhitelisted() {
2895            return hasDiscoFeature(
2896                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2897        }
2898
2899        public boolean mam() {
2900            return MessageArchiveService.Version.has(getAccountFeatures());
2901        }
2902
2903        public List<String> getAccountFeatures() {
2904            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2905            return result == null ? Collections.emptyList() : result.getFeatures();
2906        }
2907
2908        public boolean push() {
2909            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2910                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2911        }
2912
2913        public boolean rosterVersioning() {
2914            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2915        }
2916
2917        public void setBlockListRequested(boolean value) {
2918            this.blockListRequested = value;
2919        }
2920
2921        public boolean httpUpload(long filesize) {
2922            if (Config.DISABLE_HTTP_UPLOAD) {
2923                return false;
2924            } else {
2925                for (String namespace :
2926                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2927                    List<Entry<Jid, ServiceDiscoveryResult>> items =
2928                            findDiscoItemsByFeature(namespace);
2929                    if (items.size() > 0) {
2930                        try {
2931                            long maxsize =
2932                                    Long.parseLong(
2933                                            items.get(0)
2934                                                    .getValue()
2935                                                    .getExtendedDiscoInformation(
2936                                                            namespace, "max-file-size"));
2937                            if (filesize <= maxsize) {
2938                                return true;
2939                            } else {
2940                                Log.d(
2941                                        Config.LOGTAG,
2942                                        account.getJid().asBareJid()
2943                                                + ": http upload is not available for files with size "
2944                                                + filesize
2945                                                + " (max is "
2946                                                + maxsize
2947                                                + ")");
2948                                return false;
2949                            }
2950                        } catch (Exception e) {
2951                            return true;
2952                        }
2953                    }
2954                }
2955                return false;
2956            }
2957        }
2958
2959        public boolean useLegacyHttpUpload() {
2960            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
2961                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2962        }
2963
2964        public long getMaxHttpUploadSize() {
2965            for (String namespace :
2966                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2967                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2968                if (items.size() > 0) {
2969                    try {
2970                        return Long.parseLong(
2971                                items.get(0)
2972                                        .getValue()
2973                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
2974                    } catch (Exception e) {
2975                        // ignored
2976                    }
2977                }
2978            }
2979            return -1;
2980        }
2981
2982        public boolean stanzaIds() {
2983            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2984        }
2985
2986        public boolean bookmarks2() {
2987            return pepPublishOptions()
2988                    && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
2989        }
2990
2991        public boolean externalServiceDiscovery() {
2992            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2993        }
2994    }
2995}