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