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