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