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