XmppConnection.java

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