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(
1146                    Config.LOGTAG,
1147                    account.getJid().asBareJid()
1148                            + ": resumption failed ("
1149                            + XmlHelper.print(failed.getChildren())
1150                            + ")");
1151        }
1152        resetStreamId();
1153        if (sendBindRequest) {
1154            sendBindRequest();
1155        }
1156    }
1157
1158    private boolean acknowledgeStanzaUpTo(final int serverCount) {
1159        if (serverCount > stanzasSent) {
1160            Log.e(
1161                    Config.LOGTAG,
1162                    "server acknowledged more stanzas than we sent. serverCount="
1163                            + serverCount
1164                            + ", ourCount="
1165                            + stanzasSent);
1166        }
1167        boolean acknowledgedMessages = false;
1168        for (int i = 0; i < mStanzaQueue.size(); ++i) {
1169            if (serverCount >= mStanzaQueue.keyAt(i)) {
1170                if (Config.EXTENDED_SM_LOGGING) {
1171                    Log.d(
1172                            Config.LOGTAG,
1173                            account.getJid().asBareJid()
1174                                    + ": server acknowledged stanza #"
1175                                    + mStanzaQueue.keyAt(i));
1176                }
1177                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1178                if (stanza instanceof MessagePacket packet && acknowledgedListener != null) {
1179                    final String id = packet.getId();
1180                    final Jid to = packet.getTo();
1181                    if (id != null && to != null) {
1182                        acknowledgedMessages |=
1183                                acknowledgedListener.onMessageAcknowledged(account, to, id);
1184                    }
1185                }
1186                mStanzaQueue.removeAt(i);
1187                i--;
1188            }
1189        }
1190        return acknowledgedMessages;
1191    }
1192
1193    private @NonNull Element processPacket(final Tag currentTag, final int packetType)
1194            throws IOException {
1195        final Element element =
1196                switch (packetType) {
1197                    case PACKET_IQ -> new IqPacket();
1198                    case PACKET_MESSAGE -> new MessagePacket();
1199                    case PACKET_PRESENCE -> new PresencePacket();
1200                    default -> throw new AssertionError("Should never encounter invalid type");
1201                };
1202        element.setAttributes(currentTag.getAttributes());
1203        Tag nextTag = tagReader.readTag();
1204        if (nextTag == null) {
1205            throw new IOException("interrupted mid tag");
1206        }
1207        while (!nextTag.isEnd(element.getName())) {
1208            if (!nextTag.isNo()) {
1209                element.addChild(tagReader.readElement(nextTag));
1210            }
1211            nextTag = tagReader.readTag();
1212            if (nextTag == null) {
1213                throw new IOException("interrupted mid tag");
1214            }
1215        }
1216        if (stanzasReceived == Integer.MAX_VALUE) {
1217            resetStreamId();
1218            throw new IOException("time to restart the session. cant handle >2 billion pcks");
1219        }
1220        if (inSmacksSession) {
1221            ++stanzasReceived;
1222        } else if (features.sm()) {
1223            Log.d(
1224                    Config.LOGTAG,
1225                    account.getJid().asBareJid()
1226                            + ": not counting stanza("
1227                            + element.getClass().getSimpleName()
1228                            + "). Not in smacks session.");
1229        }
1230        lastPacketReceived = SystemClock.elapsedRealtime();
1231        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
1232            Log.d(Config.LOGTAG, "[background stanza] " + element);
1233        }
1234        if (element instanceof IqPacket
1235                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
1236                && element.hasChild("jingle", Namespace.JINGLE)) {
1237            return JinglePacket.upgrade((IqPacket) element);
1238        } else {
1239            return element;
1240        }
1241    }
1242
1243    private void processIq(final Tag currentTag) throws IOException {
1244        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
1245        if (!packet.valid()) {
1246            Log.e(
1247                    Config.LOGTAG,
1248                    "encountered invalid iq from='"
1249                            + packet.getFrom()
1250                            + "' to='"
1251                            + packet.getTo()
1252                            + "'");
1253            return;
1254        }
1255        if (Thread.currentThread().isInterrupted()) {
1256            Log.d(
1257                    Config.LOGTAG,
1258                    account.getJid().asBareJid() + "Not processing iq. Thread was interrupted");
1259            return;
1260        }
1261        if (packet instanceof JinglePacket jinglePacket && isBound) {
1262            if (this.jingleListener != null) {
1263                this.jingleListener.onJinglePacketReceived(account, jinglePacket);
1264            }
1265        } else {
1266            final OnIqPacketReceived callback = getIqPacketReceivedCallback(packet);
1267            if (callback == null) {
1268                Log.d(
1269                        Config.LOGTAG,
1270                        account.getJid().asBareJid().toString()
1271                                + ": no callback registered for IQ from "
1272                                + packet.getFrom());
1273                return;
1274            }
1275            try {
1276                callback.onIqPacketReceived(account, packet);
1277            } catch (final StateChangingError error) {
1278                throw new StateChangingException(error.state);
1279            }
1280        }
1281    }
1282
1283    private OnIqPacketReceived getIqPacketReceivedCallback(final IqPacket stanza)
1284            throws StateChangingException {
1285        final boolean isRequest =
1286                stanza.getType() == IqPacket.TYPE.GET || stanza.getType() == IqPacket.TYPE.SET;
1287        if (isRequest) {
1288            if (isBound) {
1289                return this.unregisteredIqListener;
1290            } else {
1291                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1292            }
1293        } else {
1294            synchronized (this.packetCallbacks) {
1295                final var pair = packetCallbacks.get(stanza.getId());
1296                if (pair == null) {
1297                    return null;
1298                }
1299                if (pair.first.toServer(account)) {
1300                    if (stanza.fromServer(account)) {
1301                        packetCallbacks.remove(stanza.getId());
1302                        return pair.second;
1303                    } else {
1304                        Log.e(
1305                                Config.LOGTAG,
1306                                account.getJid().asBareJid().toString()
1307                                        + ": ignoring spoofed iq packet");
1308                    }
1309                } else {
1310                    if (stanza.getFrom() != null && stanza.getFrom().equals(pair.first.getTo())) {
1311                        packetCallbacks.remove(stanza.getId());
1312                        return pair.second;
1313                    } else {
1314                        Log.e(
1315                                Config.LOGTAG,
1316                                account.getJid().asBareJid().toString()
1317                                        + ": ignoring spoofed iq packet");
1318                    }
1319                }
1320            }
1321        }
1322        return null;
1323    }
1324
1325    private void processMessage(final Tag currentTag) throws IOException {
1326        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
1327        if (!packet.valid()) {
1328            Log.e(
1329                    Config.LOGTAG,
1330                    "encountered invalid message from='"
1331                            + packet.getFrom()
1332                            + "' to='"
1333                            + packet.getTo()
1334                            + "'");
1335            return;
1336        }
1337        if (Thread.currentThread().isInterrupted()) {
1338            Log.d(
1339                    Config.LOGTAG,
1340                    account.getJid().asBareJid()
1341                            + "Not processing message. Thread was interrupted");
1342            return;
1343        }
1344        this.messageListener.onMessagePacketReceived(account, packet);
1345    }
1346
1347    private void processPresence(final Tag currentTag) throws IOException {
1348        final PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
1349        if (!packet.valid()) {
1350            Log.e(
1351                    Config.LOGTAG,
1352                    "encountered invalid presence from='"
1353                            + packet.getFrom()
1354                            + "' to='"
1355                            + packet.getTo()
1356                            + "'");
1357            return;
1358        }
1359        if (Thread.currentThread().isInterrupted()) {
1360            Log.d(
1361                    Config.LOGTAG,
1362                    account.getJid().asBareJid()
1363                            + "Not processing presence. Thread was interrupted");
1364            return;
1365        }
1366        this.presenceListener.onPresencePacketReceived(account, packet);
1367    }
1368
1369    private void sendStartTLS() throws IOException {
1370        final Tag startTLS = Tag.empty("starttls");
1371        startTLS.setAttribute("xmlns", Namespace.TLS);
1372        tagWriter.writeTag(startTLS);
1373    }
1374
1375    private void switchOverToTls() throws XmlPullParserException, IOException {
1376        tagReader.readTag();
1377        final Socket socket = this.socket;
1378        final SSLSocket sslSocket = upgradeSocketToTls(socket);
1379        this.socket = sslSocket;
1380        this.tagReader.setInputStream(sslSocket.getInputStream());
1381        this.tagWriter.setOutputStream(sslSocket.getOutputStream());
1382        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1383        final boolean quickStart;
1384        try {
1385            quickStart = establishStream(SSLSockets.version(sslSocket));
1386        } catch (final InterruptedException e) {
1387            return;
1388        }
1389        if (quickStart) {
1390            this.quickStartInProgress = true;
1391        }
1392        features.encryptionEnabled = true;
1393        final Tag tag = tagReader.readTag();
1394        if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1395            SSLSockets.log(account, sslSocket);
1396            processStream();
1397        } else {
1398            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1399        }
1400        sslSocket.close();
1401    }
1402
1403    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1404        final SSLSocketFactory sslSocketFactory;
1405        try {
1406            sslSocketFactory = getSSLSocketFactory();
1407        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1408            throw new StateChangingException(Account.State.TLS_ERROR);
1409        }
1410        final InetAddress address = socket.getInetAddress();
1411        final SSLSocket sslSocket =
1412                (SSLSocket)
1413                        sslSocketFactory.createSocket(
1414                                socket, address.getHostAddress(), socket.getPort(), true);
1415        SSLSockets.setSecurity(sslSocket);
1416        SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1417        SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1418        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1419        try {
1420            if (!xmppDomainVerifier.verify(
1421                    account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1422                Log.d(
1423                        Config.LOGTAG,
1424                        account.getJid().asBareJid()
1425                                + ": TLS certificate domain verification failed");
1426                FileBackend.close(sslSocket);
1427                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1428            }
1429        } catch (final SSLPeerUnverifiedException e) {
1430            FileBackend.close(sslSocket);
1431            throw new StateChangingException(Account.State.TLS_ERROR);
1432        }
1433        return sslSocket;
1434    }
1435
1436    private void processStreamFeatures(final Tag currentTag) throws IOException {
1437        this.streamFeatures = tagReader.readElement(currentTag);
1438        final boolean isSecure = isSecure();
1439        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1440        if (this.quickStartInProgress) {
1441            if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1442                Log.d(
1443                        Config.LOGTAG,
1444                        account.getJid().asBareJid()
1445                                + ": quick start in progress. ignoring features: "
1446                                + XmlHelper.printElementNames(this.streamFeatures));
1447                if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1448                    return;
1449                }
1450                if (isFastTokenAvailable(
1451                        this.streamFeatures.findChild("authentication", Namespace.SASL_2))) {
1452                    Log.d(
1453                            Config.LOGTAG,
1454                            account.getJid().asBareJid()
1455                                    + ": fast token available; resetting quick start");
1456                    account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1457                    mXmppConnectionService.databaseBackend.updateAccount(account);
1458                }
1459                return;
1460            }
1461            Log.d(
1462                    Config.LOGTAG,
1463                    account.getJid().asBareJid()
1464                            + ": server lost support for SASL 2. quick start not possible");
1465            this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1466            mXmppConnectionService.databaseBackend.updateAccount(account);
1467            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1468        }
1469        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
1470                && !features.encryptionEnabled) {
1471            sendStartTLS();
1472        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1473                && account.isOptionSet(Account.OPTION_REGISTER)) {
1474            if (isSecure) {
1475                register();
1476            } else {
1477                Log.d(
1478                        Config.LOGTAG,
1479                        account.getJid().asBareJid()
1480                                + ": unable to find STARTTLS for registration process "
1481                                + XmlHelper.printElementNames(this.streamFeatures));
1482                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1483            }
1484        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1485                && account.isOptionSet(Account.OPTION_REGISTER)) {
1486            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1487        } else if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)
1488                && shouldAuthenticate
1489                && isSecure) {
1490            authenticate(SaslMechanism.Version.SASL_2);
1491        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1492                && shouldAuthenticate
1493                && isSecure) {
1494            authenticate(SaslMechanism.Version.SASL);
1495        } else if (this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT)
1496                && isSecure
1497                && LoginInfo.isSuccess(loginInfo)
1498                && streamId != null
1499                && !inSmacksSession) {
1500            if (Config.EXTENDED_SM_LOGGING) {
1501                Log.d(
1502                        Config.LOGTAG,
1503                        account.getJid().asBareJid()
1504                                + ": resuming after stanza #"
1505                                + stanzasReceived);
1506            }
1507            final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1508            this.mSmCatchupMessageCounter.set(0);
1509            this.mWaitingForSmCatchup.set(true);
1510            this.tagWriter.writeStanzaAsync(resume);
1511        } else if (needsBinding) {
1512            if (this.streamFeatures.hasChild("bind", Namespace.BIND)
1513                    && isSecure
1514                    && LoginInfo.isSuccess(loginInfo)) {
1515                sendBindRequest();
1516            } else {
1517                Log.d(
1518                        Config.LOGTAG,
1519                        account.getJid().asBareJid()
1520                                + ": unable to find bind feature "
1521                                + XmlHelper.printElementNames(this.streamFeatures));
1522                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1523            }
1524        } else {
1525            Log.d(
1526                    Config.LOGTAG,
1527                    account.getJid().asBareJid()
1528                            + ": received NOP stream features: "
1529                            + XmlHelper.printElementNames(this.streamFeatures));
1530        }
1531    }
1532
1533    private void authenticate() throws IOException {
1534        final boolean isSecure = isSecure();
1535        if (isSecure && this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1536            authenticate(SaslMechanism.Version.SASL_2);
1537        } else if (isSecure && this.streamFeatures.hasChild("mechanisms", Namespace.SASL)) {
1538            authenticate(SaslMechanism.Version.SASL);
1539        } else {
1540            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1541        }
1542    }
1543
1544    private boolean isSecure() {
1545        return features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1546    }
1547
1548    private void authenticate(final SaslMechanism.Version version) throws IOException {
1549        final Element authElement;
1550        if (version == SaslMechanism.Version.SASL) {
1551            authElement = this.streamFeatures.findChild("mechanisms", Namespace.SASL);
1552        } else {
1553            authElement = this.streamFeatures.findChild("authentication", Namespace.SASL_2);
1554        }
1555        final Collection<String> mechanisms = SaslMechanism.mechanisms(authElement);
1556        final Element cbElement =
1557                this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1558        final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1559        final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1560        final SaslMechanism saslMechanism =
1561                factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1562        this.validate(saslMechanism, mechanisms);
1563        final boolean quickStartAvailable;
1564        final String firstMessage =
1565                saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1566        final boolean usingFast = SaslMechanism.hashedToken(saslMechanism);
1567        final Element authenticate;
1568        if (version == SaslMechanism.Version.SASL) {
1569            authenticate = new Element("auth", Namespace.SASL);
1570            if (!Strings.isNullOrEmpty(firstMessage)) {
1571                authenticate.setContent(firstMessage);
1572            }
1573            quickStartAvailable = false;
1574            this.loginInfo = new LoginInfo(saslMechanism, version, Collections.emptyList());
1575        } else if (version == SaslMechanism.Version.SASL_2) {
1576            final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1577            final boolean sm = inline != null && inline.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1578            final HashedToken.Mechanism hashTokenRequest;
1579            if (usingFast) {
1580                hashTokenRequest = null;
1581            } else {
1582                final Element fast =
1583                        inline == null ? null : inline.findChild("fast", Namespace.FAST);
1584                final Collection<String> fastMechanisms = SaslMechanism.mechanisms(fast);
1585                hashTokenRequest =
1586                        HashedToken.Mechanism.best(fastMechanisms, SSLSockets.version(this.socket));
1587            }
1588            final Collection<String> bindFeatures = Bind2.features(inline);
1589            quickStartAvailable =
1590                    sm
1591                            && bindFeatures != null
1592                            && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1593            if (bindFeatures != null) {
1594                try {
1595                    mXmppConnectionService.restoredFromDatabaseLatch.await();
1596                } catch (final InterruptedException e) {
1597                    Log.d(
1598                            Config.LOGTAG,
1599                            account.getJid().asBareJid()
1600                                    + ": interrupted while waiting for DB restore during SASL2 bind");
1601                    return;
1602                }
1603            }
1604            this.loginInfo = new LoginInfo(saslMechanism, version, bindFeatures);
1605            this.hashTokenRequest = hashTokenRequest;
1606            authenticate =
1607                    generateAuthenticationRequest(
1608                            firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1609        } else {
1610            throw new AssertionError("Missing implementation for " + version);
1611        }
1612
1613        if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1614            mXmppConnectionService.databaseBackend.updateAccount(account);
1615        }
1616
1617        Log.d(
1618                Config.LOGTAG,
1619                account.getJid().toString()
1620                        + ": Authenticating with "
1621                        + version
1622                        + "/"
1623                        + LoginInfo.mechanism(this.loginInfo).getMechanism());
1624        authenticate.setAttribute("mechanism", LoginInfo.mechanism(this.loginInfo).getMechanism());
1625        synchronized (this.mStanzaQueue) {
1626            this.stanzasSentBeforeAuthentication = this.stanzasSent;
1627            tagWriter.writeElement(authenticate);
1628        }
1629    }
1630
1631    private static boolean isFastTokenAvailable(final Element authentication) {
1632        final Element inline = authentication == null ? null : authentication.findChild("inline");
1633        return inline != null && inline.hasChild("fast", Namespace.FAST);
1634    }
1635
1636    private void validate(
1637            final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms)
1638            throws StateChangingException {
1639        if (saslMechanism == null) {
1640            Log.d(
1641                    Config.LOGTAG,
1642                    account.getJid().asBareJid()
1643                            + ": unable to find supported SASL mechanism in "
1644                            + mechanisms);
1645            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1646        }
1647        if (SaslMechanism.hashedToken(saslMechanism)) {
1648            return;
1649        }
1650        final int pinnedMechanism = account.getPinnedMechanismPriority();
1651        if (pinnedMechanism > saslMechanism.getPriority()) {
1652            Log.e(
1653                    Config.LOGTAG,
1654                    "Auth failed. Authentication mechanism "
1655                            + saslMechanism.getMechanism()
1656                            + " has lower priority ("
1657                            + saslMechanism.getPriority()
1658                            + ") than pinned priority ("
1659                            + pinnedMechanism
1660                            + "). Possible downgrade attack?");
1661            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1662        }
1663    }
1664
1665    private Element generateAuthenticationRequest(
1666            final String firstMessage, final boolean usingFast) {
1667        return generateAuthenticationRequest(
1668                firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1669    }
1670
1671    private Element generateAuthenticationRequest(
1672            final String firstMessage,
1673            final boolean usingFast,
1674            final HashedToken.Mechanism hashedTokenRequest,
1675            final Collection<String> bind,
1676            final boolean inlineStreamManagement) {
1677        final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1678        if (!Strings.isNullOrEmpty(firstMessage)) {
1679            authenticate.addChild("initial-response").setContent(firstMessage);
1680        }
1681        final Element userAgent = authenticate.addChild("user-agent");
1682        userAgent.setAttribute("id", AccountUtils.publicDeviceId(account));
1683        userAgent
1684                .addChild("software")
1685                .setContent(mXmppConnectionService.getString(R.string.app_name));
1686        if (!PhoneHelper.isEmulator()) {
1687            userAgent
1688                    .addChild("device")
1689                    .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1690        }
1691        // do not include bind if 'inlineStreamManagement' is missing and we have a streamId
1692        // (because we would rather just do a normal SM/resume)
1693        final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1694        if (bind != null && mayAttemptBind) {
1695            authenticate.addChild(generateBindRequest(bind));
1696        }
1697        if (inlineStreamManagement && streamId != null) {
1698            final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1699            this.mSmCatchupMessageCounter.set(0);
1700            this.mWaitingForSmCatchup.set(true);
1701            authenticate.addChild(resume);
1702        }
1703        if (hashedTokenRequest != null) {
1704            authenticate
1705                    .addChild("request-token", Namespace.FAST)
1706                    .setAttribute("mechanism", hashedTokenRequest.name());
1707        }
1708        if (usingFast) {
1709            authenticate.addChild("fast", Namespace.FAST);
1710        }
1711        return authenticate;
1712    }
1713
1714    private Element generateBindRequest(final Collection<String> bindFeatures) {
1715        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1716        final Element bind = new Element("bind", Namespace.BIND2);
1717        bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1718        if (bindFeatures.contains(Namespace.CARBONS)) {
1719            bind.addChild("enable", Namespace.CARBONS);
1720        }
1721        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1722            bind.addChild(new EnablePacket());
1723        }
1724        return bind;
1725    }
1726
1727    private void register() {
1728        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1729        if (preAuth != null && features.invite()) {
1730            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1731            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1732            sendUnmodifiedIqPacket(
1733                    preAuthRequest,
1734                    (account, response) -> {
1735                        if (response.getType() == IqPacket.TYPE.RESULT) {
1736                            sendRegistryRequest();
1737                        } else {
1738                            final String error = response.getErrorCondition();
1739                            Log.d(
1740                                    Config.LOGTAG,
1741                                    account.getJid().asBareJid()
1742                                            + ": failed to pre auth. "
1743                                            + error);
1744                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1745                        }
1746                    },
1747                    true);
1748        } else {
1749            sendRegistryRequest();
1750        }
1751    }
1752
1753    private void sendRegistryRequest() {
1754        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1755        register.query(Namespace.REGISTER);
1756        register.setTo(account.getDomain());
1757        sendUnmodifiedIqPacket(
1758                register,
1759                (account, packet) -> {
1760                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1761                        return;
1762                    }
1763                    if (packet.getType() == IqPacket.TYPE.ERROR) {
1764                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1765                    }
1766                    final Element query = packet.query(Namespace.REGISTER);
1767                    if (query.hasChild("username") && (query.hasChild("password"))) {
1768                        final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1769                        final Element username =
1770                                new Element("username").setContent(account.getUsername());
1771                        final Element password =
1772                                new Element("password").setContent(account.getPassword());
1773                        register1.query(Namespace.REGISTER).addChild(username);
1774                        register1.query().addChild(password);
1775                        register1.setFrom(account.getJid().asBareJid());
1776                        sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1777                    } else if (query.hasChild("x", Namespace.DATA)) {
1778                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1779                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1780                        final String id = packet.getId();
1781                        InputStream is;
1782                        if (blob != null) {
1783                            try {
1784                                final String base64Blob = blob.getContent();
1785                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1786                                is = new ByteArrayInputStream(strBlob);
1787                            } catch (Exception e) {
1788                                is = null;
1789                            }
1790                        } else {
1791                            final boolean useTor =
1792                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1793                            try {
1794                                final String url = data.getValue("url");
1795                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1796                                if (url != null) {
1797                                    is = HttpConnectionManager.open(url, useTor);
1798                                } else if (fallbackUrl != null) {
1799                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1800                                } else {
1801                                    is = null;
1802                                }
1803                            } catch (final IOException e) {
1804                                Log.d(
1805                                        Config.LOGTAG,
1806                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1807                                        e);
1808                                is = null;
1809                            }
1810                        }
1811
1812                        if (is != null) {
1813                            Bitmap captcha = BitmapFactory.decodeStream(is);
1814                            try {
1815                                if (mXmppConnectionService.displayCaptchaRequest(
1816                                        account, id, data, captcha)) {
1817                                    return;
1818                                }
1819                            } catch (Exception e) {
1820                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1821                            }
1822                        }
1823                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1824                    } else if (query.hasChild("instructions")
1825                            || query.hasChild("x", Namespace.OOB)) {
1826                        final String instructions = query.findChildContent("instructions");
1827                        final Element oob = query.findChild("x", Namespace.OOB);
1828                        final String url = oob == null ? null : oob.findChildContent("url");
1829                        if (url != null) {
1830                            setAccountCreationFailed(url);
1831                        } else if (instructions != null) {
1832                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1833                            if (matcher.find()) {
1834                                setAccountCreationFailed(
1835                                        instructions.substring(matcher.start(), matcher.end()));
1836                            }
1837                        }
1838                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1839                    }
1840                },
1841                true);
1842    }
1843
1844    private void setAccountCreationFailed(final String url) {
1845        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1846        if (httpUrl != null && httpUrl.isHttps()) {
1847            this.redirectionUrl = httpUrl;
1848            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1849        }
1850        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1851    }
1852
1853    public HttpUrl getRedirectionUrl() {
1854        return this.redirectionUrl;
1855    }
1856
1857    public void resetEverything() {
1858        resetAttemptCount(true);
1859        resetStreamId();
1860        clearIqCallbacks();
1861        synchronized (this.mStanzaQueue) {
1862            this.stanzasSent = 0;
1863            this.mStanzaQueue.clear();
1864        }
1865        this.redirectionUrl = null;
1866        synchronized (this.disco) {
1867            disco.clear();
1868        }
1869        synchronized (this.commands) {
1870            this.commands.clear();
1871        }
1872        this.loginInfo = null;
1873    }
1874
1875    private void sendBindRequest() {
1876        try {
1877            mXmppConnectionService.restoredFromDatabaseLatch.await();
1878        } catch (InterruptedException e) {
1879            Log.d(
1880                    Config.LOGTAG,
1881                    account.getJid().asBareJid()
1882                            + ": interrupted while waiting for DB restore during bind");
1883            return;
1884        }
1885        clearIqCallbacks();
1886        if (account.getJid().isBareJid()) {
1887            account.setResource(this.createNewResource());
1888        } else {
1889            fixResource(mXmppConnectionService, account);
1890        }
1891        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1892        final String resource =
1893                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1894        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1895        this.sendUnmodifiedIqPacket(
1896                iq,
1897                (account, packet) -> {
1898                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1899                        return;
1900                    }
1901                    final Element bind = packet.findChild("bind");
1902                    if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1903                        isBound = true;
1904                        final Element jid = bind.findChild("jid");
1905                        if (jid != null && jid.getContent() != null) {
1906                            try {
1907                                Jid assignedJid = Jid.ofEscaped(jid.getContent());
1908                                if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1909                                    Log.d(
1910                                            Config.LOGTAG,
1911                                            account.getJid().asBareJid()
1912                                                    + ": server tried to re-assign domain to "
1913                                                    + assignedJid.getDomain());
1914                                    throw new StateChangingError(Account.State.BIND_FAILURE);
1915                                }
1916                                if (account.setJid(assignedJid)) {
1917                                    Log.d(
1918                                            Config.LOGTAG,
1919                                            account.getJid().asBareJid()
1920                                                    + ": jid changed during bind. updating database");
1921                                    mXmppConnectionService.databaseBackend.updateAccount(account);
1922                                }
1923                                if (streamFeatures.hasChild("session")
1924                                        && !streamFeatures
1925                                                .findChild("session")
1926                                                .hasChild("optional")) {
1927                                    sendStartSession();
1928                                } else {
1929                                    final boolean waitForDisco = enableStreamManagement();
1930                                    sendPostBindInitialization(waitForDisco, false);
1931                                }
1932                                return;
1933                            } catch (final IllegalArgumentException e) {
1934                                Log.d(
1935                                        Config.LOGTAG,
1936                                        account.getJid().asBareJid()
1937                                                + ": server reported invalid jid ("
1938                                                + jid.getContent()
1939                                                + ") on bind");
1940                            }
1941                        } else {
1942                            Log.d(
1943                                    Config.LOGTAG,
1944                                    account.getJid()
1945                                            + ": disconnecting because of bind failure. (no jid)");
1946                        }
1947                    } else {
1948                        Log.d(
1949                                Config.LOGTAG,
1950                                account.getJid()
1951                                        + ": disconnecting because of bind failure ("
1952                                        + packet);
1953                    }
1954                    final Element error = packet.findChild("error");
1955                    if (packet.getType() == IqPacket.TYPE.ERROR
1956                            && error != null
1957                            && error.hasChild("conflict")) {
1958                        account.setResource(createNewResource());
1959                    }
1960                    throw new StateChangingError(Account.State.BIND_FAILURE);
1961                },
1962                true);
1963    }
1964
1965    private void clearIqCallbacks() {
1966        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1967        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1968        synchronized (this.packetCallbacks) {
1969            if (this.packetCallbacks.size() == 0) {
1970                return;
1971            }
1972            Log.d(
1973                    Config.LOGTAG,
1974                    account.getJid().asBareJid()
1975                            + ": clearing "
1976                            + this.packetCallbacks.size()
1977                            + " iq callbacks");
1978            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1979                    this.packetCallbacks.values().iterator();
1980            while (iterator.hasNext()) {
1981                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1982                callbacks.add(entry.second);
1983                iterator.remove();
1984            }
1985        }
1986        for (OnIqPacketReceived callback : callbacks) {
1987            try {
1988                callback.onIqPacketReceived(account, failurePacket);
1989            } catch (StateChangingError error) {
1990                Log.d(
1991                        Config.LOGTAG,
1992                        account.getJid().asBareJid()
1993                                + ": caught StateChangingError("
1994                                + error.state.toString()
1995                                + ") while clearing callbacks");
1996                // ignore
1997            }
1998        }
1999        Log.d(
2000                Config.LOGTAG,
2001                account.getJid().asBareJid()
2002                        + ": done clearing iq callbacks. "
2003                        + this.packetCallbacks.size()
2004                        + " left");
2005    }
2006
2007    public void sendDiscoTimeout() {
2008        if (mWaitForDisco.compareAndSet(true, false)) {
2009            Log.d(
2010                    Config.LOGTAG,
2011                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
2012            finalizeBind();
2013        }
2014    }
2015
2016    private void sendStartSession() {
2017        Log.d(
2018                Config.LOGTAG,
2019                account.getJid().asBareJid() + ": sending legacy session to outdated server");
2020        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
2021        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
2022        this.sendUnmodifiedIqPacket(
2023                startSession,
2024                (account, packet) -> {
2025                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2026                        final boolean waitForDisco = enableStreamManagement();
2027                        sendPostBindInitialization(waitForDisco, false);
2028                    } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2029                        throw new StateChangingError(Account.State.SESSION_FAILURE);
2030                    }
2031                },
2032                true);
2033    }
2034
2035    private boolean enableStreamManagement() {
2036        final boolean streamManagement =
2037                this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
2038        if (streamManagement) {
2039            synchronized (this.mStanzaQueue) {
2040                final EnablePacket enable = new EnablePacket();
2041                tagWriter.writeStanzaAsync(enable);
2042                stanzasSent = 0;
2043                mStanzaQueue.clear();
2044            }
2045            return true;
2046        } else {
2047            return false;
2048        }
2049    }
2050
2051    private void sendPostBindInitialization(
2052            final boolean waitForDisco, final boolean carbonsEnabled) {
2053        features.carbonsEnabled = carbonsEnabled;
2054        features.blockListRequested = false;
2055        synchronized (this.disco) {
2056            this.disco.clear();
2057        }
2058        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
2059        mPendingServiceDiscoveries.set(0);
2060        mWaitForDisco.set(waitForDisco);
2061        lastDiscoStarted = SystemClock.elapsedRealtime();
2062        mXmppConnectionService.scheduleWakeUpCall(
2063                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2064        final Element caps = streamFeatures.findChild("c");
2065        final String hash = caps == null ? null : caps.getAttribute("hash");
2066        final String ver = caps == null ? null : caps.getAttribute("ver");
2067        ServiceDiscoveryResult discoveryResult = null;
2068        if (hash != null && ver != null) {
2069            discoveryResult =
2070                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2071        }
2072        final boolean requestDiscoItemsFirst =
2073                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
2074        if (requestDiscoItemsFirst) {
2075            sendServiceDiscoveryItems(account.getDomain());
2076        }
2077        if (discoveryResult == null) {
2078            sendServiceDiscoveryInfo(account.getDomain());
2079        } else {
2080            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
2081            disco.put(account.getDomain(), discoveryResult);
2082        }
2083        discoverMamPreferences();
2084        sendServiceDiscoveryInfo(account.getJid().asBareJid());
2085        if (!requestDiscoItemsFirst) {
2086            sendServiceDiscoveryItems(account.getDomain());
2087        }
2088
2089        if (!mWaitForDisco.get()) {
2090            finalizeBind();
2091        }
2092        this.lastSessionStarted = SystemClock.elapsedRealtime();
2093    }
2094
2095    private void sendServiceDiscoveryInfo(final Jid jid) {
2096        mPendingServiceDiscoveries.incrementAndGet();
2097        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2098        iq.setTo(jid);
2099        iq.query("http://jabber.org/protocol/disco#info");
2100        this.sendIqPacket(
2101                iq,
2102                (account, packet) -> {
2103                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2104                        boolean advancedStreamFeaturesLoaded;
2105                        synchronized (XmppConnection.this.disco) {
2106                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2107                            if (jid.equals(account.getDomain())) {
2108                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2109                                        result);
2110                            }
2111                            disco.put(jid, result);
2112                            advancedStreamFeaturesLoaded =
2113                                    disco.containsKey(account.getDomain())
2114                                            && disco.containsKey(account.getJid().asBareJid());
2115                        }
2116                        if (advancedStreamFeaturesLoaded
2117                                && (jid.equals(account.getDomain())
2118                                        || jid.equals(account.getJid().asBareJid()))) {
2119                            enableAdvancedStreamFeatures();
2120                        }
2121                    } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2122                        Log.d(
2123                                Config.LOGTAG,
2124                                account.getJid().asBareJid()
2125                                        + ": could not query disco info for "
2126                                        + jid.toString());
2127                        final boolean serverOrAccount =
2128                                jid.equals(account.getDomain())
2129                                        || jid.equals(account.getJid().asBareJid());
2130                        final boolean advancedStreamFeaturesLoaded;
2131                        if (serverOrAccount) {
2132                            synchronized (XmppConnection.this.disco) {
2133                                disco.put(jid, ServiceDiscoveryResult.empty());
2134                                advancedStreamFeaturesLoaded =
2135                                        disco.containsKey(account.getDomain())
2136                                                && disco.containsKey(account.getJid().asBareJid());
2137                            }
2138                        } else {
2139                            advancedStreamFeaturesLoaded = false;
2140                        }
2141                        if (advancedStreamFeaturesLoaded) {
2142                            enableAdvancedStreamFeatures();
2143                        }
2144                    }
2145                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2146                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2147                                && mWaitForDisco.compareAndSet(true, false)) {
2148                            finalizeBind();
2149                        }
2150                    }
2151                });
2152    }
2153
2154    private void discoverMamPreferences() {
2155        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2156        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2157        sendIqPacket(
2158                request,
2159                (account, response) -> {
2160                    if (response.getType() == IqPacket.TYPE.RESULT) {
2161                        Element prefs =
2162                                response.findChild(
2163                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
2164                        isMamPreferenceAlways =
2165                                "always"
2166                                        .equals(
2167                                                prefs == null
2168                                                        ? null
2169                                                        : prefs.getAttribute("default"));
2170                    }
2171                });
2172    }
2173
2174    private void discoverCommands() {
2175        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2176        request.setTo(account.getDomain());
2177        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2178        sendIqPacket(
2179                request,
2180                (account, response) -> {
2181                    if (response.getType() == IqPacket.TYPE.RESULT) {
2182                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2183                        if (query == null) {
2184                            return;
2185                        }
2186                        final HashMap<String, Jid> commands = new HashMap<>();
2187                        for (final Element child : query.getChildren()) {
2188                            if ("item".equals(child.getName())) {
2189                                final String node = child.getAttribute("node");
2190                                final Jid jid = child.getAttributeAsJid("jid");
2191                                if (node != null && jid != null) {
2192                                    commands.put(node, jid);
2193                                }
2194                            }
2195                        }
2196                        synchronized (this.commands) {
2197                            this.commands.clear();
2198                            this.commands.putAll(commands);
2199                        }
2200                    }
2201                });
2202    }
2203
2204    public boolean isMamPreferenceAlways() {
2205        return isMamPreferenceAlways;
2206    }
2207
2208    private void finalizeBind() {
2209        this.offlineMessagesRetrieved = false;
2210        if (bindListener != null) {
2211            bindListener.onBind(account);
2212        }
2213        changeStatusToOnline();
2214    }
2215
2216    private void enableAdvancedStreamFeatures() {
2217        if (getFeatures().blocking() && !features.blockListRequested) {
2218            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2219            this.sendIqPacket(
2220                    getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
2221        }
2222        for (final OnAdvancedStreamFeaturesLoaded listener :
2223                advancedStreamFeaturesLoadedListeners) {
2224            listener.onAdvancedStreamFeaturesAvailable(account);
2225        }
2226        if (getFeatures().carbons() && !features.carbonsEnabled) {
2227            sendEnableCarbons();
2228        }
2229        if (getFeatures().commands()) {
2230            discoverCommands();
2231        }
2232    }
2233
2234    private void sendServiceDiscoveryItems(final Jid server) {
2235        mPendingServiceDiscoveries.incrementAndGet();
2236        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2237        iq.setTo(server.getDomain());
2238        iq.query("http://jabber.org/protocol/disco#items");
2239        this.sendIqPacket(
2240                iq,
2241                (account, packet) -> {
2242                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2243                        final HashSet<Jid> items = new HashSet<>();
2244                        final List<Element> elements = packet.query().getChildren();
2245                        for (final Element element : elements) {
2246                            if (element.getName().equals("item")) {
2247                                final Jid jid =
2248                                        InvalidJid.getNullForInvalid(
2249                                                element.getAttributeAsJid("jid"));
2250                                if (jid != null && !jid.equals(account.getDomain())) {
2251                                    items.add(jid);
2252                                }
2253                            }
2254                        }
2255                        for (Jid jid : items) {
2256                            sendServiceDiscoveryInfo(jid);
2257                        }
2258                    } else {
2259                        Log.d(
2260                                Config.LOGTAG,
2261                                account.getJid().asBareJid()
2262                                        + ": could not query disco items of "
2263                                        + server);
2264                    }
2265                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2266                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2267                                && mWaitForDisco.compareAndSet(true, false)) {
2268                            finalizeBind();
2269                        }
2270                    }
2271                });
2272    }
2273
2274    private void sendEnableCarbons() {
2275        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2276        iq.addChild("enable", Namespace.CARBONS);
2277        this.sendIqPacket(
2278                iq,
2279                (account, packet) -> {
2280                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2281                        Log.d(
2282                                Config.LOGTAG,
2283                                account.getJid().asBareJid() + ": successfully enabled carbons");
2284                        features.carbonsEnabled = true;
2285                    } else {
2286                        Log.d(
2287                                Config.LOGTAG,
2288                                account.getJid().asBareJid()
2289                                        + ": could not enable carbons "
2290                                        + packet);
2291                    }
2292                });
2293    }
2294
2295    private void processStreamError(final Tag currentTag) throws IOException {
2296        final Element streamError = tagReader.readElement(currentTag);
2297        if (streamError == null) {
2298            return;
2299        }
2300        if (streamError.hasChild("conflict")) {
2301            account.setResource(createNewResource());
2302            Log.d(
2303                    Config.LOGTAG,
2304                    account.getJid().asBareJid()
2305                            + ": switching resource due to conflict ("
2306                            + account.getResource()
2307                            + ")");
2308            throw new IOException();
2309        } else if (streamError.hasChild("host-unknown")) {
2310            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2311        } else if (streamError.hasChild("policy-violation")) {
2312            this.lastConnect = SystemClock.elapsedRealtime();
2313            final String text = streamError.findChildContent("text");
2314            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2315            failPendingMessages(text);
2316            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2317        } else if (streamError.hasChild("see-other-host")) {
2318            final String seeOtherHost = streamError.findChildContent("see-other-host");
2319            final Resolver.Result currentResolverResult = this.currentResolverResult;
2320            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2321                Log.d(
2322                        Config.LOGTAG,
2323                        account.getJid().asBareJid() + ": stream error " + streamError);
2324                throw new StateChangingException(Account.State.STREAM_ERROR);
2325            }
2326            Log.d(
2327                    Config.LOGTAG,
2328                    account.getJid().asBareJid()
2329                            + ": see other host: "
2330                            + seeOtherHost
2331                            + " "
2332                            + currentResolverResult);
2333            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2334            if (seeOtherResult != null) {
2335                this.seeOtherHostResolverResult = seeOtherResult;
2336                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2337            } else {
2338                throw new StateChangingException(Account.State.STREAM_ERROR);
2339            }
2340        } else {
2341            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2342            throw new StateChangingException(Account.State.STREAM_ERROR);
2343        }
2344    }
2345
2346    private void failPendingMessages(final String error) {
2347        synchronized (this.mStanzaQueue) {
2348            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2349                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
2350                if (stanza instanceof MessagePacket packet) {
2351                    final String id = packet.getId();
2352                    final Jid to = packet.getTo();
2353                    mXmppConnectionService.markMessage(
2354                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2355                }
2356            }
2357        }
2358    }
2359
2360    private boolean establishStream(final SSLSockets.Version sslVersion)
2361            throws IOException, InterruptedException {
2362        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2363        final SaslMechanism quickStartMechanism;
2364        if (secureConnection) {
2365            quickStartMechanism =
2366                    SaslMechanism.ensureAvailable(account.getQuickStartMechanism(), sslVersion);
2367        } else {
2368            quickStartMechanism = null;
2369        }
2370        if (secureConnection
2371                && Config.QUICKSTART_ENABLED
2372                && quickStartMechanism != null
2373                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2374            mXmppConnectionService.restoredFromDatabaseLatch.await();
2375            this.loginInfo =
2376                    new LoginInfo(
2377                            quickStartMechanism,
2378                            SaslMechanism.Version.SASL_2,
2379                            Bind2.QUICKSTART_FEATURES);
2380            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2381            final Element authenticate =
2382                    generateAuthenticationRequest(
2383                            quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2384                            usingFast);
2385            authenticate.setAttribute("mechanism", quickStartMechanism.getMechanism());
2386            sendStartStream(true, false);
2387            synchronized (this.mStanzaQueue) {
2388                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2389                tagWriter.writeElement(authenticate);
2390            }
2391            Log.d(
2392                    Config.LOGTAG,
2393                    account.getJid().toString()
2394                            + ": quick start with "
2395                            + quickStartMechanism.getMechanism());
2396            return true;
2397        } else {
2398            sendStartStream(secureConnection, true);
2399            return false;
2400        }
2401    }
2402
2403    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2404        final Tag stream = Tag.start("stream:stream");
2405        stream.setAttribute("to", account.getServer());
2406        if (from) {
2407            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2408        }
2409        stream.setAttribute("version", "1.0");
2410        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2411        stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2412        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2413        tagWriter.writeTag(stream, flush);
2414    }
2415
2416    private String createNewResource() {
2417        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2418    }
2419
2420    private String nextRandomId() {
2421        return nextRandomId(false);
2422    }
2423
2424    private String nextRandomId(final boolean s) {
2425        return CryptoHelper.random(s ? 3 : 9);
2426    }
2427
2428    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2429        packet.setFrom(account.getJid());
2430        return this.sendUnmodifiedIqPacket(packet, callback, false);
2431    }
2432
2433    public synchronized String sendUnmodifiedIqPacket(
2434            final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2435        if (packet.getId() == null) {
2436            packet.setAttribute("id", nextRandomId());
2437        }
2438        if (callback != null) {
2439            synchronized (this.packetCallbacks) {
2440                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2441            }
2442        }
2443        this.sendPacket(packet, force);
2444        return packet.getId();
2445    }
2446
2447    public void sendMessagePacket(final MessagePacket packet) {
2448        this.sendPacket(packet);
2449    }
2450
2451    public void sendPresencePacket(final PresencePacket packet) {
2452        this.sendPacket(packet);
2453    }
2454
2455    private synchronized void sendPacket(final AbstractStanza packet) {
2456        sendPacket(packet, false);
2457    }
2458
2459    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2460        if (stanzasSent == Integer.MAX_VALUE) {
2461            resetStreamId();
2462            disconnect(true);
2463            return;
2464        }
2465        synchronized (this.mStanzaQueue) {
2466            if (force || isBound) {
2467                tagWriter.writeStanzaAsync(packet);
2468            } else {
2469                Log.d(
2470                        Config.LOGTAG,
2471                        account.getJid().asBareJid()
2472                                + " do not write stanza to unbound stream "
2473                                + packet.toString());
2474            }
2475            if (packet instanceof AbstractAcknowledgeableStanza stanza) {
2476                if (this.mStanzaQueue.size() != 0) {
2477                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2478                    if (currentHighestKey != stanzasSent) {
2479                        throw new AssertionError("Stanza count messed up");
2480                    }
2481                }
2482
2483                ++stanzasSent;
2484                if (Config.EXTENDED_SM_LOGGING) {
2485                    Log.d(
2486                            Config.LOGTAG,
2487                            account.getJid().asBareJid()
2488                                    + ": counting outbound "
2489                                    + packet.getName()
2490                                    + " as #"
2491                                    + stanzasSent);
2492                }
2493                this.mStanzaQueue.append(stanzasSent, stanza);
2494                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2495                    if (Config.EXTENDED_SM_LOGGING) {
2496                        Log.d(
2497                                Config.LOGTAG,
2498                                account.getJid().asBareJid()
2499                                        + ": requesting ack for message stanza #"
2500                                        + stanzasSent);
2501                    }
2502                    tagWriter.writeStanzaAsync(new RequestPacket());
2503                }
2504            }
2505        }
2506    }
2507
2508    public void sendPing() {
2509        if (!r()) {
2510            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2511            iq.setFrom(account.getJid());
2512            iq.addChild("ping", Namespace.PING);
2513            this.sendIqPacket(iq, null);
2514        }
2515        this.lastPingSent = SystemClock.elapsedRealtime();
2516    }
2517
2518    public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2519        this.messageListener = listener;
2520    }
2521
2522    public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2523        this.unregisteredIqListener = listener;
2524    }
2525
2526    public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2527        this.presenceListener = listener;
2528    }
2529
2530    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2531        this.jingleListener = listener;
2532    }
2533
2534    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2535        this.statusListener = listener;
2536    }
2537
2538    public void setOnBindListener(final OnBindListener listener) {
2539        this.bindListener = listener;
2540    }
2541
2542    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2543        this.acknowledgedListener = listener;
2544    }
2545
2546    public void addOnAdvancedStreamFeaturesAvailableListener(
2547            final OnAdvancedStreamFeaturesLoaded listener) {
2548        this.advancedStreamFeaturesLoadedListeners.add(listener);
2549    }
2550
2551    private void forceCloseSocket() {
2552        FileBackend.close(this.socket);
2553        FileBackend.close(this.tagReader);
2554    }
2555
2556    public void interrupt() {
2557        if (this.mThread != null) {
2558            this.mThread.interrupt();
2559        }
2560    }
2561
2562    public void disconnect(final boolean force) {
2563        interrupt();
2564        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2565        if (force) {
2566            forceCloseSocket();
2567        } else {
2568            final TagWriter currentTagWriter = this.tagWriter;
2569            if (currentTagWriter.isActive()) {
2570                currentTagWriter.finish();
2571                final Socket currentSocket = this.socket;
2572                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2573                try {
2574                    currentTagWriter.await(1, TimeUnit.SECONDS);
2575                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2576                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2577                    if (streamCountDownLatch != null) {
2578                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2579                            Log.d(
2580                                    Config.LOGTAG,
2581                                    account.getJid().asBareJid() + ": remote ended stream");
2582                        } else {
2583                            Log.d(
2584                                    Config.LOGTAG,
2585                                    account.getJid().asBareJid()
2586                                            + ": remote has not closed socket. force closing");
2587                        }
2588                    }
2589                } catch (InterruptedException e) {
2590                    Log.d(
2591                            Config.LOGTAG,
2592                            account.getJid().asBareJid()
2593                                    + ": interrupted while gracefully closing stream");
2594                } catch (final IOException e) {
2595                    Log.d(
2596                            Config.LOGTAG,
2597                            account.getJid().asBareJid()
2598                                    + ": io exception during disconnect ("
2599                                    + e.getMessage()
2600                                    + ")");
2601                } finally {
2602                    FileBackend.close(currentSocket);
2603                }
2604            } else {
2605                forceCloseSocket();
2606            }
2607        }
2608    }
2609
2610    private void resetStreamId() {
2611        this.streamId = null;
2612        this.boundStreamFeatures = null;
2613    }
2614
2615    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2616        synchronized (this.disco) {
2617            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2618            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2619                if (cursor.getValue().getFeatures().contains(feature)) {
2620                    items.add(cursor);
2621                }
2622            }
2623            return items;
2624        }
2625    }
2626
2627    public Jid findDiscoItemByFeature(final String feature) {
2628        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2629        if (items.size() >= 1) {
2630            return items.get(0).getKey();
2631        }
2632        return null;
2633    }
2634
2635    public boolean r() {
2636        if (getFeatures().sm()) {
2637            this.tagWriter.writeStanzaAsync(new RequestPacket());
2638            return true;
2639        } else {
2640            return false;
2641        }
2642    }
2643
2644    public List<String> getMucServersWithholdAccount() {
2645        final List<String> servers = getMucServers();
2646        servers.remove(account.getDomain().toEscapedString());
2647        return servers;
2648    }
2649
2650    public List<String> getMucServers() {
2651        List<String> servers = new ArrayList<>();
2652        synchronized (this.disco) {
2653            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2654                final ServiceDiscoveryResult value = cursor.getValue();
2655                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2656                        && value.hasIdentity("conference", "text")
2657                        && !value.getFeatures().contains("jabber:iq:gateway")
2658                        && !value.hasIdentity("conference", "irc")) {
2659                    servers.add(cursor.getKey().toString());
2660                }
2661            }
2662        }
2663        return servers;
2664    }
2665
2666    public String getMucServer() {
2667        List<String> servers = getMucServers();
2668        return servers.size() > 0 ? servers.get(0) : null;
2669    }
2670
2671    public int getTimeToNextAttempt(final boolean aggressive) {
2672        final int interval;
2673        if (aggressive) {
2674            interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2675        } else {
2676            final int additionalTime =
2677                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2678            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2679        }
2680        final int secondsSinceLast =
2681                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2682        return interval - secondsSinceLast;
2683    }
2684
2685    public int getAttempt() {
2686        return this.attempt;
2687    }
2688
2689    public Features getFeatures() {
2690        return this.features;
2691    }
2692
2693    public long getLastSessionEstablished() {
2694        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2695        return System.currentTimeMillis() - diff;
2696    }
2697
2698    public long getLastConnect() {
2699        return this.lastConnect;
2700    }
2701
2702    public long getLastPingSent() {
2703        return this.lastPingSent;
2704    }
2705
2706    public long getLastDiscoStarted() {
2707        return this.lastDiscoStarted;
2708    }
2709
2710    public long getLastPacketReceived() {
2711        return this.lastPacketReceived;
2712    }
2713
2714    public void sendActive() {
2715        this.sendPacket(new ActivePacket());
2716    }
2717
2718    public void sendInactive() {
2719        this.sendPacket(new InactivePacket());
2720    }
2721
2722    public void resetAttemptCount(boolean resetConnectTime) {
2723        this.attempt = 0;
2724        if (resetConnectTime) {
2725            this.lastConnect = 0;
2726        }
2727    }
2728
2729    public void setInteractive(boolean interactive) {
2730        this.mInteractive = interactive;
2731    }
2732
2733    private IqGenerator getIqGenerator() {
2734        return mXmppConnectionService.getIqGenerator();
2735    }
2736
2737    public void trackOfflineMessageRetrieval(boolean trackOfflineMessageRetrieval) {
2738        if (trackOfflineMessageRetrieval) {
2739            final IqPacket iqPing = new IqPacket(IqPacket.TYPE.GET);
2740            iqPing.addChild("ping", Namespace.PING);
2741            this.sendIqPacket(
2742                    iqPing,
2743                    (a, response) -> {
2744                        Log.d(
2745                                Config.LOGTAG,
2746                                account.getJid().asBareJid()
2747                                        + ": got ping response after sending initial presence");
2748                        XmppConnection.this.offlineMessagesRetrieved = true;
2749                    });
2750        } else {
2751            this.offlineMessagesRetrieved = true;
2752        }
2753    }
2754
2755    public boolean isOfflineMessagesRetrieved() {
2756        return this.offlineMessagesRetrieved;
2757    }
2758
2759    private class MyKeyManager implements X509KeyManager {
2760        @Override
2761        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2762            return account.getPrivateKeyAlias();
2763        }
2764
2765        @Override
2766        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2767            return null;
2768        }
2769
2770        @Override
2771        public X509Certificate[] getCertificateChain(String alias) {
2772            Log.d(Config.LOGTAG, "getting certificate chain");
2773            try {
2774                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2775            } catch (final Exception e) {
2776                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2777                return new X509Certificate[0];
2778            }
2779        }
2780
2781        @Override
2782        public String[] getClientAliases(String s, Principal[] principals) {
2783            final String alias = account.getPrivateKeyAlias();
2784            return alias != null ? new String[] {alias} : new String[0];
2785        }
2786
2787        @Override
2788        public String[] getServerAliases(String s, Principal[] principals) {
2789            return new String[0];
2790        }
2791
2792        @Override
2793        public PrivateKey getPrivateKey(String alias) {
2794            try {
2795                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2796            } catch (Exception e) {
2797                return null;
2798            }
2799        }
2800    }
2801
2802    private static class LoginInfo {
2803        public final SaslMechanism saslMechanism;
2804        public final SaslMechanism.Version saslVersion;
2805        public final List<String> inlineBindFeatures;
2806        public final AtomicBoolean success = new AtomicBoolean(false);
2807
2808        private LoginInfo(
2809                final SaslMechanism saslMechanism,
2810                final SaslMechanism.Version saslVersion,
2811                final Collection<String> inlineBindFeatures) {
2812            Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2813            Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2814            this.saslMechanism = saslMechanism;
2815            this.saslVersion = saslVersion;
2816            this.inlineBindFeatures =
2817                    inlineBindFeatures == null
2818                            ? Collections.emptyList()
2819                            : ImmutableList.copyOf(inlineBindFeatures);
2820        }
2821
2822        public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2823            return loginInfo == null ? null : loginInfo.saslMechanism;
2824        }
2825
2826        public void success(final String challenge, final SSLSocket sslSocket)
2827                throws SaslMechanism.AuthenticationException {
2828            final var response = this.saslMechanism.getResponse(challenge, sslSocket);
2829            if (!Strings.isNullOrEmpty(response)) {
2830                throw new SaslMechanism.AuthenticationException(
2831                        "processing success yielded another response");
2832            }
2833            if (this.success.compareAndSet(false, true)) {
2834                return;
2835            }
2836            throw new SaslMechanism.AuthenticationException("Process 'success' twice");
2837        }
2838
2839        public static boolean isSuccess(final LoginInfo loginInfo) {
2840            return loginInfo != null && loginInfo.success.get();
2841        }
2842    }
2843
2844    private static class StreamId {
2845        public final String id;
2846        public final Resolver.Result location;
2847
2848        private StreamId(String id, Resolver.Result location) {
2849            this.id = id;
2850            this.location = location;
2851        }
2852
2853        @NonNull
2854        @Override
2855        public String toString() {
2856            return MoreObjects.toStringHelper(this)
2857                    .add("id", id)
2858                    .add("location", location)
2859                    .toString();
2860        }
2861    }
2862
2863    private static class StateChangingError extends Error {
2864        private final Account.State state;
2865
2866        public StateChangingError(Account.State state) {
2867            this.state = state;
2868        }
2869    }
2870
2871    private static class StateChangingException extends IOException {
2872        private final Account.State state;
2873
2874        public StateChangingException(Account.State state) {
2875            this.state = state;
2876        }
2877    }
2878
2879    public class Features {
2880        XmppConnection connection;
2881        private boolean carbonsEnabled = false;
2882        private boolean encryptionEnabled = false;
2883        private boolean blockListRequested = false;
2884
2885        public Features(final XmppConnection connection) {
2886            this.connection = connection;
2887        }
2888
2889        private boolean hasDiscoFeature(final Jid server, final String feature) {
2890            synchronized (XmppConnection.this.disco) {
2891                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2892                return sdr != null && sdr.getFeatures().contains(feature);
2893            }
2894        }
2895
2896        public boolean carbons() {
2897            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2898        }
2899
2900        public boolean commands() {
2901            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2902        }
2903
2904        public boolean easyOnboardingInvites() {
2905            synchronized (commands) {
2906                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2907            }
2908        }
2909
2910        public boolean bookmarksConversion() {
2911            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2912                    && pepPublishOptions();
2913        }
2914
2915        public boolean blocking() {
2916            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2917        }
2918
2919        public boolean spamReporting() {
2920            return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
2921        }
2922
2923        public boolean flexibleOfflineMessageRetrieval() {
2924            return hasDiscoFeature(
2925                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2926        }
2927
2928        public boolean register() {
2929            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2930        }
2931
2932        public boolean invite() {
2933            return connection.streamFeatures != null
2934                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2935        }
2936
2937        public boolean sm() {
2938            return streamId != null
2939                    || (connection.streamFeatures != null
2940                            && connection.streamFeatures.hasChild(
2941                                    "sm", Namespace.STREAM_MANAGEMENT));
2942        }
2943
2944        public boolean csi() {
2945            return connection.streamFeatures != null
2946                    && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2947        }
2948
2949        public boolean pep() {
2950            synchronized (XmppConnection.this.disco) {
2951                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2952                return info != null && info.hasIdentity("pubsub", "pep");
2953            }
2954        }
2955
2956        public boolean pepPersistent() {
2957            synchronized (XmppConnection.this.disco) {
2958                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2959                return info != null
2960                        && info.getFeatures()
2961                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
2962            }
2963        }
2964
2965        public boolean pepPublishOptions() {
2966            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2967        }
2968
2969        public boolean pepOmemoWhitelisted() {
2970            return hasDiscoFeature(
2971                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2972        }
2973
2974        public boolean mam() {
2975            return MessageArchiveService.Version.has(getAccountFeatures());
2976        }
2977
2978        public List<String> getAccountFeatures() {
2979            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2980            return result == null ? Collections.emptyList() : result.getFeatures();
2981        }
2982
2983        public boolean push() {
2984            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2985                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2986        }
2987
2988        public boolean rosterVersioning() {
2989            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2990        }
2991
2992        public void setBlockListRequested(boolean value) {
2993            this.blockListRequested = value;
2994        }
2995
2996        public boolean httpUpload(long filesize) {
2997            if (Config.DISABLE_HTTP_UPLOAD) {
2998                return false;
2999            } else {
3000                for (String namespace :
3001                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3002                    List<Entry<Jid, ServiceDiscoveryResult>> items =
3003                            findDiscoItemsByFeature(namespace);
3004                    if (items.size() > 0) {
3005                        try {
3006                            long maxsize =
3007                                    Long.parseLong(
3008                                            items.get(0)
3009                                                    .getValue()
3010                                                    .getExtendedDiscoInformation(
3011                                                            namespace, "max-file-size"));
3012                            if (filesize <= maxsize) {
3013                                return true;
3014                            } else {
3015                                Log.d(
3016                                        Config.LOGTAG,
3017                                        account.getJid().asBareJid()
3018                                                + ": http upload is not available for files with size "
3019                                                + filesize
3020                                                + " (max is "
3021                                                + maxsize
3022                                                + ")");
3023                                return false;
3024                            }
3025                        } catch (Exception e) {
3026                            return true;
3027                        }
3028                    }
3029                }
3030                return false;
3031            }
3032        }
3033
3034        public boolean useLegacyHttpUpload() {
3035            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
3036                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
3037        }
3038
3039        public long getMaxHttpUploadSize() {
3040            for (String namespace :
3041                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3042                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
3043                if (items.size() > 0) {
3044                    try {
3045                        return Long.parseLong(
3046                                items.get(0)
3047                                        .getValue()
3048                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
3049                    } catch (Exception e) {
3050                        // ignored
3051                    }
3052                }
3053            }
3054            return -1;
3055        }
3056
3057        public boolean stanzaIds() {
3058            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3059        }
3060
3061        public boolean bookmarks2() {
3062            return pepPublishOptions()
3063                    && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3064        }
3065
3066        public boolean externalServiceDiscovery() {
3067            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3068        }
3069    }
3070}