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        this.socket = sslSocket;
1264        this.tagReader.setInputStream(sslSocket.getInputStream());
1265        this.tagWriter.setOutputStream(sslSocket.getOutputStream());
1266        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1267        final boolean quickStart;
1268        try {
1269            quickStart = establishStream(SSLSockets.version(sslSocket));
1270        } catch (final InterruptedException e) {
1271            return;
1272        }
1273        if (quickStart) {
1274            this.quickStartInProgress = true;
1275        }
1276        features.encryptionEnabled = true;
1277        final Tag tag = tagReader.readTag();
1278        if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1279            SSLSockets.log(account, sslSocket);
1280            processStream();
1281        } else {
1282            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1283        }
1284        sslSocket.close();
1285    }
1286
1287    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1288        final SSLSocketFactory sslSocketFactory;
1289        try {
1290            sslSocketFactory = getSSLSocketFactory();
1291        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1292            throw new StateChangingException(Account.State.TLS_ERROR);
1293        }
1294        final InetAddress address = socket.getInetAddress();
1295        final SSLSocket sslSocket =
1296                (SSLSocket)
1297                        sslSocketFactory.createSocket(
1298                                socket, address.getHostAddress(), socket.getPort(), true);
1299        SSLSockets.setSecurity(sslSocket);
1300        SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1301        SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1302        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1303        try {
1304            if (!xmppDomainVerifier.verify(
1305                    account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1306                Log.d(
1307                        Config.LOGTAG,
1308                        account.getJid().asBareJid()
1309                                + ": TLS certificate domain verification failed");
1310                FileBackend.close(sslSocket);
1311                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1312            }
1313        } catch (final SSLPeerUnverifiedException e) {
1314            FileBackend.close(sslSocket);
1315            throw new StateChangingException(Account.State.TLS_ERROR);
1316        }
1317        return sslSocket;
1318    }
1319
1320    private void processStreamFeatures(final Tag currentTag) throws IOException {
1321        this.streamFeatures = tagReader.readElement(currentTag);
1322        final boolean isSecure = isSecure();
1323        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1324        if (this.quickStartInProgress) {
1325            if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1326                Log.d(
1327                        Config.LOGTAG,
1328                        account.getJid().asBareJid()
1329                                + ": quick start in progress. ignoring features: "
1330                                + XmlHelper.printElementNames(this.streamFeatures));
1331                if (SaslMechanism.hashedToken(this.saslMechanism)) {
1332                    return;
1333                }
1334                if (isFastTokenAvailable(
1335                        this.streamFeatures.findChild("authentication", Namespace.SASL_2))) {
1336                    Log.d(
1337                            Config.LOGTAG,
1338                            account.getJid().asBareJid()
1339                                    + ": fast token available; resetting quick start");
1340                    account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1341                    mXmppConnectionService.databaseBackend.updateAccount(account);
1342                }
1343                return;
1344            }
1345            Log.d(
1346                    Config.LOGTAG,
1347                    account.getJid().asBareJid()
1348                            + ": server lost support for SASL 2. quick start not possible");
1349            this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1350            mXmppConnectionService.databaseBackend.updateAccount(account);
1351            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1352        }
1353        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
1354                && !features.encryptionEnabled) {
1355            sendStartTLS();
1356        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1357                && account.isOptionSet(Account.OPTION_REGISTER)) {
1358            if (isSecure) {
1359                register();
1360            } else {
1361                Log.d(
1362                        Config.LOGTAG,
1363                        account.getJid().asBareJid()
1364                                + ": unable to find STARTTLS for registration process "
1365                                + XmlHelper.printElementNames(this.streamFeatures));
1366                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1367            }
1368        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1369                && account.isOptionSet(Account.OPTION_REGISTER)) {
1370            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1371        } else if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)
1372                && shouldAuthenticate
1373                && isSecure) {
1374            authenticate(SaslMechanism.Version.SASL_2);
1375        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1376                && shouldAuthenticate
1377                && isSecure) {
1378            authenticate(SaslMechanism.Version.SASL);
1379        } else if (this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT)
1380                && streamId != null
1381                && !inSmacksSession) {
1382            if (Config.EXTENDED_SM_LOGGING) {
1383                Log.d(
1384                        Config.LOGTAG,
1385                        account.getJid().asBareJid()
1386                                + ": resuming after stanza #"
1387                                + stanzasReceived);
1388            }
1389            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived);
1390            this.mSmCatchupMessageCounter.set(0);
1391            this.mWaitingForSmCatchup.set(true);
1392            this.tagWriter.writeStanzaAsync(resume);
1393        } else if (needsBinding) {
1394            if (this.streamFeatures.hasChild("bind", Namespace.BIND) && isSecure) {
1395                sendBindRequest();
1396            } else {
1397                Log.d(
1398                        Config.LOGTAG,
1399                        account.getJid().asBareJid()
1400                                + ": unable to find bind feature "
1401                                + XmlHelper.printElementNames(this.streamFeatures));
1402                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1403            }
1404        } else {
1405
1406            Log.d(
1407                    Config.LOGTAG,
1408                    account.getJid().asBareJid()
1409                            + ": received NOP stream features: "
1410                            + XmlHelper.printElementNames(this.streamFeatures));
1411        }
1412    }
1413
1414    private void authenticate() throws IOException {
1415        final boolean isSecure = isSecure();
1416        if (isSecure && this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {authenticate(SaslMechanism.Version.SASL_2);
1417        } else if (isSecure && this.streamFeatures.hasChild("mechanisms", Namespace.SASL)) {
1418            authenticate(SaslMechanism.Version.SASL);
1419        } else {
1420            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1421        }
1422    }
1423
1424    private boolean isSecure() {
1425        return features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1426    }
1427
1428    private void authenticate(final SaslMechanism.Version version) throws IOException {
1429        final Element authElement;
1430        if (version == SaslMechanism.Version.SASL) {
1431            authElement = this.streamFeatures.findChild("mechanisms", Namespace.SASL);
1432        } else {
1433            authElement = this.streamFeatures.findChild("authentication", Namespace.SASL_2);
1434        }
1435        final Collection<String> mechanisms = SaslMechanism.mechanisms(authElement);
1436        final Element cbElement =
1437                this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1438        final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1439        final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1440        final SaslMechanism saslMechanism = factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1441        this.saslMechanism = validate(saslMechanism, mechanisms);
1442        final boolean quickStartAvailable;
1443        final String firstMessage = this.saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1444        final boolean usingFast = SaslMechanism.hashedToken(this.saslMechanism);
1445        final Element authenticate;
1446        if (version == SaslMechanism.Version.SASL) {
1447            authenticate = new Element("auth", Namespace.SASL);
1448            if (!Strings.isNullOrEmpty(firstMessage)) {
1449                authenticate.setContent(firstMessage);
1450            }
1451            quickStartAvailable = false;
1452        } else if (version == SaslMechanism.Version.SASL_2) {
1453            final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1454            final boolean sm = inline != null && inline.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1455            final HashedToken.Mechanism hashTokenRequest;
1456            if (usingFast) {
1457                hashTokenRequest = null;
1458            } else {
1459                final Element fast = inline == null ? null : inline.findChild("fast", Namespace.FAST);
1460                final Collection<String> fastMechanisms = SaslMechanism.mechanisms(fast);
1461                hashTokenRequest =
1462                        HashedToken.Mechanism.best(fastMechanisms, SSLSockets.version(this.socket));
1463            }
1464            final Collection<String> bindFeatures = Bind2.features(inline);
1465            quickStartAvailable =
1466                    sm
1467                            && bindFeatures != null
1468                            && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1469            if (bindFeatures != null) {
1470                try {
1471                    mXmppConnectionService.restoredFromDatabaseLatch.await();
1472                } catch (final InterruptedException e) {
1473                    Log.d(
1474                            Config.LOGTAG,
1475                            account.getJid().asBareJid()
1476                                    + ": interrupted while waiting for DB restore during SASL2 bind");
1477                    return;
1478                }
1479            }
1480            this.hashTokenRequest = hashTokenRequest;
1481            authenticate = generateAuthenticationRequest(firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1482        } else {
1483            throw new AssertionError("Missing implementation for " + version);
1484        }
1485
1486        if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1487            mXmppConnectionService.databaseBackend.updateAccount(account);
1488        }
1489
1490        Log.d(
1491                Config.LOGTAG,
1492                account.getJid().toString()
1493                        + ": Authenticating with "
1494                        + version
1495                        + "/"
1496                        + this.saslMechanism.getMechanism());
1497        authenticate.setAttribute("mechanism", this.saslMechanism.getMechanism());
1498        synchronized (this.mStanzaQueue) {
1499            this.stanzasSentBeforeAuthentication = this.stanzasSent;
1500            tagWriter.writeElement(authenticate);
1501        }
1502    }
1503
1504    private static boolean isFastTokenAvailable(final Element authentication) {
1505        final Element inline = authentication == null ? null : authentication.findChild("inline");
1506        return inline != null && inline.hasChild("fast", Namespace.FAST);
1507    }
1508
1509    @NonNull
1510    private SaslMechanism validate(final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms) throws StateChangingException {
1511        if (saslMechanism == null) {
1512            Log.d(
1513                    Config.LOGTAG,
1514                    account.getJid().asBareJid()
1515                            + ": unable to find supported SASL mechanism in "
1516                            + mechanisms);
1517            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1518        }
1519        if (SaslMechanism.hashedToken(saslMechanism)) {
1520            return saslMechanism;
1521        }
1522        final int pinnedMechanism = account.getPinnedMechanismPriority();
1523        if (pinnedMechanism > saslMechanism.getPriority()) {
1524            Log.e(
1525                    Config.LOGTAG,
1526                    "Auth failed. Authentication mechanism "
1527                            + saslMechanism.getMechanism()
1528                            + " has lower priority ("
1529                            + saslMechanism.getPriority()
1530                            + ") than pinned priority ("
1531                            + pinnedMechanism
1532                            + "). Possible downgrade attack?");
1533            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1534        }
1535        return saslMechanism;
1536    }
1537
1538    private Element generateAuthenticationRequest(final String firstMessage, final boolean usingFast) {
1539        return generateAuthenticationRequest(firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1540    }
1541
1542    private Element generateAuthenticationRequest(
1543            final String firstMessage,
1544            final boolean usingFast,
1545            final HashedToken.Mechanism hashedTokenRequest,
1546            final Collection<String> bind,
1547            final boolean inlineStreamManagement) {
1548        final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1549        if (!Strings.isNullOrEmpty(firstMessage)) {
1550            authenticate.addChild("initial-response").setContent(firstMessage);
1551        }
1552        final Element userAgent = authenticate.addChild("user-agent");
1553        userAgent.setAttribute("id", AccountUtils.publicDeviceId(account));
1554        userAgent
1555                .addChild("software")
1556                .setContent(mXmppConnectionService.getString(R.string.app_name));
1557        if (!PhoneHelper.isEmulator()) {
1558            userAgent
1559                    .addChild("device")
1560                    .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1561        }
1562        // do not include bind if 'inlinestreamManagment' is missing and we have a streamId
1563        final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1564        if (bind != null && mayAttemptBind) {
1565            authenticate.addChild(generateBindRequest(bind));
1566        }
1567        if (inlineStreamManagement && streamId != null) {
1568            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived);
1569            this.mSmCatchupMessageCounter.set(0);
1570            this.mWaitingForSmCatchup.set(true);
1571            authenticate.addChild(resume);
1572        }
1573        if (hashedTokenRequest != null) {
1574            authenticate
1575                    .addChild("request-token", Namespace.FAST)
1576                    .setAttribute("mechanism", hashedTokenRequest.name());
1577        }
1578        if (usingFast) {
1579            authenticate.addChild("fast", Namespace.FAST);
1580        }
1581        return authenticate;
1582    }
1583
1584    private Element generateBindRequest(final Collection<String> bindFeatures) {
1585        Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1586        final Element bind = new Element("bind", Namespace.BIND2);
1587        bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1588        if (bindFeatures.contains(Namespace.CARBONS)) {
1589            bind.addChild("enable", Namespace.CARBONS);
1590        }
1591        if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1592            bind.addChild(new EnablePacket());
1593        }
1594        return bind;
1595    }
1596
1597    private void register() {
1598        final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1599        if (preAuth != null && features.invite()) {
1600            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1601            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1602            sendUnmodifiedIqPacket(
1603                    preAuthRequest,
1604                    (account, response) -> {
1605                        if (response.getType() == IqPacket.TYPE.RESULT) {
1606                            sendRegistryRequest();
1607                        } else {
1608                            final String error = response.getErrorCondition();
1609                            Log.d(
1610                                    Config.LOGTAG,
1611                                    account.getJid().asBareJid()
1612                                            + ": failed to pre auth. "
1613                                            + error);
1614                            throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1615                        }
1616                    },
1617                    true);
1618        } else {
1619            sendRegistryRequest();
1620        }
1621    }
1622
1623    private void sendRegistryRequest() {
1624        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1625        register.query(Namespace.REGISTER);
1626        register.setTo(account.getDomain());
1627        sendUnmodifiedIqPacket(
1628                register,
1629                (account, packet) -> {
1630                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1631                        return;
1632                    }
1633                    if (packet.getType() == IqPacket.TYPE.ERROR) {
1634                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1635                    }
1636                    final Element query = packet.query(Namespace.REGISTER);
1637                    if (query.hasChild("username") && (query.hasChild("password"))) {
1638                        final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1639                        final Element username =
1640                                new Element("username").setContent(account.getUsername());
1641                        final Element password =
1642                                new Element("password").setContent(account.getPassword());
1643                        register1.query(Namespace.REGISTER).addChild(username);
1644                        register1.query().addChild(password);
1645                        register1.setFrom(account.getJid().asBareJid());
1646                        sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1647                    } else if (query.hasChild("x", Namespace.DATA)) {
1648                        final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1649                        final Element blob = query.findChild("data", "urn:xmpp:bob");
1650                        final String id = packet.getId();
1651                        InputStream is;
1652                        if (blob != null) {
1653                            try {
1654                                final String base64Blob = blob.getContent();
1655                                final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1656                                is = new ByteArrayInputStream(strBlob);
1657                            } catch (Exception e) {
1658                                is = null;
1659                            }
1660                        } else {
1661                            final boolean useTor =
1662                                    mXmppConnectionService.useTorToConnect() || account.isOnion();
1663                            try {
1664                                final String url = data.getValue("url");
1665                                final String fallbackUrl = data.getValue("captcha-fallback-url");
1666                                if (url != null) {
1667                                    is = HttpConnectionManager.open(url, useTor);
1668                                } else if (fallbackUrl != null) {
1669                                    is = HttpConnectionManager.open(fallbackUrl, useTor);
1670                                } else {
1671                                    is = null;
1672                                }
1673                            } catch (final IOException e) {
1674                                Log.d(
1675                                        Config.LOGTAG,
1676                                        account.getJid().asBareJid() + ": unable to fetch captcha",
1677                                        e);
1678                                is = null;
1679                            }
1680                        }
1681
1682                        if (is != null) {
1683                            Bitmap captcha = BitmapFactory.decodeStream(is);
1684                            try {
1685                                if (mXmppConnectionService.displayCaptchaRequest(
1686                                        account, id, data, captcha)) {
1687                                    return;
1688                                }
1689                            } catch (Exception e) {
1690                                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1691                            }
1692                        }
1693                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1694                    } else if (query.hasChild("instructions")
1695                            || query.hasChild("x", Namespace.OOB)) {
1696                        final String instructions = query.findChildContent("instructions");
1697                        final Element oob = query.findChild("x", Namespace.OOB);
1698                        final String url = oob == null ? null : oob.findChildContent("url");
1699                        if (url != null) {
1700                            setAccountCreationFailed(url);
1701                        } else if (instructions != null) {
1702                            final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1703                            if (matcher.find()) {
1704                                setAccountCreationFailed(
1705                                        instructions.substring(matcher.start(), matcher.end()));
1706                            }
1707                        }
1708                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1709                    }
1710                },
1711                true);
1712    }
1713
1714    private void setAccountCreationFailed(final String url) {
1715        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1716        if (httpUrl != null && httpUrl.isHttps()) {
1717            this.redirectionUrl = httpUrl;
1718            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1719        }
1720        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1721    }
1722
1723    public HttpUrl getRedirectionUrl() {
1724        return this.redirectionUrl;
1725    }
1726
1727    public void resetEverything() {
1728        resetAttemptCount(true);
1729        resetStreamId();
1730        clearIqCallbacks();
1731        this.stanzasSent = 0;
1732        mStanzaQueue.clear();
1733        this.redirectionUrl = null;
1734        synchronized (this.disco) {
1735            disco.clear();
1736        }
1737        synchronized (this.commands) {
1738            this.commands.clear();
1739        }
1740        this.saslMechanism = null;
1741    }
1742
1743    private void sendBindRequest() {
1744        try {
1745            mXmppConnectionService.restoredFromDatabaseLatch.await();
1746        } catch (InterruptedException e) {
1747            Log.d(
1748                    Config.LOGTAG,
1749                    account.getJid().asBareJid()
1750                            + ": interrupted while waiting for DB restore during bind");
1751            return;
1752        }
1753        clearIqCallbacks();
1754        if (account.getJid().isBareJid()) {
1755            account.setResource(this.createNewResource());
1756        } else {
1757            fixResource(mXmppConnectionService, account);
1758        }
1759        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1760        final String resource =
1761                Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1762        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1763        this.sendUnmodifiedIqPacket(
1764                iq,
1765                (account, packet) -> {
1766                    if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1767                        return;
1768                    }
1769                    final Element bind = packet.findChild("bind");
1770                    if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1771                        isBound = true;
1772                        final Element jid = bind.findChild("jid");
1773                        if (jid != null && jid.getContent() != null) {
1774                            try {
1775                                Jid assignedJid = Jid.ofEscaped(jid.getContent());
1776                                if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1777                                    Log.d(
1778                                            Config.LOGTAG,
1779                                            account.getJid().asBareJid()
1780                                                    + ": server tried to re-assign domain to "
1781                                                    + assignedJid.getDomain());
1782                                    throw new StateChangingError(Account.State.BIND_FAILURE);
1783                                }
1784                                if (account.setJid(assignedJid)) {
1785                                    Log.d(
1786                                            Config.LOGTAG,
1787                                            account.getJid().asBareJid()
1788                                                    + ": jid changed during bind. updating database");
1789                                    mXmppConnectionService.databaseBackend.updateAccount(account);
1790                                }
1791                                if (streamFeatures.hasChild("session")
1792                                        && !streamFeatures
1793                                                .findChild("session")
1794                                                .hasChild("optional")) {
1795                                    sendStartSession();
1796                                } else {
1797                                    final boolean waitForDisco = enableStreamManagement();
1798                                    sendPostBindInitialization(waitForDisco, false);
1799                                }
1800                                return;
1801                            } catch (final IllegalArgumentException e) {
1802                                Log.d(
1803                                        Config.LOGTAG,
1804                                        account.getJid().asBareJid()
1805                                                + ": server reported invalid jid ("
1806                                                + jid.getContent()
1807                                                + ") on bind");
1808                            }
1809                        } else {
1810                            Log.d(
1811                                    Config.LOGTAG,
1812                                    account.getJid()
1813                                            + ": disconnecting because of bind failure. (no jid)");
1814                        }
1815                    } else {
1816                        Log.d(
1817                                Config.LOGTAG,
1818                                account.getJid()
1819                                        + ": disconnecting because of bind failure ("
1820                                        + packet);
1821                    }
1822                    final Element error = packet.findChild("error");
1823                    if (packet.getType() == IqPacket.TYPE.ERROR
1824                            && error != null
1825                            && error.hasChild("conflict")) {
1826                        account.setResource(createNewResource());
1827                    }
1828                    throw new StateChangingError(Account.State.BIND_FAILURE);
1829                },
1830                true);
1831    }
1832
1833    private void clearIqCallbacks() {
1834        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1835        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1836        synchronized (this.packetCallbacks) {
1837            if (this.packetCallbacks.size() == 0) {
1838                return;
1839            }
1840            Log.d(
1841                    Config.LOGTAG,
1842                    account.getJid().asBareJid()
1843                            + ": clearing "
1844                            + this.packetCallbacks.size()
1845                            + " iq callbacks");
1846            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1847                    this.packetCallbacks.values().iterator();
1848            while (iterator.hasNext()) {
1849                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1850                callbacks.add(entry.second);
1851                iterator.remove();
1852            }
1853        }
1854        for (OnIqPacketReceived callback : callbacks) {
1855            try {
1856                callback.onIqPacketReceived(account, failurePacket);
1857            } catch (StateChangingError error) {
1858                Log.d(
1859                        Config.LOGTAG,
1860                        account.getJid().asBareJid()
1861                                + ": caught StateChangingError("
1862                                + error.state.toString()
1863                                + ") while clearing callbacks");
1864                // ignore
1865            }
1866        }
1867        Log.d(
1868                Config.LOGTAG,
1869                account.getJid().asBareJid()
1870                        + ": done clearing iq callbacks. "
1871                        + this.packetCallbacks.size()
1872                        + " left");
1873    }
1874
1875    public void sendDiscoTimeout() {
1876        if (mWaitForDisco.compareAndSet(true, false)) {
1877            Log.d(
1878                    Config.LOGTAG,
1879                    account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1880            finalizeBind();
1881        }
1882    }
1883
1884    private void sendStartSession() {
1885        Log.d(
1886                Config.LOGTAG,
1887                account.getJid().asBareJid() + ": sending legacy session to outdated server");
1888        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1889        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1890        this.sendUnmodifiedIqPacket(
1891                startSession,
1892                (account, packet) -> {
1893                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1894                        final boolean waitForDisco = enableStreamManagement();
1895                        sendPostBindInitialization(waitForDisco, false);
1896                    } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1897                        throw new StateChangingError(Account.State.SESSION_FAILURE);
1898                    }
1899                },
1900                true);
1901    }
1902
1903    private boolean enableStreamManagement() {
1904        final boolean streamManagement =
1905                this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1906        if (streamManagement) {
1907            synchronized (this.mStanzaQueue) {
1908                final EnablePacket enable = new EnablePacket();
1909                tagWriter.writeStanzaAsync(enable);
1910                stanzasSent = 0;
1911                mStanzaQueue.clear();
1912            }
1913            return true;
1914        } else {
1915            return false;
1916        }
1917    }
1918
1919    private void sendPostBindInitialization(
1920            final boolean waitForDisco, final boolean carbonsEnabled) {
1921        features.carbonsEnabled = carbonsEnabled;
1922        features.blockListRequested = false;
1923        synchronized (this.disco) {
1924            this.disco.clear();
1925        }
1926        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1927        mPendingServiceDiscoveries.set(0);
1928        mWaitForDisco.set(waitForDisco);
1929        lastDiscoStarted = SystemClock.elapsedRealtime();
1930        mXmppConnectionService.scheduleWakeUpCall(
1931                Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1932        final Element caps = streamFeatures.findChild("c");
1933        final String hash = caps == null ? null : caps.getAttribute("hash");
1934        final String ver = caps == null ? null : caps.getAttribute("ver");
1935        ServiceDiscoveryResult discoveryResult = null;
1936        if (hash != null && ver != null) {
1937            discoveryResult =
1938                    mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1939        }
1940        final boolean requestDiscoItemsFirst =
1941                !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1942        if (requestDiscoItemsFirst) {
1943            sendServiceDiscoveryItems(account.getDomain());
1944        }
1945        if (discoveryResult == null) {
1946            sendServiceDiscoveryInfo(account.getDomain());
1947        } else {
1948            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1949            disco.put(account.getDomain(), discoveryResult);
1950        }
1951        discoverMamPreferences();
1952        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1953        if (!requestDiscoItemsFirst) {
1954            sendServiceDiscoveryItems(account.getDomain());
1955        }
1956
1957        if (!mWaitForDisco.get()) {
1958            finalizeBind();
1959        }
1960        this.lastSessionStarted = SystemClock.elapsedRealtime();
1961    }
1962
1963    private void sendServiceDiscoveryInfo(final Jid jid) {
1964        mPendingServiceDiscoveries.incrementAndGet();
1965        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1966        iq.setTo(jid);
1967        iq.query("http://jabber.org/protocol/disco#info");
1968        this.sendIqPacket(
1969                iq,
1970                (account, packet) -> {
1971                    if (packet.getType() == IqPacket.TYPE.RESULT) {
1972                        boolean advancedStreamFeaturesLoaded;
1973                        synchronized (XmppConnection.this.disco) {
1974                            ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1975                            if (jid.equals(account.getDomain())) {
1976                                mXmppConnectionService.databaseBackend.insertDiscoveryResult(
1977                                        result);
1978                            }
1979                            disco.put(jid, result);
1980                            advancedStreamFeaturesLoaded =
1981                                    disco.containsKey(account.getDomain())
1982                                            && disco.containsKey(account.getJid().asBareJid());
1983                        }
1984                        if (advancedStreamFeaturesLoaded
1985                                && (jid.equals(account.getDomain())
1986                                        || jid.equals(account.getJid().asBareJid()))) {
1987                            enableAdvancedStreamFeatures();
1988                        }
1989                    } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1990                        Log.d(
1991                                Config.LOGTAG,
1992                                account.getJid().asBareJid()
1993                                        + ": could not query disco info for "
1994                                        + jid.toString());
1995                        final boolean serverOrAccount =
1996                                jid.equals(account.getDomain())
1997                                        || jid.equals(account.getJid().asBareJid());
1998                        final boolean advancedStreamFeaturesLoaded;
1999                        if (serverOrAccount) {
2000                            synchronized (XmppConnection.this.disco) {
2001                                disco.put(jid, ServiceDiscoveryResult.empty());
2002                                advancedStreamFeaturesLoaded =
2003                                        disco.containsKey(account.getDomain())
2004                                                && disco.containsKey(account.getJid().asBareJid());
2005                            }
2006                        } else {
2007                            advancedStreamFeaturesLoaded = false;
2008                        }
2009                        if (advancedStreamFeaturesLoaded) {
2010                            enableAdvancedStreamFeatures();
2011                        }
2012                    }
2013                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2014                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2015                                && mWaitForDisco.compareAndSet(true, false)) {
2016                            finalizeBind();
2017                        }
2018                    }
2019                });
2020    }
2021
2022    private void discoverMamPreferences() {
2023        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2024        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2025        sendIqPacket(
2026                request,
2027                (account, response) -> {
2028                    if (response.getType() == IqPacket.TYPE.RESULT) {
2029                        Element prefs =
2030                                response.findChild(
2031                                        "prefs", MessageArchiveService.Version.MAM_2.namespace);
2032                        isMamPreferenceAlways =
2033                                "always"
2034                                        .equals(
2035                                                prefs == null
2036                                                        ? null
2037                                                        : prefs.getAttribute("default"));
2038                    }
2039                });
2040    }
2041
2042    private void discoverCommands() {
2043        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2044        request.setTo(account.getDomain());
2045        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2046        sendIqPacket(
2047                request,
2048                (account, response) -> {
2049                    if (response.getType() == IqPacket.TYPE.RESULT) {
2050                        final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2051                        if (query == null) {
2052                            return;
2053                        }
2054                        final HashMap<String, Jid> commands = new HashMap<>();
2055                        for (final Element child : query.getChildren()) {
2056                            if ("item".equals(child.getName())) {
2057                                final String node = child.getAttribute("node");
2058                                final Jid jid = child.getAttributeAsJid("jid");
2059                                if (node != null && jid != null) {
2060                                    commands.put(node, jid);
2061                                }
2062                            }
2063                        }
2064                        synchronized (this.commands) {
2065                            this.commands.clear();
2066                            this.commands.putAll(commands);
2067                        }
2068                    }
2069                });
2070    }
2071
2072    public boolean isMamPreferenceAlways() {
2073        return isMamPreferenceAlways;
2074    }
2075
2076    private void finalizeBind() {
2077        if (bindListener != null) {
2078            bindListener.onBind(account);
2079        }
2080        changeStatusToOnline();
2081    }
2082
2083    private void enableAdvancedStreamFeatures() {
2084        if (getFeatures().blocking() && !features.blockListRequested) {
2085            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2086            this.sendIqPacket(
2087                    getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
2088        }
2089        for (final OnAdvancedStreamFeaturesLoaded listener :
2090                advancedStreamFeaturesLoadedListeners) {
2091            listener.onAdvancedStreamFeaturesAvailable(account);
2092        }
2093        if (getFeatures().carbons() && !features.carbonsEnabled) {
2094            sendEnableCarbons();
2095        }
2096        if (getFeatures().commands()) {
2097            discoverCommands();
2098        }
2099    }
2100
2101    private void sendServiceDiscoveryItems(final Jid server) {
2102        mPendingServiceDiscoveries.incrementAndGet();
2103        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2104        iq.setTo(server.getDomain());
2105        iq.query("http://jabber.org/protocol/disco#items");
2106        this.sendIqPacket(
2107                iq,
2108                (account, packet) -> {
2109                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2110                        final HashSet<Jid> items = new HashSet<>();
2111                        final List<Element> elements = packet.query().getChildren();
2112                        for (final Element element : elements) {
2113                            if (element.getName().equals("item")) {
2114                                final Jid jid =
2115                                        InvalidJid.getNullForInvalid(
2116                                                element.getAttributeAsJid("jid"));
2117                                if (jid != null && !jid.equals(account.getDomain())) {
2118                                    items.add(jid);
2119                                }
2120                            }
2121                        }
2122                        for (Jid jid : items) {
2123                            sendServiceDiscoveryInfo(jid);
2124                        }
2125                    } else {
2126                        Log.d(
2127                                Config.LOGTAG,
2128                                account.getJid().asBareJid()
2129                                        + ": could not query disco items of "
2130                                        + server);
2131                    }
2132                    if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2133                        if (mPendingServiceDiscoveries.decrementAndGet() == 0
2134                                && mWaitForDisco.compareAndSet(true, false)) {
2135                            finalizeBind();
2136                        }
2137                    }
2138                });
2139    }
2140
2141    private void sendEnableCarbons() {
2142        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2143        iq.addChild("enable", Namespace.CARBONS);
2144        this.sendIqPacket(
2145                iq,
2146                (account, packet) -> {
2147                    if (packet.getType() == IqPacket.TYPE.RESULT) {
2148                        Log.d(
2149                                Config.LOGTAG,
2150                                account.getJid().asBareJid() + ": successfully enabled carbons");
2151                        features.carbonsEnabled = true;
2152                    } else {
2153                        Log.d(
2154                                Config.LOGTAG,
2155                                account.getJid().asBareJid()
2156                                        + ": could not enable carbons "
2157                                        + packet);
2158                    }
2159                });
2160    }
2161
2162    private void processStreamError(final Tag currentTag) throws IOException {
2163        final Element streamError = tagReader.readElement(currentTag);
2164        if (streamError == null) {
2165            return;
2166        }
2167        if (streamError.hasChild("conflict")) {
2168            account.setResource(createNewResource());
2169            Log.d(
2170                    Config.LOGTAG,
2171                    account.getJid().asBareJid()
2172                            + ": switching resource due to conflict ("
2173                            + account.getResource()
2174                            + ")");
2175            throw new IOException();
2176        } else if (streamError.hasChild("host-unknown")) {
2177            throw new StateChangingException(Account.State.HOST_UNKNOWN);
2178        } else if (streamError.hasChild("policy-violation")) {
2179            this.lastConnect = SystemClock.elapsedRealtime();
2180            final String text = streamError.findChildContent("text");
2181            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2182            failPendingMessages(text);
2183            throw new StateChangingException(Account.State.POLICY_VIOLATION);
2184        } else if (streamError.hasChild("see-other-host")) {
2185            final String seeOtherHost = streamError.findChildContent("see-other-host");
2186            final Resolver.Result currentResolverResult = this.currentResolverResult;
2187            if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2188                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2189                throw new StateChangingException(Account.State.STREAM_ERROR);
2190            }
2191            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": see other host: "+seeOtherHost+" "+currentResolverResult);
2192            final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2193            if (seeOtherResult != null) {
2194                this.seeOtherHostResolverResult = seeOtherResult;
2195                throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2196            } else {
2197                throw new StateChangingException(Account.State.STREAM_ERROR);
2198            }
2199        } else {
2200            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2201            throw new StateChangingException(Account.State.STREAM_ERROR);
2202        }
2203    }
2204
2205    private void failPendingMessages(final String error) {
2206        synchronized (this.mStanzaQueue) {
2207            for (int i = 0; i < mStanzaQueue.size(); ++i) {
2208                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
2209                if (stanza instanceof MessagePacket) {
2210                    final MessagePacket packet = (MessagePacket) stanza;
2211                    final String id = packet.getId();
2212                    final Jid to = packet.getTo();
2213                    mXmppConnectionService.markMessage(
2214                            account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2215                }
2216            }
2217        }
2218    }
2219
2220    private boolean establishStream(final SSLSockets.Version sslVersion)
2221            throws IOException, InterruptedException {
2222        final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2223        final SaslMechanism quickStartMechanism;
2224        if (secureConnection) {
2225            quickStartMechanism = SaslMechanism.ensureAvailable(account.getQuickStartMechanism(), sslVersion);
2226        } else {
2227            quickStartMechanism = null;
2228        }
2229        if (secureConnection
2230                && Config.QUICKSTART_ENABLED
2231                && quickStartMechanism != null
2232                && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2233            mXmppConnectionService.restoredFromDatabaseLatch.await();
2234            this.saslMechanism = quickStartMechanism;
2235            final boolean usingFast = quickStartMechanism instanceof HashedToken;
2236            final Element authenticate =
2237                    generateAuthenticationRequest(quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)), usingFast);
2238            authenticate.setAttribute("mechanism", quickStartMechanism.getMechanism());
2239            sendStartStream(true, false);
2240            synchronized (this.mStanzaQueue) {
2241                this.stanzasSentBeforeAuthentication = this.stanzasSent;
2242                tagWriter.writeElement(authenticate);
2243            }
2244            Log.d(
2245                    Config.LOGTAG,
2246                    account.getJid().toString()
2247                            + ": quick start with "
2248                            + quickStartMechanism.getMechanism());
2249            return true;
2250        } else {
2251            sendStartStream(secureConnection, true);
2252            return false;
2253        }
2254    }
2255
2256    private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2257        final Tag stream = Tag.start("stream:stream");
2258        stream.setAttribute("to", account.getServer());
2259        if (from) {
2260            stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2261        }
2262        stream.setAttribute("version", "1.0");
2263        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2264        stream.setAttribute("xmlns", "jabber:client");
2265        stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2266        tagWriter.writeTag(stream, flush);
2267    }
2268
2269    private String createNewResource() {
2270        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2271    }
2272
2273    private String nextRandomId() {
2274        return nextRandomId(false);
2275    }
2276
2277    private String nextRandomId(final boolean s) {
2278        return CryptoHelper.random(s ? 3 : 9);
2279    }
2280
2281    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2282        packet.setFrom(account.getJid());
2283        return this.sendUnmodifiedIqPacket(packet, callback, false);
2284    }
2285
2286    public synchronized String sendUnmodifiedIqPacket(
2287            final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2288        if (packet.getId() == null) {
2289            packet.setAttribute("id", nextRandomId());
2290        }
2291        if (callback != null) {
2292            synchronized (this.packetCallbacks) {
2293                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2294            }
2295        }
2296        this.sendPacket(packet, force);
2297        return packet.getId();
2298    }
2299
2300    public void sendMessagePacket(final MessagePacket packet) {
2301        this.sendPacket(packet);
2302    }
2303
2304    public void sendPresencePacket(final PresencePacket packet) {
2305        this.sendPacket(packet);
2306    }
2307
2308    private synchronized void sendPacket(final AbstractStanza packet) {
2309        sendPacket(packet, false);
2310    }
2311
2312    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2313        if (stanzasSent == Integer.MAX_VALUE) {
2314            resetStreamId();
2315            disconnect(true);
2316            return;
2317        }
2318        synchronized (this.mStanzaQueue) {
2319            if (force || isBound) {
2320                tagWriter.writeStanzaAsync(packet);
2321            } else {
2322                Log.d(
2323                        Config.LOGTAG,
2324                        account.getJid().asBareJid()
2325                                + " do not write stanza to unbound stream "
2326                                + packet.toString());
2327            }
2328            if (packet instanceof AbstractAcknowledgeableStanza) {
2329                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
2330
2331                if (this.mStanzaQueue.size() != 0) {
2332                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2333                    if (currentHighestKey != stanzasSent) {
2334                        throw new AssertionError("Stanza count messed up");
2335                    }
2336                }
2337
2338                ++stanzasSent;
2339                if (Config.EXTENDED_SM_LOGGING) {
2340                    Log.d(Config.LOGTAG, account.getJid().asBareJid()+": counting outbound "+packet.getName()+" as #" + stanzasSent);
2341                }
2342                this.mStanzaQueue.append(stanzasSent, stanza);
2343                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2344                    if (Config.EXTENDED_SM_LOGGING) {
2345                        Log.d(
2346                                Config.LOGTAG,
2347                                account.getJid().asBareJid()
2348                                        + ": requesting ack for message stanza #"
2349                                        + stanzasSent);
2350                    }
2351                    tagWriter.writeStanzaAsync(new RequestPacket());
2352                }
2353            }
2354        }
2355    }
2356
2357    public void sendPing() {
2358        if (!r()) {
2359            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2360            iq.setFrom(account.getJid());
2361            iq.addChild("ping", Namespace.PING);
2362            this.sendIqPacket(iq, null);
2363        }
2364        this.lastPingSent = SystemClock.elapsedRealtime();
2365    }
2366
2367    public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2368        this.messageListener = listener;
2369    }
2370
2371    public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2372        this.unregisteredIqListener = listener;
2373    }
2374
2375    public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2376        this.presenceListener = listener;
2377    }
2378
2379    public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2380        this.jingleListener = listener;
2381    }
2382
2383    public void setOnStatusChangedListener(final OnStatusChanged listener) {
2384        this.statusListener = listener;
2385    }
2386
2387    public void setOnBindListener(final OnBindListener listener) {
2388        this.bindListener = listener;
2389    }
2390
2391    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2392        this.acknowledgedListener = listener;
2393    }
2394
2395    public void addOnAdvancedStreamFeaturesAvailableListener(
2396            final OnAdvancedStreamFeaturesLoaded listener) {
2397        this.advancedStreamFeaturesLoadedListeners.add(listener);
2398    }
2399
2400    private void forceCloseSocket() {
2401        FileBackend.close(this.socket);
2402        FileBackend.close(this.tagReader);
2403    }
2404
2405    public void interrupt() {
2406        if (this.mThread != null) {
2407            this.mThread.interrupt();
2408        }
2409    }
2410
2411    public void disconnect(final boolean force) {
2412        interrupt();
2413        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2414        if (force) {
2415            forceCloseSocket();
2416        } else {
2417            final TagWriter currentTagWriter = this.tagWriter;
2418            if (currentTagWriter.isActive()) {
2419                currentTagWriter.finish();
2420                final Socket currentSocket = this.socket;
2421                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2422                try {
2423                    currentTagWriter.await(1, TimeUnit.SECONDS);
2424                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2425                    currentTagWriter.writeTag(Tag.end("stream:stream"));
2426                    if (streamCountDownLatch != null) {
2427                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2428                            Log.d(
2429                                    Config.LOGTAG,
2430                                    account.getJid().asBareJid() + ": remote ended stream");
2431                        } else {
2432                            Log.d(
2433                                    Config.LOGTAG,
2434                                    account.getJid().asBareJid()
2435                                            + ": remote has not closed socket. force closing");
2436                        }
2437                    }
2438                } catch (InterruptedException e) {
2439                    Log.d(
2440                            Config.LOGTAG,
2441                            account.getJid().asBareJid()
2442                                    + ": interrupted while gracefully closing stream");
2443                } catch (final IOException e) {
2444                    Log.d(
2445                            Config.LOGTAG,
2446                            account.getJid().asBareJid()
2447                                    + ": io exception during disconnect ("
2448                                    + e.getMessage()
2449                                    + ")");
2450                } finally {
2451                    FileBackend.close(currentSocket);
2452                }
2453            } else {
2454                forceCloseSocket();
2455            }
2456        }
2457    }
2458
2459    private void resetStreamId() {
2460        this.streamId = null;
2461        this.boundStreamFeatures = null;
2462    }
2463
2464    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2465        synchronized (this.disco) {
2466            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2467            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2468                if (cursor.getValue().getFeatures().contains(feature)) {
2469                    items.add(cursor);
2470                }
2471            }
2472            return items;
2473        }
2474    }
2475
2476    public Jid findDiscoItemByFeature(final String feature) {
2477        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2478        if (items.size() >= 1) {
2479            return items.get(0).getKey();
2480        }
2481        return null;
2482    }
2483
2484    public boolean r() {
2485        if (getFeatures().sm()) {
2486            this.tagWriter.writeStanzaAsync(new RequestPacket());
2487            return true;
2488        } else {
2489            return false;
2490        }
2491    }
2492
2493    public List<String> getMucServersWithholdAccount() {
2494        final List<String> servers = getMucServers();
2495        servers.remove(account.getDomain().toEscapedString());
2496        return servers;
2497    }
2498
2499    public List<String> getMucServers() {
2500        List<String> servers = new ArrayList<>();
2501        synchronized (this.disco) {
2502            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2503                final ServiceDiscoveryResult value = cursor.getValue();
2504                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2505                        && value.hasIdentity("conference", "text")
2506                        && !value.getFeatures().contains("jabber:iq:gateway")
2507                        && !value.hasIdentity("conference", "irc")) {
2508                    servers.add(cursor.getKey().toString());
2509                }
2510            }
2511        }
2512        return servers;
2513    }
2514
2515    public String getMucServer() {
2516        List<String> servers = getMucServers();
2517        return servers.size() > 0 ? servers.get(0) : null;
2518    }
2519
2520    public int getTimeToNextAttempt(final boolean aggressive) {
2521        final int interval;
2522        if (aggressive) {
2523            interval = Math.min((int) (3 * Math.pow(1.3,attempt)), 60);
2524        } else {
2525            final int additionalTime =
2526                    account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2527            interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2528        }
2529        final int secondsSinceLast =
2530                (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2531        return interval - secondsSinceLast;
2532    }
2533
2534    public int getAttempt() {
2535        return this.attempt;
2536    }
2537
2538    public Features getFeatures() {
2539        return this.features;
2540    }
2541
2542    public long getLastSessionEstablished() {
2543        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2544        return System.currentTimeMillis() - diff;
2545    }
2546
2547    public long getLastConnect() {
2548        return this.lastConnect;
2549    }
2550
2551    public long getLastPingSent() {
2552        return this.lastPingSent;
2553    }
2554
2555    public long getLastDiscoStarted() {
2556        return this.lastDiscoStarted;
2557    }
2558
2559    public long getLastPacketReceived() {
2560        return this.lastPacketReceived;
2561    }
2562
2563    public void sendActive() {
2564        this.sendPacket(new ActivePacket());
2565    }
2566
2567    public void sendInactive() {
2568        this.sendPacket(new InactivePacket());
2569    }
2570
2571    public void resetAttemptCount(boolean resetConnectTime) {
2572        this.attempt = 0;
2573        if (resetConnectTime) {
2574            this.lastConnect = 0;
2575        }
2576    }
2577
2578    public void setInteractive(boolean interactive) {
2579        this.mInteractive = interactive;
2580    }
2581
2582    private IqGenerator getIqGenerator() {
2583        return mXmppConnectionService.getIqGenerator();
2584    }
2585
2586    private class MyKeyManager implements X509KeyManager {
2587        @Override
2588        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2589            return account.getPrivateKeyAlias();
2590        }
2591
2592        @Override
2593        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2594            return null;
2595        }
2596
2597        @Override
2598        public X509Certificate[] getCertificateChain(String alias) {
2599            Log.d(Config.LOGTAG, "getting certificate chain");
2600            try {
2601                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2602            } catch (final Exception e) {
2603                Log.d(Config.LOGTAG, "could not get certificate chain", e);
2604                return new X509Certificate[0];
2605            }
2606        }
2607
2608        @Override
2609        public String[] getClientAliases(String s, Principal[] principals) {
2610            final String alias = account.getPrivateKeyAlias();
2611            return alias != null ? new String[] {alias} : new String[0];
2612        }
2613
2614        @Override
2615        public String[] getServerAliases(String s, Principal[] principals) {
2616            return new String[0];
2617        }
2618
2619        @Override
2620        public PrivateKey getPrivateKey(String alias) {
2621            try {
2622                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2623            } catch (Exception e) {
2624                return null;
2625            }
2626        }
2627    }
2628
2629    private static class StateChangingError extends Error {
2630        private final Account.State state;
2631
2632        public StateChangingError(Account.State state) {
2633            this.state = state;
2634        }
2635    }
2636
2637    private static class StateChangingException extends IOException {
2638        private final Account.State state;
2639
2640        public StateChangingException(Account.State state) {
2641            this.state = state;
2642        }
2643    }
2644
2645    public class Features {
2646        XmppConnection connection;
2647        private boolean carbonsEnabled = false;
2648        private boolean encryptionEnabled = false;
2649        private boolean blockListRequested = false;
2650
2651        public Features(final XmppConnection connection) {
2652            this.connection = connection;
2653        }
2654
2655        private boolean hasDiscoFeature(final Jid server, final String feature) {
2656            synchronized (XmppConnection.this.disco) {
2657                final ServiceDiscoveryResult sdr = connection.disco.get(server);
2658                return sdr != null && sdr.getFeatures().contains(feature);
2659            }
2660        }
2661
2662        public boolean carbons() {
2663            return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2664        }
2665
2666        public boolean commands() {
2667            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2668        }
2669
2670        public boolean easyOnboardingInvites() {
2671            synchronized (commands) {
2672                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2673            }
2674        }
2675
2676        public boolean bookmarksConversion() {
2677            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2678                    && pepPublishOptions();
2679        }
2680
2681        public boolean avatarConversion() {
2682            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION)
2683                    && pepPublishOptions();
2684        }
2685
2686        public boolean blocking() {
2687            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2688        }
2689
2690        public boolean spamReporting() {
2691            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
2692        }
2693
2694        public boolean flexibleOfflineMessageRetrieval() {
2695            return hasDiscoFeature(
2696                    account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2697        }
2698
2699        public boolean register() {
2700            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2701        }
2702
2703        public boolean invite() {
2704            return connection.streamFeatures != null
2705                    && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2706        }
2707
2708        public boolean sm() {
2709            return streamId != null
2710                    || (connection.streamFeatures != null
2711                            && connection.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT));
2712        }
2713
2714        public boolean csi() {
2715            return connection.streamFeatures != null
2716                    && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2717        }
2718
2719        public boolean pep() {
2720            synchronized (XmppConnection.this.disco) {
2721                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2722                return info != null && info.hasIdentity("pubsub", "pep");
2723            }
2724        }
2725
2726        public boolean pepPersistent() {
2727            synchronized (XmppConnection.this.disco) {
2728                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2729                return info != null
2730                        && info.getFeatures()
2731                                .contains("http://jabber.org/protocol/pubsub#persistent-items");
2732            }
2733        }
2734
2735        public boolean pepPublishOptions() {
2736            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2737        }
2738
2739        public boolean pepOmemoWhitelisted() {
2740            return hasDiscoFeature(
2741                    account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2742        }
2743
2744        public boolean mam() {
2745            return MessageArchiveService.Version.has(getAccountFeatures());
2746        }
2747
2748        public List<String> getAccountFeatures() {
2749            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2750            return result == null ? Collections.emptyList() : result.getFeatures();
2751        }
2752
2753        public boolean push() {
2754            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2755                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2756        }
2757
2758        public boolean rosterVersioning() {
2759            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2760        }
2761
2762        public void setBlockListRequested(boolean value) {
2763            this.blockListRequested = value;
2764        }
2765
2766        public boolean httpUpload(long filesize) {
2767            if (Config.DISABLE_HTTP_UPLOAD) {
2768                return false;
2769            } else {
2770                for (String namespace :
2771                        new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2772                    List<Entry<Jid, ServiceDiscoveryResult>> items =
2773                            findDiscoItemsByFeature(namespace);
2774                    if (items.size() > 0) {
2775                        try {
2776                            long maxsize =
2777                                    Long.parseLong(
2778                                            items.get(0)
2779                                                    .getValue()
2780                                                    .getExtendedDiscoInformation(
2781                                                            namespace, "max-file-size"));
2782                            if (filesize <= maxsize) {
2783                                return true;
2784                            } else {
2785                                Log.d(
2786                                        Config.LOGTAG,
2787                                        account.getJid().asBareJid()
2788                                                + ": http upload is not available for files with size "
2789                                                + filesize
2790                                                + " (max is "
2791                                                + maxsize
2792                                                + ")");
2793                                return false;
2794                            }
2795                        } catch (Exception e) {
2796                            return true;
2797                        }
2798                    }
2799                }
2800                return false;
2801            }
2802        }
2803
2804        public boolean useLegacyHttpUpload() {
2805            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
2806                    && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2807        }
2808
2809        public long getMaxHttpUploadSize() {
2810            for (String namespace :
2811                    new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2812                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2813                if (items.size() > 0) {
2814                    try {
2815                        return Long.parseLong(
2816                                items.get(0)
2817                                        .getValue()
2818                                        .getExtendedDiscoInformation(namespace, "max-file-size"));
2819                    } catch (Exception e) {
2820                        // ignored
2821                    }
2822                }
2823            }
2824            return -1;
2825        }
2826
2827        public boolean stanzaIds() {
2828            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2829        }
2830
2831        public boolean bookmarks2() {
2832            return Config
2833                    .USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2834        }
2835
2836        public boolean externalServiceDiscovery() {
2837            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2838        }
2839    }
2840}