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