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