XmppConnection.java

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