XmppConnection.java

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