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