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