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