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