XmppConnection.java

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