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            final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1294            final boolean sm = inline != null && inline.hasChild("sm", "urn:xmpp:sm:3");
1295            final Collection<String> bindFeatures = bindFeatures(inline);
1296            authenticate = generateAuthenticationRequest(firstMessage, bindFeatures, sm);
1297        } else {
1298            throw new AssertionError("Missing implementation for " + version);
1299        }
1300
1301        Log.d(
1302                Config.LOGTAG,
1303                account.getJid().toString()
1304                        + ": Authenticating with "
1305                        + version
1306                        + "/"
1307                        + saslMechanism.getMechanism());
1308        authenticate.setAttribute("mechanism", saslMechanism.getMechanism());
1309        tagWriter.writeElement(authenticate);
1310    }
1311
1312    private static Collection<String> bindFeatures(final Element inline) {
1313        final Element inlineBind2 =
1314                inline != null ? inline.findChild("bind", Namespace.BIND2) : null;
1315        final Element inlineBind2Inline =
1316                inlineBind2 != null ? inlineBind2.findChild("inline", Namespace.BIND2) : null;
1317        if (inlineBind2 == null) {
1318            return null;
1319        }
1320        if (inlineBind2Inline == null) {
1321            return Collections.emptyList();
1322        }
1323        return Collections2.transform(
1324                inlineBind2Inline.getChildren(), c -> c == null ? null : c.getAttribute("var"));
1325    }
1326
1327    private Element generateAuthenticationRequest(
1328            final String firstMessage,
1329            final Collection<String> bind,
1330            final boolean inlineStreamManagement) {
1331        final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1332        if (!Strings.isNullOrEmpty(firstMessage)) {
1333            authenticate.addChild("initial-response").setContent(firstMessage);
1334        }
1335        final Element userAgent = authenticate.addChild("user-agent");
1336        userAgent.setAttribute("id", account.getUuid());
1337        userAgent
1338                .addChild("software")
1339                .setContent(mXmppConnectionService.getString(R.string.app_name));
1340        if (!PhoneHelper.isEmulator()) {
1341            userAgent
1342                    .addChild("device")
1343                    .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1344        }
1345        if (bind != null) {
1346            authenticate.addChild(generateBindRequest(bind));
1347        }
1348        if (inlineStreamManagement && streamId != null) {
1349            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived);
1350            this.mSmCatchupMessageCounter.set(0);
1351            this.mWaitingForSmCatchup.set(true);
1352            authenticate.addChild(resume);
1353        }
1354        return authenticate;
1355    }
1356
1357    private Element generateBindRequest(final Collection<String> bindFeatures) {
1358        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1359        final Element bind = new Element("bind", Namespace.BIND2);
1360        bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1361        final Element features = bind.addChild("features");
1362        if (bindFeatures.contains(Namespace.CARBONS)) {
1363            features.addChild("enable", Namespace.CARBONS);
1364        }
1365        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1366            features.addChild(new EnablePacket());
1367        }
1368        return bind;
1369    }
1370
1371    private void register() {
1372        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1373        if (preAuth != null && features.invite()) {
1374            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1375            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1376            sendUnmodifiedIqPacket(
1377                    preAuthRequest,
1378                    (account, response) -> {
1379                        if (response.getType() == IqPacket.TYPE.RESULT) {
1380                            sendRegistryRequest();
1381                        } else {
1382                            final String error = response.getErrorCondition();
1383                            Log.d(
1384                                    Config.LOGTAG,
1385                                    account.getJid().asBareJid()
1386                                            + ": failed to pre auth. "
1387                                            + error);
1388                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1389                        }
1390                    },
1391                    true);
1392        } else {
1393            sendRegistryRequest();
1394        }
1395    }
1396
1397    private void sendRegistryRequest() {
1398        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1399        register.query(Namespace.REGISTER);
1400        register.setTo(account.getDomain());
1401        sendUnmodifiedIqPacket(
1402                register,
1403                (account, packet) -> {
1404                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1405                        return;
1406                    }
1407                    if (packet.getType() == IqPacket.TYPE.ERROR) {
1408                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1409                    }
1410                    final Element query = packet.query(Namespace.REGISTER);
1411                    if (query.hasChild("username") && (query.hasChild("password"))) {
1412                        final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1413                        final Element username =
1414                                new Element("username").setContent(account.getUsername());
1415                        final Element password =
1416                                new Element("password").setContent(account.getPassword());
1417                        register1.query(Namespace.REGISTER).addChild(username);
1418                        register1.query().addChild(password);
1419                        register1.setFrom(account.getJid().asBareJid());
1420                        sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1421                    } else if (query.hasChild("x", Namespace.DATA)) {
1422                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1423                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1424                        final String id = packet.getId();
1425                        InputStream is;
1426                        if (blob != null) {
1427                            try {
1428                                final String base64Blob = blob.getContent();
1429                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1430                                is = new ByteArrayInputStream(strBlob);
1431                            } catch (Exception e) {
1432                                is = null;
1433                            }
1434                        } else {
1435                            final boolean useTor =
1436                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1437                            try {
1438                                final String url = data.getValue("url");
1439                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1440                                if (url != null) {
1441                                    is = HttpConnectionManager.open(url, useTor);
1442                                } else if (fallbackUrl != null) {
1443                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1444                                } else {
1445                                    is = null;
1446                                }
1447                            } catch (final IOException e) {
1448                                Log.d(
1449                                        Config.LOGTAG,
1450                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1451                                        e);
1452                                is = null;
1453                            }
1454                        }
1455
1456                        if (is != null) {
1457                            Bitmap captcha = BitmapFactory.decodeStream(is);
1458                            try {
1459                                if (mXmppConnectionService.displayCaptchaRequest(
1460                                        account, id, data, captcha)) {
1461                                    return;
1462                                }
1463                            } catch (Exception e) {
1464                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1465                            }
1466                        }
1467                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1468                    } else if (query.hasChild("instructions")
1469                            || query.hasChild("x", Namespace.OOB)) {
1470                        final String instructions = query.findChildContent("instructions");
1471                        final Element oob = query.findChild("x", Namespace.OOB);
1472                        final String url = oob == null ? null : oob.findChildContent("url");
1473                        if (url != null) {
1474                            setAccountCreationFailed(url);
1475                        } else if (instructions != null) {
1476                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1477                            if (matcher.find()) {
1478                                setAccountCreationFailed(
1479                                        instructions.substring(matcher.start(), matcher.end()));
1480                            }
1481                        }
1482                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1483                    }
1484                },
1485                true);
1486    }
1487
1488    private void setAccountCreationFailed(final String url) {
1489        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1490        if (httpUrl != null && httpUrl.isHttps()) {
1491            this.redirectionUrl = httpUrl;
1492            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1493        }
1494        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1495    }
1496
1497    public HttpUrl getRedirectionUrl() {
1498        return this.redirectionUrl;
1499    }
1500
1501    public void resetEverything() {
1502        resetAttemptCount(true);
1503        resetStreamId();
1504        clearIqCallbacks();
1505        this.stanzasSent = 0;
1506        mStanzaQueue.clear();
1507        this.redirectionUrl = null;
1508        synchronized (this.disco) {
1509            disco.clear();
1510        }
1511        synchronized (this.commands) {
1512            this.commands.clear();
1513        }
1514    }
1515
1516    private void sendBindRequest() {
1517        try {
1518            mXmppConnectionService.restoredFromDatabaseLatch.await();
1519        } catch (InterruptedException e) {
1520            Log.d(
1521                    Config.LOGTAG,
1522                    account.getJid().asBareJid()
1523                            + ": interrupted while waiting for DB restore during bind");
1524            return;
1525        }
1526        clearIqCallbacks();
1527        if (account.getJid().isBareJid()) {
1528            account.setResource(this.createNewResource());
1529        } else {
1530            fixResource(mXmppConnectionService, account);
1531        }
1532        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1533        final String resource =
1534                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1535        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1536        this.sendUnmodifiedIqPacket(
1537                iq,
1538                (account, packet) -> {
1539                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1540                        return;
1541                    }
1542                    final Element bind = packet.findChild("bind");
1543                    if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1544                        isBound = true;
1545                        final Element jid = bind.findChild("jid");
1546                        if (jid != null && jid.getContent() != null) {
1547                            try {
1548                                Jid assignedJid = Jid.ofEscaped(jid.getContent());
1549                                if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1550                                    Log.d(
1551                                            Config.LOGTAG,
1552                                            account.getJid().asBareJid()
1553                                                    + ": server tried to re-assign domain to "
1554                                                    + assignedJid.getDomain());
1555                                    throw new StateChangingError(Account.State.BIND_FAILURE);
1556                                }
1557                                if (account.setJid(assignedJid)) {
1558                                    Log.d(
1559                                            Config.LOGTAG,
1560                                            account.getJid().asBareJid()
1561                                                    + ": jid changed during bind. updating database");
1562                                    mXmppConnectionService.databaseBackend.updateAccount(account);
1563                                }
1564                                if (streamFeatures.hasChild("session")
1565                                        && !streamFeatures
1566                                                .findChild("session")
1567                                                .hasChild("optional")) {
1568                                    sendStartSession();
1569                                } else {
1570                                    final boolean waitForDisco = enableStreamManagement();
1571                                    sendPostBindInitialization(waitForDisco, false);
1572                                }
1573                                return;
1574                            } catch (final IllegalArgumentException e) {
1575                                Log.d(
1576                                        Config.LOGTAG,
1577                                        account.getJid().asBareJid()
1578                                                + ": server reported invalid jid ("
1579                                                + jid.getContent()
1580                                                + ") on bind");
1581                            }
1582                        } else {
1583                            Log.d(
1584                                    Config.LOGTAG,
1585                                    account.getJid()
1586                                            + ": disconnecting because of bind failure. (no jid)");
1587                        }
1588                    } else {
1589                        Log.d(
1590                                Config.LOGTAG,
1591                                account.getJid()
1592                                        + ": disconnecting because of bind failure ("
1593                                        + packet);
1594                    }
1595                    final Element error = packet.findChild("error");
1596                    if (packet.getType() == IqPacket.TYPE.ERROR
1597                            && error != null
1598                            && error.hasChild("conflict")) {
1599                        account.setResource(createNewResource());
1600                    }
1601                    throw new StateChangingError(Account.State.BIND_FAILURE);
1602                },
1603                true);
1604    }
1605
1606    private void clearIqCallbacks() {
1607        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1608        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1609        synchronized (this.packetCallbacks) {
1610            if (this.packetCallbacks.size() == 0) {
1611                return;
1612            }
1613            Log.d(
1614                    Config.LOGTAG,
1615                    account.getJid().asBareJid()
1616                            + ": clearing "
1617                            + this.packetCallbacks.size()
1618                            + " iq callbacks");
1619            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1620                    this.packetCallbacks.values().iterator();
1621            while (iterator.hasNext()) {
1622                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1623                callbacks.add(entry.second);
1624                iterator.remove();
1625            }
1626        }
1627        for (OnIqPacketReceived callback : callbacks) {
1628            try {
1629                callback.onIqPacketReceived(account, failurePacket);
1630            } catch (StateChangingError error) {
1631                Log.d(
1632                        Config.LOGTAG,
1633                        account.getJid().asBareJid()
1634                                + ": caught StateChangingError("
1635                                + error.state.toString()
1636                                + ") while clearing callbacks");
1637                // ignore
1638            }
1639        }
1640        Log.d(
1641                Config.LOGTAG,
1642                account.getJid().asBareJid()
1643                        + ": done clearing iq callbacks. "
1644                        + this.packetCallbacks.size()
1645                        + " left");
1646    }
1647
1648    public void sendDiscoTimeout() {
1649        if (mWaitForDisco.compareAndSet(true, false)) {
1650            Log.d(
1651                    Config.LOGTAG,
1652                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1653            finalizeBind();
1654        }
1655    }
1656
1657    private void sendStartSession() {
1658        Log.d(
1659                Config.LOGTAG,
1660                account.getJid().asBareJid() + ": sending legacy session to outdated server");
1661        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1662        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1663        this.sendUnmodifiedIqPacket(
1664                startSession,
1665                (account, packet) -> {
1666                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1667                        final boolean waitForDisco = enableStreamManagement();
1668                        sendPostBindInitialization(waitForDisco, false);
1669                    } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1670                        throw new StateChangingError(Account.State.SESSION_FAILURE);
1671                    }
1672                },
1673                true);
1674    }
1675
1676    private boolean enableStreamManagement() {
1677        final boolean streamManagement =
1678                this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1679        if (streamManagement) {
1680            synchronized (this.mStanzaQueue) {
1681                final EnablePacket enable = new EnablePacket();
1682                tagWriter.writeStanzaAsync(enable);
1683                stanzasSent = 0;
1684                mStanzaQueue.clear();
1685            }
1686            return true;
1687        } else {
1688            return false;
1689        }
1690    }
1691
1692    private void sendPostBindInitialization(
1693            final boolean waitForDisco, final boolean carbonsEnabled) {
1694        features.carbonsEnabled = carbonsEnabled;
1695        features.blockListRequested = false;
1696        synchronized (this.disco) {
1697            this.disco.clear();
1698        }
1699        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1700        mPendingServiceDiscoveries.set(0);
1701        if (!waitForDisco
1702                || Patches.DISCO_EXCEPTIONS.contains(
1703                        account.getJid().getDomain().toEscapedString())) {
1704            Log.d(
1705                    Config.LOGTAG,
1706                    account.getJid().asBareJid() + ": do not wait for service discovery");
1707            mWaitForDisco.set(false);
1708        } else {
1709            mWaitForDisco.set(true);
1710        }
1711        lastDiscoStarted = SystemClock.elapsedRealtime();
1712        mXmppConnectionService.scheduleWakeUpCall(
1713                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1714        Element caps = streamFeatures.findChild("c");
1715        final String hash = caps == null ? null : caps.getAttribute("hash");
1716        final String ver = caps == null ? null : caps.getAttribute("ver");
1717        ServiceDiscoveryResult discoveryResult = null;
1718        if (hash != null && ver != null) {
1719            discoveryResult =
1720                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1721        }
1722        final boolean requestDiscoItemsFirst =
1723                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1724        if (requestDiscoItemsFirst) {
1725            sendServiceDiscoveryItems(account.getDomain());
1726        }
1727        if (discoveryResult == null) {
1728            sendServiceDiscoveryInfo(account.getDomain());
1729        } else {
1730            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1731            disco.put(account.getDomain(), discoveryResult);
1732        }
1733        discoverMamPreferences();
1734        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1735        if (!requestDiscoItemsFirst) {
1736            sendServiceDiscoveryItems(account.getDomain());
1737        }
1738
1739        if (!mWaitForDisco.get()) {
1740            finalizeBind();
1741        }
1742        this.lastSessionStarted = SystemClock.elapsedRealtime();
1743    }
1744
1745    private void sendServiceDiscoveryInfo(final Jid jid) {
1746        mPendingServiceDiscoveries.incrementAndGet();
1747        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1748        iq.setTo(jid);
1749        iq.query("http://jabber.org/protocol/disco#info");
1750        this.sendIqPacket(
1751                iq,
1752                (account, packet) -> {
1753                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1754                        boolean advancedStreamFeaturesLoaded;
1755                        synchronized (XmppConnection.this.disco) {
1756                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1757                            if (jid.equals(account.getDomain())) {
1758                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
1759                                        result);
1760                            }
1761                            disco.put(jid, result);
1762                            advancedStreamFeaturesLoaded =
1763                                    disco.containsKey(account.getDomain())
1764                                            && disco.containsKey(account.getJid().asBareJid());
1765                        }
1766                        if (advancedStreamFeaturesLoaded
1767                                && (jid.equals(account.getDomain())
1768                                        || jid.equals(account.getJid().asBareJid()))) {
1769                            enableAdvancedStreamFeatures();
1770                        }
1771                    } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1772                        Log.d(
1773                                Config.LOGTAG,
1774                                account.getJid().asBareJid()
1775                                        + ": could not query disco info for "
1776                                        + jid.toString());
1777                        final boolean serverOrAccount =
1778                                jid.equals(account.getDomain())
1779                                        || jid.equals(account.getJid().asBareJid());
1780                        final boolean advancedStreamFeaturesLoaded;
1781                        if (serverOrAccount) {
1782                            synchronized (XmppConnection.this.disco) {
1783                                disco.put(jid, ServiceDiscoveryResult.empty());
1784                                advancedStreamFeaturesLoaded =
1785                                        disco.containsKey(account.getDomain())
1786                                                && disco.containsKey(account.getJid().asBareJid());
1787                            }
1788                        } else {
1789                            advancedStreamFeaturesLoaded = false;
1790                        }
1791                        if (advancedStreamFeaturesLoaded) {
1792                            enableAdvancedStreamFeatures();
1793                        }
1794                    }
1795                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1796                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
1797                                && mWaitForDisco.compareAndSet(true, false)) {
1798                            finalizeBind();
1799                        }
1800                    }
1801                });
1802    }
1803
1804    private void discoverMamPreferences() {
1805        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1806        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1807        sendIqPacket(
1808                request,
1809                (account, response) -> {
1810                    if (response.getType() == IqPacket.TYPE.RESULT) {
1811                        Element prefs =
1812                                response.findChild(
1813                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
1814                        isMamPreferenceAlways =
1815                                "always"
1816                                        .equals(
1817                                                prefs == null
1818                                                        ? null
1819                                                        : prefs.getAttribute("default"));
1820                    }
1821                });
1822    }
1823
1824    private void discoverCommands() {
1825        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1826        request.setTo(account.getDomain());
1827        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1828        sendIqPacket(
1829                request,
1830                (account, response) -> {
1831                    if (response.getType() == IqPacket.TYPE.RESULT) {
1832                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1833                        if (query == null) {
1834                            return;
1835                        }
1836                        final HashMap<String, Jid> commands = new HashMap<>();
1837                        for (final Element child : query.getChildren()) {
1838                            if ("item".equals(child.getName())) {
1839                                final String node = child.getAttribute("node");
1840                                final Jid jid = child.getAttributeAsJid("jid");
1841                                if (node != null && jid != null) {
1842                                    commands.put(node, jid);
1843                                }
1844                            }
1845                        }
1846                        Log.d(Config.LOGTAG, commands.toString());
1847                        synchronized (this.commands) {
1848                            this.commands.clear();
1849                            this.commands.putAll(commands);
1850                        }
1851                    }
1852                });
1853    }
1854
1855    public boolean isMamPreferenceAlways() {
1856        return isMamPreferenceAlways;
1857    }
1858
1859    private void finalizeBind() {
1860        Log.d(
1861                Config.LOGTAG,
1862                account.getJid().asBareJid() + ": online with resource " + account.getResource());
1863        if (bindListener != null) {
1864            bindListener.onBind(account);
1865        }
1866        changeStatus(Account.State.ONLINE);
1867    }
1868
1869    private void enableAdvancedStreamFeatures() {
1870        if (getFeatures().blocking() && !features.blockListRequested) {
1871            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1872            this.sendIqPacket(
1873                    getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1874        }
1875        for (final OnAdvancedStreamFeaturesLoaded listener :
1876                advancedStreamFeaturesLoadedListeners) {
1877            listener.onAdvancedStreamFeaturesAvailable(account);
1878        }
1879        if (getFeatures().carbons() && !features.carbonsEnabled) {
1880            sendEnableCarbons();
1881        }
1882        if (getFeatures().commands()) {
1883            discoverCommands();
1884        }
1885    }
1886
1887    private void sendServiceDiscoveryItems(final Jid server) {
1888        mPendingServiceDiscoveries.incrementAndGet();
1889        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1890        iq.setTo(server.getDomain());
1891        iq.query("http://jabber.org/protocol/disco#items");
1892        this.sendIqPacket(
1893                iq,
1894                (account, packet) -> {
1895                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1896                        final HashSet<Jid> items = new HashSet<>();
1897                        final List<Element> elements = packet.query().getChildren();
1898                        for (final Element element : elements) {
1899                            if (element.getName().equals("item")) {
1900                                final Jid jid =
1901                                        InvalidJid.getNullForInvalid(
1902                                                element.getAttributeAsJid("jid"));
1903                                if (jid != null && !jid.equals(account.getDomain())) {
1904                                    items.add(jid);
1905                                }
1906                            }
1907                        }
1908                        for (Jid jid : items) {
1909                            sendServiceDiscoveryInfo(jid);
1910                        }
1911                    } else {
1912                        Log.d(
1913                                Config.LOGTAG,
1914                                account.getJid().asBareJid()
1915                                        + ": could not query disco items of "
1916                                        + server);
1917                    }
1918                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1919                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
1920                                && mWaitForDisco.compareAndSet(true, false)) {
1921                            finalizeBind();
1922                        }
1923                    }
1924                });
1925    }
1926
1927    private void sendEnableCarbons() {
1928        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1929        iq.addChild("enable", Namespace.CARBONS);
1930        this.sendIqPacket(
1931                iq,
1932                (account, packet) -> {
1933                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1934                        Log.d(
1935                                Config.LOGTAG,
1936                                account.getJid().asBareJid() + ": successfully enabled carbons");
1937                        features.carbonsEnabled = true;
1938                    } else {
1939                        Log.d(
1940                                Config.LOGTAG,
1941                                account.getJid().asBareJid()
1942                                        + ": could not enable carbons "
1943                                        + packet);
1944                    }
1945                });
1946    }
1947
1948    private void processStreamError(final Tag currentTag) throws IOException {
1949        final Element streamError = tagReader.readElement(currentTag);
1950        if (streamError == null) {
1951            return;
1952        }
1953        if (streamError.hasChild("conflict")) {
1954            account.setResource(createNewResource());
1955            Log.d(
1956                    Config.LOGTAG,
1957                    account.getJid().asBareJid()
1958                            + ": switching resource due to conflict ("
1959                            + account.getResource()
1960                            + ")");
1961            throw new IOException();
1962        } else if (streamError.hasChild("host-unknown")) {
1963            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1964        } else if (streamError.hasChild("policy-violation")) {
1965            this.lastConnect = SystemClock.elapsedRealtime();
1966            final String text = streamError.findChildContent("text");
1967            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1968            failPendingMessages(text);
1969            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1970        } else {
1971            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
1972            throw new StateChangingException(Account.State.STREAM_ERROR);
1973        }
1974    }
1975
1976    private void failPendingMessages(final String error) {
1977        synchronized (this.mStanzaQueue) {
1978            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1979                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1980                if (stanza instanceof MessagePacket) {
1981                    final MessagePacket packet = (MessagePacket) stanza;
1982                    final String id = packet.getId();
1983                    final Jid to = packet.getTo();
1984                    mXmppConnectionService.markMessage(
1985                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
1986                }
1987            }
1988        }
1989    }
1990
1991    private void sendStartStream() throws IOException {
1992        final Tag stream = Tag.start("stream:stream");
1993        stream.setAttribute("to", account.getServer());
1994        stream.setAttribute("version", "1.0");
1995        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1996        stream.setAttribute("xmlns", "jabber:client");
1997        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1998        tagWriter.writeTag(stream);
1999    }
2000
2001    private String createNewResource() {
2002        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2003    }
2004
2005    private String nextRandomId() {
2006        return nextRandomId(false);
2007    }
2008
2009    private String nextRandomId(final boolean s) {
2010        return CryptoHelper.random(s ? 3 : 9);
2011    }
2012
2013    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2014        packet.setFrom(account.getJid());
2015        return this.sendUnmodifiedIqPacket(packet, callback, false);
2016    }
2017
2018    public synchronized String sendUnmodifiedIqPacket(
2019            final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2020        if (packet.getId() == null) {
2021            packet.setAttribute("id", nextRandomId());
2022        }
2023        if (callback != null) {
2024            synchronized (this.packetCallbacks) {
2025                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2026            }
2027        }
2028        this.sendPacket(packet, force);
2029        return packet.getId();
2030    }
2031
2032    public void sendMessagePacket(final MessagePacket packet) {
2033        this.sendPacket(packet);
2034    }
2035
2036    public void sendPresencePacket(final PresencePacket packet) {
2037        this.sendPacket(packet);
2038    }
2039
2040    private synchronized void sendPacket(final AbstractStanza packet) {
2041        sendPacket(packet, false);
2042    }
2043
2044    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2045        if (stanzasSent == Integer.MAX_VALUE) {
2046            resetStreamId();
2047            disconnect(true);
2048            return;
2049        }
2050        synchronized (this.mStanzaQueue) {
2051            if (force || isBound) {
2052                tagWriter.writeStanzaAsync(packet);
2053            } else {
2054                Log.d(
2055                        Config.LOGTAG,
2056                        account.getJid().asBareJid()
2057                                + " do not write stanza to unbound stream "
2058                                + packet.toString());
2059            }
2060            if (packet instanceof AbstractAcknowledgeableStanza) {
2061                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
2062
2063                if (this.mStanzaQueue.size() != 0) {
2064                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2065                    if (currentHighestKey != stanzasSent) {
2066                        throw new AssertionError("Stanza count messed up");
2067                    }
2068                }
2069
2070                ++stanzasSent;
2071                this.mStanzaQueue.append(stanzasSent, stanza);
2072                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2073                    if (Config.EXTENDED_SM_LOGGING) {
2074                        Log.d(
2075                                Config.LOGTAG,
2076                                account.getJid().asBareJid()
2077                                        + ": requesting ack for message stanza #"
2078                                        + stanzasSent);
2079                    }
2080                    tagWriter.writeStanzaAsync(new RequestPacket());
2081                }
2082            }
2083        }
2084    }
2085
2086    public void sendPing() {
2087        if (!r()) {
2088            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2089            iq.setFrom(account.getJid());
2090            iq.addChild("ping", Namespace.PING);
2091            this.sendIqPacket(iq, null);
2092        }
2093        this.lastPingSent = SystemClock.elapsedRealtime();
2094    }
2095
2096    public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2097        this.messageListener = listener;
2098    }
2099
2100    public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2101        this.unregisteredIqListener = listener;
2102    }
2103
2104    public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2105        this.presenceListener = listener;
2106    }
2107
2108    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2109        this.jingleListener = listener;
2110    }
2111
2112    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2113        this.statusListener = listener;
2114    }
2115
2116    public void setOnBindListener(final OnBindListener listener) {
2117        this.bindListener = listener;
2118    }
2119
2120    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2121        this.acknowledgedListener = listener;
2122    }
2123
2124    public void addOnAdvancedStreamFeaturesAvailableListener(
2125            final OnAdvancedStreamFeaturesLoaded listener) {
2126        this.advancedStreamFeaturesLoadedListeners.add(listener);
2127    }
2128
2129    private void forceCloseSocket() {
2130        FileBackend.close(this.socket);
2131        FileBackend.close(this.tagReader);
2132    }
2133
2134    public void interrupt() {
2135        if (this.mThread != null) {
2136            this.mThread.interrupt();
2137        }
2138    }
2139
2140    public void disconnect(final boolean force) {
2141        interrupt();
2142        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2143        if (force) {
2144            forceCloseSocket();
2145        } else {
2146            final TagWriter currentTagWriter = this.tagWriter;
2147            if (currentTagWriter.isActive()) {
2148                currentTagWriter.finish();
2149                final Socket currentSocket = this.socket;
2150                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2151                try {
2152                    currentTagWriter.await(1, TimeUnit.SECONDS);
2153                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2154                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2155                    if (streamCountDownLatch != null) {
2156                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2157                            Log.d(
2158                                    Config.LOGTAG,
2159                                    account.getJid().asBareJid() + ": remote ended stream");
2160                        } else {
2161                            Log.d(
2162                                    Config.LOGTAG,
2163                                    account.getJid().asBareJid()
2164                                            + ": remote has not closed socket. force closing");
2165                        }
2166                    }
2167                } catch (InterruptedException e) {
2168                    Log.d(
2169                            Config.LOGTAG,
2170                            account.getJid().asBareJid()
2171                                    + ": interrupted while gracefully closing stream");
2172                } catch (final IOException e) {
2173                    Log.d(
2174                            Config.LOGTAG,
2175                            account.getJid().asBareJid()
2176                                    + ": io exception during disconnect ("
2177                                    + e.getMessage()
2178                                    + ")");
2179                } finally {
2180                    FileBackend.close(currentSocket);
2181                }
2182            } else {
2183                forceCloseSocket();
2184            }
2185        }
2186    }
2187
2188    private void resetStreamId() {
2189        this.streamId = null;
2190    }
2191
2192    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2193        synchronized (this.disco) {
2194            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2195            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2196                if (cursor.getValue().getFeatures().contains(feature)) {
2197                    items.add(cursor);
2198                }
2199            }
2200            return items;
2201        }
2202    }
2203
2204    public Jid findDiscoItemByFeature(final String feature) {
2205        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2206        if (items.size() >= 1) {
2207            return items.get(0).getKey();
2208        }
2209        return null;
2210    }
2211
2212    public boolean r() {
2213        if (getFeatures().sm()) {
2214            this.tagWriter.writeStanzaAsync(new RequestPacket());
2215            return true;
2216        } else {
2217            return false;
2218        }
2219    }
2220
2221    public List<String> getMucServersWithholdAccount() {
2222        final List<String> servers = getMucServers();
2223        servers.remove(account.getDomain().toEscapedString());
2224        return servers;
2225    }
2226
2227    public List<String> getMucServers() {
2228        List<String> servers = new ArrayList<>();
2229        synchronized (this.disco) {
2230            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2231                final ServiceDiscoveryResult value = cursor.getValue();
2232                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2233                        && value.hasIdentity("conference", "text")
2234                        && !value.getFeatures().contains("jabber:iq:gateway")
2235                        && !value.hasIdentity("conference", "irc")) {
2236                    servers.add(cursor.getKey().toString());
2237                }
2238            }
2239        }
2240        return servers;
2241    }
2242
2243    public String getMucServer() {
2244        List<String> servers = getMucServers();
2245        return servers.size() > 0 ? servers.get(0) : null;
2246    }
2247
2248    public int getTimeToNextAttempt() {
2249        final int additionalTime =
2250                account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2251        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2252        final int secondsSinceLast =
2253                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2254        return interval - secondsSinceLast;
2255    }
2256
2257    public int getAttempt() {
2258        return this.attempt;
2259    }
2260
2261    public Features getFeatures() {
2262        return this.features;
2263    }
2264
2265    public long getLastSessionEstablished() {
2266        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2267        return System.currentTimeMillis() - diff;
2268    }
2269
2270    public long getLastConnect() {
2271        return this.lastConnect;
2272    }
2273
2274    public long getLastPingSent() {
2275        return this.lastPingSent;
2276    }
2277
2278    public long getLastDiscoStarted() {
2279        return this.lastDiscoStarted;
2280    }
2281
2282    public long getLastPacketReceived() {
2283        return this.lastPacketReceived;
2284    }
2285
2286    public void sendActive() {
2287        this.sendPacket(new ActivePacket());
2288    }
2289
2290    public void sendInactive() {
2291        this.sendPacket(new InactivePacket());
2292    }
2293
2294    public void resetAttemptCount(boolean resetConnectTime) {
2295        this.attempt = 0;
2296        if (resetConnectTime) {
2297            this.lastConnect = 0;
2298        }
2299    }
2300
2301    public void setInteractive(boolean interactive) {
2302        this.mInteractive = interactive;
2303    }
2304
2305    public Identity getServerIdentity() {
2306        synchronized (this.disco) {
2307            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
2308            if (result == null) {
2309                return Identity.UNKNOWN;
2310            }
2311            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
2312                if (id.getType().equals("im")
2313                        && id.getCategory().equals("server")
2314                        && id.getName() != null) {
2315                    switch (id.getName()) {
2316                        case "Prosody":
2317                            return Identity.PROSODY;
2318                        case "ejabberd":
2319                            return Identity.EJABBERD;
2320                        case "Slack-XMPP":
2321                            return Identity.SLACK;
2322                    }
2323                }
2324            }
2325        }
2326        return Identity.UNKNOWN;
2327    }
2328
2329    private IqGenerator getIqGenerator() {
2330        return mXmppConnectionService.getIqGenerator();
2331    }
2332
2333    public enum Identity {
2334        FACEBOOK,
2335        SLACK,
2336        EJABBERD,
2337        PROSODY,
2338        NIMBUZZ,
2339        UNKNOWN
2340    }
2341
2342    private class MyKeyManager implements X509KeyManager {
2343        @Override
2344        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2345            return account.getPrivateKeyAlias();
2346        }
2347
2348        @Override
2349        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2350            return null;
2351        }
2352
2353        @Override
2354        public X509Certificate[] getCertificateChain(String alias) {
2355            Log.d(Config.LOGTAG, "getting certificate chain");
2356            try {
2357                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2358            } catch (final Exception e) {
2359                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2360                return new X509Certificate[0];
2361            }
2362        }
2363
2364        @Override
2365        public String[] getClientAliases(String s, Principal[] principals) {
2366            final String alias = account.getPrivateKeyAlias();
2367            return alias != null ? new String[] {alias} : new String[0];
2368        }
2369
2370        @Override
2371        public String[] getServerAliases(String s, Principal[] principals) {
2372            return new String[0];
2373        }
2374
2375        @Override
2376        public PrivateKey getPrivateKey(String alias) {
2377            try {
2378                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2379            } catch (Exception e) {
2380                return null;
2381            }
2382        }
2383    }
2384
2385    private static class StateChangingError extends Error {
2386        private final Account.State state;
2387
2388        public StateChangingError(Account.State state) {
2389            this.state = state;
2390        }
2391    }
2392
2393    private static class StateChangingException extends IOException {
2394        private final Account.State state;
2395
2396        public StateChangingException(Account.State state) {
2397            this.state = state;
2398        }
2399    }
2400
2401    public class Features {
2402        XmppConnection connection;
2403        private boolean carbonsEnabled = false;
2404        private boolean encryptionEnabled = false;
2405        private boolean blockListRequested = false;
2406
2407        public Features(final XmppConnection connection) {
2408            this.connection = connection;
2409        }
2410
2411        private boolean hasDiscoFeature(final Jid server, final String feature) {
2412            synchronized (XmppConnection.this.disco) {
2413                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2414                return sdr != null && sdr.getFeatures().contains(feature);
2415            }
2416        }
2417
2418        public boolean carbons() {
2419            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2420        }
2421
2422        public boolean commands() {
2423            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2424        }
2425
2426        public boolean easyOnboardingInvites() {
2427            synchronized (commands) {
2428                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2429            }
2430        }
2431
2432        public boolean bookmarksConversion() {
2433            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2434                    && pepPublishOptions();
2435        }
2436
2437        public boolean avatarConversion() {
2438            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION)
2439                    && pepPublishOptions();
2440        }
2441
2442        public boolean blocking() {
2443            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2444        }
2445
2446        public boolean spamReporting() {
2447            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
2448        }
2449
2450        public boolean flexibleOfflineMessageRetrieval() {
2451            return hasDiscoFeature(
2452                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2453        }
2454
2455        public boolean register() {
2456            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2457        }
2458
2459        public boolean invite() {
2460            return connection.streamFeatures != null
2461                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2462        }
2463
2464        public boolean sm() {
2465            return streamId != null
2466                    || (connection.streamFeatures != null
2467                            && connection.streamFeatures.hasChild("sm"));
2468        }
2469
2470        public boolean csi() {
2471            return connection.streamFeatures != null
2472                    && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2473        }
2474
2475        public boolean pep() {
2476            synchronized (XmppConnection.this.disco) {
2477                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2478                return info != null && info.hasIdentity("pubsub", "pep");
2479            }
2480        }
2481
2482        public boolean pepPersistent() {
2483            synchronized (XmppConnection.this.disco) {
2484                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2485                return info != null
2486                        && info.getFeatures()
2487                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
2488            }
2489        }
2490
2491        public boolean pepPublishOptions() {
2492            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2493        }
2494
2495        public boolean pepOmemoWhitelisted() {
2496            return hasDiscoFeature(
2497                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2498        }
2499
2500        public boolean mam() {
2501            return MessageArchiveService.Version.has(getAccountFeatures());
2502        }
2503
2504        public List<String> getAccountFeatures() {
2505            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2506            return result == null ? Collections.emptyList() : result.getFeatures();
2507        }
2508
2509        public boolean push() {
2510            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2511                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2512        }
2513
2514        public boolean rosterVersioning() {
2515            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2516        }
2517
2518        public void setBlockListRequested(boolean value) {
2519            this.blockListRequested = value;
2520        }
2521
2522        public boolean httpUpload(long filesize) {
2523            if (Config.DISABLE_HTTP_UPLOAD) {
2524                return false;
2525            } else {
2526                for (String namespace :
2527                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2528                    List<Entry<Jid, ServiceDiscoveryResult>> items =
2529                            findDiscoItemsByFeature(namespace);
2530                    if (items.size() > 0) {
2531                        try {
2532                            long maxsize =
2533                                    Long.parseLong(
2534                                            items.get(0)
2535                                                    .getValue()
2536                                                    .getExtendedDiscoInformation(
2537                                                            namespace, "max-file-size"));
2538                            if (filesize <= maxsize) {
2539                                return true;
2540                            } else {
2541                                Log.d(
2542                                        Config.LOGTAG,
2543                                        account.getJid().asBareJid()
2544                                                + ": http upload is not available for files with size "
2545                                                + filesize
2546                                                + " (max is "
2547                                                + maxsize
2548                                                + ")");
2549                                return false;
2550                            }
2551                        } catch (Exception e) {
2552                            return true;
2553                        }
2554                    }
2555                }
2556                return false;
2557            }
2558        }
2559
2560        public boolean useLegacyHttpUpload() {
2561            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
2562                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2563        }
2564
2565        public long getMaxHttpUploadSize() {
2566            for (String namespace :
2567                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2568                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2569                if (items.size() > 0) {
2570                    try {
2571                        return Long.parseLong(
2572                                items.get(0)
2573                                        .getValue()
2574                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
2575                    } catch (Exception e) {
2576                        // ignored
2577                    }
2578                }
2579            }
2580            return -1;
2581        }
2582
2583        public boolean stanzaIds() {
2584            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2585        }
2586
2587        public boolean bookmarks2() {
2588            return Config
2589                    .USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2590        }
2591
2592        public boolean externalServiceDiscovery() {
2593            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2594        }
2595    }
2596}