XmppConnection.java

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