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