XmppConnection.java

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