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