XmppConnection.java

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