XmppConnection.java

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