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