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                if (processSuccess(success)) {
 474                    break;
 475                }
 476
 477            } else if (nextTag.isStart("failure", Namespace.TLS)) {
 478                throw new StateChangingException(Account.State.TLS_ERROR);
 479            } else if (nextTag.isStart("failure")) {
 480                final Element failure = tagReader.readElement(nextTag);
 481                final SaslMechanism.Version version;
 482                try {
 483                    version = SaslMechanism.Version.of(failure);
 484                } catch (final IllegalArgumentException e) {
 485                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 486                }
 487                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
 488                if (failure.hasChild("temporary-auth-failure")) {
 489                    throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
 490                } else if (failure.hasChild("account-disabled")) {
 491                    final String text = failure.findChildContent("text");
 492                    if (Strings.isNullOrEmpty(text)) {
 493                        throw new StateChangingException(Account.State.UNAUTHORIZED);
 494                    }
 495                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 496                    if (matcher.find()) {
 497                        final HttpUrl url;
 498                        try {
 499                            url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
 500                        } catch (final IllegalArgumentException e) {
 501                            throw new StateChangingException(Account.State.UNAUTHORIZED);
 502                        }
 503                        if (url.isHttps()) {
 504                            this.redirectionUrl = url;
 505                            throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 506                        }
 507                    }
 508                }
 509                throw new StateChangingException(Account.State.UNAUTHORIZED);
 510            } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
 511                throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
 512            } else if (nextTag.isStart("challenge")) {
 513                final Element challenge = tagReader.readElement(nextTag);
 514                final SaslMechanism.Version version;
 515                try {
 516                    version = SaslMechanism.Version.of(challenge);
 517                } catch (final IllegalArgumentException e) {
 518                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 519                }
 520                final Element response;
 521                if (version == SaslMechanism.Version.SASL) {
 522                    response = new Element("response", Namespace.SASL);
 523                } else if (version == SaslMechanism.Version.SASL_2) {
 524                    response = new Element("response", Namespace.SASL_2);
 525                } else {
 526                    throw new AssertionError("Missing implementation for " + version);
 527                }
 528                try {
 529                    response.setContent(saslMechanism.getResponse(challenge.getContent()));
 530                } catch (final SaslMechanism.AuthenticationException e) {
 531                    // TODO: Send auth abort tag.
 532                    Log.e(Config.LOGTAG, e.toString());
 533                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 534                }
 535                tagWriter.writeElement(response);
 536            } else if (nextTag.isStart("enabled")) {
 537                final Element enabled = tagReader.readElement(nextTag);
 538                if (enabled.getAttributeAsBoolean("resume")) {
 539                    this.streamId = enabled.getAttribute("id");
 540                    Log.d(
 541                            Config.LOGTAG,
 542                            account.getJid().asBareJid().toString()
 543                                    + ": stream management("
 544                                    + smVersion
 545                                    + ") enabled (resumable)");
 546                } else {
 547                    Log.d(
 548                            Config.LOGTAG,
 549                            account.getJid().asBareJid().toString()
 550                                    + ": stream management("
 551                                    + smVersion
 552                                    + ") enabled");
 553                }
 554                this.stanzasReceived = 0;
 555                this.inSmacksSession = true;
 556                final RequestPacket r = new RequestPacket(smVersion);
 557                tagWriter.writeStanzaAsync(r);
 558            } else if (nextTag.isStart("resumed")) {
 559                final Element resumed = tagReader.readElement(nextTag);
 560                processResumed(resumed);
 561            } else if (nextTag.isStart("r")) {
 562                tagReader.readElement(nextTag);
 563                if (Config.EXTENDED_SM_LOGGING) {
 564                    Log.d(
 565                            Config.LOGTAG,
 566                            account.getJid().asBareJid()
 567                                    + ": acknowledging stanza #"
 568                                    + this.stanzasReceived);
 569                }
 570                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 571                tagWriter.writeStanzaAsync(ack);
 572            } else if (nextTag.isStart("a")) {
 573                boolean accountUiNeedsRefresh = false;
 574                synchronized (NotificationService.CATCHUP_LOCK) {
 575                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 576                        final int messageCount = mSmCatchupMessageCounter.get();
 577                        final int pendingIQs = packetCallbacks.size();
 578                        Log.d(
 579                                Config.LOGTAG,
 580                                account.getJid().asBareJid()
 581                                        + ": SM catchup complete (messages="
 582                                        + messageCount
 583                                        + ", pending IQs="
 584                                        + pendingIQs
 585                                        + ")");
 586                        accountUiNeedsRefresh = true;
 587                        if (messageCount > 0) {
 588                            mXmppConnectionService
 589                                    .getNotificationService()
 590                                    .finishBacklog(true, account);
 591                        }
 592                    }
 593                }
 594                if (accountUiNeedsRefresh) {
 595                    mXmppConnectionService.updateAccountUi();
 596                }
 597                final Element ack = tagReader.readElement(nextTag);
 598                lastPacketReceived = SystemClock.elapsedRealtime();
 599                try {
 600                    final boolean acknowledgedMessages;
 601                    synchronized (this.mStanzaQueue) {
 602                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 603                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 604                    }
 605                    if (acknowledgedMessages) {
 606                        mXmppConnectionService.updateConversationUi();
 607                    }
 608                } catch (NumberFormatException | NullPointerException e) {
 609                    Log.d(
 610                            Config.LOGTAG,
 611                            account.getJid().asBareJid()
 612                                    + ": server send ack without sequence number");
 613                }
 614            } else if (nextTag.isStart("failed")) {
 615                final Element failed = tagReader.readElement(nextTag);
 616                processFailed(failed, true);
 617            } else if (nextTag.isStart("iq")) {
 618                processIq(nextTag);
 619            } else if (nextTag.isStart("message")) {
 620                processMessage(nextTag);
 621            } else if (nextTag.isStart("presence")) {
 622                processPresence(nextTag);
 623            }
 624            nextTag = tagReader.readTag();
 625        }
 626        if (nextTag != null && nextTag.isEnd("stream")) {
 627            streamCountDownLatch.countDown();
 628        }
 629    }
 630
 631    private boolean processSuccess(final Element success) throws IOException, XmlPullParserException {
 632        final SaslMechanism.Version version;
 633        try {
 634            version = SaslMechanism.Version.of(success);
 635        } catch (final IllegalArgumentException e) {
 636            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 637        }
 638        final String challenge;
 639        if (version == SaslMechanism.Version.SASL) {
 640            challenge = success.getContent();
 641        } else if (version == SaslMechanism.Version.SASL_2) {
 642            challenge = success.findChildContent("additional-data");
 643        } else {
 644            throw new AssertionError("Missing implementation for " + version);
 645        }
 646        try {
 647            saslMechanism.getResponse(challenge);
 648        } catch (final SaslMechanism.AuthenticationException e) {
 649            Log.e(Config.LOGTAG, String.valueOf(e));
 650            throw new StateChangingException(Account.State.UNAUTHORIZED);
 651        }
 652        Log.d(
 653                Config.LOGTAG,
 654                account.getJid().asBareJid().toString()
 655                        + ": logged in (using "
 656                        + version
 657                        + ")");
 658        account.setKey(
 659                Account.PINNED_MECHANISM_KEY, String.valueOf(saslMechanism.getPriority()));
 660        if (version == SaslMechanism.Version.SASL_2) {
 661            final String authorizationIdentifier =
 662                    success.findChildContent("authorization-identifier");
 663            final Jid authorizationJid;
 664            try {
 665                authorizationJid = Strings.isNullOrEmpty(authorizationIdentifier) ? null : Jid.ofEscaped(authorizationIdentifier);
 666            } catch (final IllegalArgumentException e) {
 667                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": SASL 2.0 authorization identifier was not a valid jid");
 668                throw new StateChangingException(Account.State.BIND_FAILURE);
 669            }
 670            if (authorizationJid == null) {
 671                throw new StateChangingException(Account.State.BIND_FAILURE);
 672            }
 673            Log.d(
 674                    Config.LOGTAG,
 675                    account.getJid().asBareJid()
 676                            + ": SASL 2.0 authorization identifier was "
 677                            + authorizationJid);
 678            if (!account.getJid().getDomain().equals(authorizationJid.getDomain())) {
 679                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + authorizationJid.getDomain());
 680                throw new StateChangingError(Account.State.BIND_FAILURE);
 681            }
 682            if (authorizationJid.isFullJid() && account.setJid(authorizationJid)) {
 683                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during SASL 2.0. updating database");
 684                mXmppConnectionService.databaseBackend.updateAccount(account);
 685            }
 686            final Element resumed = success.findChild("resumed", "urn:xmpp:sm:3");
 687            final Element failed = success.findChild("failed", "urn:xmpp:sm:3");
 688            if (resumed != null && streamId != null) {
 689                processResumed(resumed);
 690            } else if (failed != null) {
 691                processFailed(failed, false); // wait for new stream features
 692            }
 693        }
 694        if (version == SaslMechanism.Version.SASL) {
 695            tagReader.reset();
 696            sendStartStream();
 697            final Tag tag = tagReader.readTag();
 698            if (tag != null && tag.isStart("stream")) {
 699                processStream();
 700                return true;
 701            } else {
 702                throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 703            }
 704        } else {
 705            return false;
 706        }
 707    }
 708
 709    private void processResumed(final Element resumed) throws StateChangingException {
 710        this.inSmacksSession = true;
 711        this.isBound = true;
 712        this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 713        lastPacketReceived = SystemClock.elapsedRealtime();
 714        final String h = resumed.getAttribute("h");
 715        if (h == null) {
 716            resetStreamId();
 717            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 718        }
 719        final int serverCount;
 720        try {
 721            serverCount = Integer.parseInt(h);
 722        } catch (final NumberFormatException e) {
 723            resetStreamId();
 724            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 725        }
 726        final ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 727        final boolean acknowledgedMessages;
 728        synchronized (this.mStanzaQueue) {
 729            if (serverCount < stanzasSent) {
 730                Log.d(
 731                        Config.LOGTAG,
 732                        account.getJid().asBareJid() + ": session resumed with lost packages");
 733                stanzasSent = serverCount;
 734            } else {
 735                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": session resumed");
 736            }
 737            acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 738            for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 739                failedStanzas.add(mStanzaQueue.valueAt(i));
 740            }
 741            mStanzaQueue.clear();
 742        }
 743        if (acknowledgedMessages) {
 744            mXmppConnectionService.updateConversationUi();
 745        }
 746        Log.d(
 747                Config.LOGTAG,
 748                account.getJid().asBareJid() + ": resending " + failedStanzas.size() + " stanzas");
 749        for (final AbstractAcknowledgeableStanza packet : failedStanzas) {
 750            if (packet instanceof MessagePacket) {
 751                MessagePacket message = (MessagePacket) packet;
 752                mXmppConnectionService.markMessage(
 753                        account,
 754                        message.getTo().asBareJid(),
 755                        message.getId(),
 756                        Message.STATUS_UNSEND);
 757            }
 758            sendPacket(packet);
 759        }
 760        Log.d(
 761                Config.LOGTAG,
 762                account.getJid().asBareJid() + ": online with resource " + account.getResource());
 763        changeStatus(Account.State.ONLINE);
 764    }
 765
 766    private void processFailed(final Element failed, final boolean sendBindRequest) {
 767        final int serverCount;
 768        try {
 769            serverCount = Integer.parseInt(failed.getAttribute("h"));
 770        } catch (final NumberFormatException | NullPointerException e) {
 771            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 772            resetStreamId();
 773            if (sendBindRequest) {
 774                sendBindRequest();
 775            }
 776            return;
 777        }
 778        Log.d(
 779                Config.LOGTAG,
 780                account.getJid().asBareJid()
 781                        + ": resumption failed but server acknowledged stanza #"
 782                        + serverCount);
 783        final boolean acknowledgedMessages;
 784        synchronized (this.mStanzaQueue) {
 785            acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 786        }
 787        if (acknowledgedMessages) {
 788            mXmppConnectionService.updateConversationUi();
 789        }
 790        resetStreamId();
 791        if (sendBindRequest) {
 792            sendBindRequest();
 793        }
 794    }
 795
 796    private boolean acknowledgeStanzaUpTo(int serverCount) {
 797        if (serverCount > stanzasSent) {
 798            Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 799        }
 800        boolean acknowledgedMessages = false;
 801        for (int i = 0; i < mStanzaQueue.size(); ++i) {
 802            if (serverCount >= mStanzaQueue.keyAt(i)) {
 803                if (Config.EXTENDED_SM_LOGGING) {
 804                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 805                }
 806                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 807                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 808                    final MessagePacket packet = (MessagePacket) stanza;
 809                    final String id = packet.getId();
 810                    final Jid to = packet.getTo();
 811                    if (id != null && to != null) {
 812                        acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, to, id);
 813                    }
 814                }
 815                mStanzaQueue.removeAt(i);
 816                i--;
 817            }
 818        }
 819        return acknowledgedMessages;
 820    }
 821
 822    private @NonNull
 823    Element processPacket(final Tag currentTag, final int packetType) throws IOException {
 824        final Element element;
 825        switch (packetType) {
 826            case PACKET_IQ:
 827                element = new IqPacket();
 828                break;
 829            case PACKET_MESSAGE:
 830                element = new MessagePacket();
 831                break;
 832            case PACKET_PRESENCE:
 833                element = new PresencePacket();
 834                break;
 835            default:
 836                throw new AssertionError("Should never encounter invalid type");
 837        }
 838        element.setAttributes(currentTag.getAttributes());
 839        Tag nextTag = tagReader.readTag();
 840        if (nextTag == null) {
 841            throw new IOException("interrupted mid tag");
 842        }
 843        while (!nextTag.isEnd(element.getName())) {
 844            if (!nextTag.isNo()) {
 845                element.addChild(tagReader.readElement(nextTag));
 846            }
 847            nextTag = tagReader.readTag();
 848            if (nextTag == null) {
 849                throw new IOException("interrupted mid tag");
 850            }
 851        }
 852        if (stanzasReceived == Integer.MAX_VALUE) {
 853            resetStreamId();
 854            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 855        }
 856        if (inSmacksSession) {
 857            ++stanzasReceived;
 858        } else if (features.sm()) {
 859            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 860        }
 861        lastPacketReceived = SystemClock.elapsedRealtime();
 862        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 863            Log.d(Config.LOGTAG, "[background stanza] " + element);
 864        }
 865        if (element instanceof IqPacket
 866                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
 867                && element.hasChild("jingle", Namespace.JINGLE)) {
 868            return JinglePacket.upgrade((IqPacket) element);
 869        } else {
 870            return element;
 871        }
 872    }
 873
 874    private void processIq(final Tag currentTag) throws IOException {
 875        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 876        if (!packet.valid()) {
 877            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 878            return;
 879        }
 880        if (packet instanceof JinglePacket) {
 881            if (this.jingleListener != null) {
 882                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 883            }
 884        } else {
 885            OnIqPacketReceived callback = null;
 886            synchronized (this.packetCallbacks) {
 887                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 888                if (packetCallbackDuple != null) {
 889                    // Packets to the server should have responses from the server
 890                    if (packetCallbackDuple.first.toServer(account)) {
 891                        if (packet.fromServer(account)) {
 892                            callback = packetCallbackDuple.second;
 893                            packetCallbacks.remove(packet.getId());
 894                        } else {
 895                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 896                        }
 897                    } else {
 898                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 899                            callback = packetCallbackDuple.second;
 900                            packetCallbacks.remove(packet.getId());
 901                        } else {
 902                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 903                        }
 904                    }
 905                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 906                    callback = this.unregisteredIqListener;
 907                }
 908            }
 909            if (callback != null) {
 910                try {
 911                    callback.onIqPacketReceived(account, packet);
 912                } catch (StateChangingError error) {
 913                    throw new StateChangingException(error.state);
 914                }
 915            }
 916        }
 917    }
 918
 919    private void processMessage(final Tag currentTag) throws IOException {
 920        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 921        if (!packet.valid()) {
 922            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 923            return;
 924        }
 925        this.messageListener.onMessagePacketReceived(account, packet);
 926    }
 927
 928    private void processPresence(final Tag currentTag) throws IOException {
 929        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 930        if (!packet.valid()) {
 931            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 932            return;
 933        }
 934        this.presenceListener.onPresencePacketReceived(account, packet);
 935    }
 936
 937    private void sendStartTLS() throws IOException {
 938        final Tag startTLS = Tag.empty("starttls");
 939        startTLS.setAttribute("xmlns", Namespace.TLS);
 940        tagWriter.writeTag(startTLS);
 941    }
 942
 943    private void switchOverToTls() throws XmlPullParserException, IOException {
 944        tagReader.readTag();
 945        final Socket socket = this.socket;
 946        final SSLSocket sslSocket = upgradeSocketToTls(socket);
 947        tagReader.setInputStream(sslSocket.getInputStream());
 948        tagWriter.setOutputStream(sslSocket.getOutputStream());
 949        sendStartStream();
 950        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 951        features.encryptionEnabled = true;
 952        final Tag tag = tagReader.readTag();
 953        if (tag != null && tag.isStart("stream")) {
 954            SSLSocketHelper.log(account, sslSocket);
 955            processStream();
 956        } else {
 957            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 958        }
 959        sslSocket.close();
 960    }
 961
 962    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
 963        final SSLSocketFactory sslSocketFactory;
 964        try {
 965            sslSocketFactory = getSSLSocketFactory();
 966        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
 967            throw new StateChangingException(Account.State.TLS_ERROR);
 968        }
 969        final InetAddress address = socket.getInetAddress();
 970        final SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 971        SSLSocketHelper.setSecurity(sslSocket);
 972        SSLSocketHelper.setHostname(sslSocket, IDN.toASCII(account.getServer()));
 973        SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 974        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
 975        try {
 976            if (!xmppDomainVerifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 977                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate domain verification failed");
 978                FileBackend.close(sslSocket);
 979                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
 980            }
 981        } catch (final SSLPeerUnverifiedException e) {
 982            FileBackend.close(sslSocket);
 983            throw new StateChangingException(Account.State.TLS_ERROR);
 984        }
 985        return sslSocket;
 986    }
 987
 988    private void processStreamFeatures(final Tag currentTag) throws IOException {
 989        this.streamFeatures = tagReader.readElement(currentTag);
 990        final boolean isSecure =
 991                features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 992        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 993        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
 994                && !features.encryptionEnabled) {
 995            sendStartTLS();
 996        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
 997                && account.isOptionSet(Account.OPTION_REGISTER)) {
 998            if (isSecure) {
 999                register();
1000            } else {
1001                Log.d(
1002                        Config.LOGTAG,
1003                        account.getJid().asBareJid()
1004                                + ": unable to find STARTTLS for registration process "
1005                                + XmlHelper.printElementNames(this.streamFeatures));
1006                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1007            }
1008        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1009                && account.isOptionSet(Account.OPTION_REGISTER)) {
1010            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1011        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL_2)
1012                && shouldAuthenticate
1013                && isSecure) {
1014            authenticate(SaslMechanism.Version.SASL_2);
1015        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1016                && shouldAuthenticate
1017                && isSecure) {
1018            authenticate(SaslMechanism.Version.SASL);
1019        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion)
1020                && streamId != null) {
1021            if (Config.EXTENDED_SM_LOGGING) {
1022                Log.d(
1023                        Config.LOGTAG,
1024                        account.getJid().asBareJid()
1025                                + ": resuming after stanza #"
1026                                + stanzasReceived);
1027            }
1028            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
1029            this.mSmCatchupMessageCounter.set(0);
1030            this.mWaitingForSmCatchup.set(true);
1031            this.tagWriter.writeStanzaAsync(resume);
1032        } else if (needsBinding) {
1033            if (this.streamFeatures.hasChild("bind", Namespace.BIND) && isSecure) {
1034                sendBindRequest();
1035            } else {
1036                Log.d(
1037                        Config.LOGTAG,
1038                        account.getJid().asBareJid()
1039                                + ": unable to find bind feature "
1040                                + XmlHelper.printElementNames(this.streamFeatures));
1041                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1042            }
1043        } else {
1044            Log.d(
1045                    Config.LOGTAG,
1046                    account.getJid().asBareJid()
1047                            + ": received NOP stream features "
1048                            + this.streamFeatures);
1049        }
1050    }
1051
1052    private void authenticate(final SaslMechanism.Version version) throws IOException {
1053        final List<String> mechanisms = extractMechanisms(streamFeatures.findChild("mechanisms"));
1054        if (mechanisms.contains(External.MECHANISM) && account.getPrivateKeyAlias() != null) {
1055            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
1056        } else if (mechanisms.contains(ScramSha512.MECHANISM)) {
1057            saslMechanism = new ScramSha512(tagWriter, account, mXmppConnectionService.getRNG());
1058        } else if (mechanisms.contains(ScramSha256.MECHANISM)) {
1059            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
1060        } else if (mechanisms.contains(ScramSha1.MECHANISM)) {
1061            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
1062        } else if (mechanisms.contains(Plain.MECHANISM) && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
1063            saslMechanism = new Plain(tagWriter, account);
1064        } else if (mechanisms.contains(DigestMd5.MECHANISM)) {
1065            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
1066        } else if (mechanisms.contains(Anonymous.MECHANISM)) {
1067            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
1068        }
1069        if (saslMechanism == null) {
1070            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find supported SASL mechanism in " + mechanisms);
1071            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1072        }
1073        final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
1074        if (pinnedMechanism > saslMechanism.getPriority()) {
1075            Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
1076                    " has lower priority (" + saslMechanism.getPriority() +
1077                    ") than pinned priority (" + pinnedMechanism +
1078                    "). Possible downgrade attack?");
1079            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1080        }
1081        final String firstMessage = saslMechanism.getClientFirstMessage();
1082        final Element authenticate;
1083        if (version == SaslMechanism.Version.SASL) {
1084            authenticate = new Element("auth", Namespace.SASL);
1085            if (!Strings.isNullOrEmpty(firstMessage)) {
1086                authenticate.setContent(firstMessage);
1087            }
1088        } else if (version == SaslMechanism.Version.SASL_2) {
1089            authenticate = new Element("authenticate", Namespace.SASL_2);
1090            if (!Strings.isNullOrEmpty(firstMessage)) {
1091                authenticate.addChild("initial-response").setContent(firstMessage);
1092            }
1093            final Element inline = this.streamFeatures.findChild("inline", Namespace.SASL_2);
1094            final boolean inlineStreamManagement = inline != null && inline.hasChild("sm", "urn:xmpp:sm:3");
1095            if (inlineStreamManagement && streamId != null) {
1096                final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
1097                this.mSmCatchupMessageCounter.set(0);
1098                this.mWaitingForSmCatchup.set(true);
1099                authenticate.addChild(resume);
1100            }
1101        } else {
1102            throw new AssertionError("Missing implementation for " + version);
1103        }
1104
1105        Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with "+version+ "/" + saslMechanism.getMechanism());
1106        authenticate.setAttribute("mechanism", saslMechanism.getMechanism());
1107        tagWriter.writeElement(authenticate);
1108    }
1109
1110    private static List<String> extractMechanisms(final Element stream) {
1111        final ArrayList<String> mechanisms = new ArrayList<>(stream
1112                .getChildren().size());
1113        for (final Element child : stream.getChildren()) {
1114            mechanisms.add(child.getContent());
1115        }
1116        return mechanisms;
1117    }
1118
1119
1120    private void register() {
1121        final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
1122        if (preAuth != null && features.invite()) {
1123            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1124            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1125            sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
1126                if (response.getType() == IqPacket.TYPE.RESULT) {
1127                    sendRegistryRequest();
1128                } else {
1129                    final String error = response.getErrorCondition();
1130                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to pre auth. " + error);
1131                    throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1132                }
1133            }, true);
1134        } else {
1135            sendRegistryRequest();
1136        }
1137    }
1138
1139    private void sendRegistryRequest() {
1140        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1141        register.query(Namespace.REGISTER);
1142        register.setTo(account.getDomain());
1143        sendUnmodifiedIqPacket(register, (account, packet) -> {
1144            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1145                return;
1146            }
1147            if (packet.getType() == IqPacket.TYPE.ERROR) {
1148                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1149            }
1150            final Element query = packet.query(Namespace.REGISTER);
1151            if (query.hasChild("username") && (query.hasChild("password"))) {
1152                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1153                final Element username = new Element("username").setContent(account.getUsername());
1154                final Element password = new Element("password").setContent(account.getPassword());
1155                register1.query(Namespace.REGISTER).addChild(username);
1156                register1.query().addChild(password);
1157                register1.setFrom(account.getJid().asBareJid());
1158                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1159            } else if (query.hasChild("x", Namespace.DATA)) {
1160                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1161                final Element blob = query.findChild("data", "urn:xmpp:bob");
1162                final String id = packet.getId();
1163                InputStream is;
1164                if (blob != null) {
1165                    try {
1166                        final String base64Blob = blob.getContent();
1167                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1168                        is = new ByteArrayInputStream(strBlob);
1169                    } catch (Exception e) {
1170                        is = null;
1171                    }
1172                } else {
1173                    final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
1174                    try {
1175                        final String url = data.getValue("url");
1176                        final String fallbackUrl = data.getValue("captcha-fallback-url");
1177                        if (url != null) {
1178                            is = HttpConnectionManager.open(url, useTor);
1179                        } else if (fallbackUrl != null) {
1180                            is = HttpConnectionManager.open(fallbackUrl, useTor);
1181                        } else {
1182                            is = null;
1183                        }
1184                    } catch (final IOException e) {
1185                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to fetch captcha", e);
1186                        is = null;
1187                    }
1188                }
1189
1190                if (is != null) {
1191                    Bitmap captcha = BitmapFactory.decodeStream(is);
1192                    try {
1193                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
1194                            return;
1195                        }
1196                    } catch (Exception e) {
1197                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1198                    }
1199                }
1200                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1201            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
1202                final String instructions = query.findChildContent("instructions");
1203                final Element oob = query.findChild("x", Namespace.OOB);
1204                final String url = oob == null ? null : oob.findChildContent("url");
1205                if (url != null) {
1206                    setAccountCreationFailed(url);
1207                } else if (instructions != null) {
1208                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1209                    if (matcher.find()) {
1210                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1211                    }
1212                }
1213                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1214            }
1215        }, true);
1216    }
1217
1218    private void setAccountCreationFailed(final String url) {
1219        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1220        if (httpUrl != null && httpUrl.isHttps()) {
1221            this.redirectionUrl = httpUrl;
1222            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1223        }
1224        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1225    }
1226
1227    public HttpUrl getRedirectionUrl() {
1228        return this.redirectionUrl;
1229    }
1230
1231    public void resetEverything() {
1232        resetAttemptCount(true);
1233        resetStreamId();
1234        clearIqCallbacks();
1235        this.stanzasSent = 0;
1236        mStanzaQueue.clear();
1237        this.redirectionUrl = null;
1238        synchronized (this.disco) {
1239            disco.clear();
1240        }
1241        synchronized (this.commands) {
1242            this.commands.clear();
1243        }
1244    }
1245
1246    private void sendBindRequest() {
1247        try {
1248            mXmppConnectionService.restoredFromDatabaseLatch.await();
1249        } catch (InterruptedException e) {
1250            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1251            return;
1252        }
1253        clearIqCallbacks();
1254        if (account.getJid().isBareJid()) {
1255            account.setResource(this.createNewResource());
1256        } else {
1257            fixResource(mXmppConnectionService, account);
1258        }
1259        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1260        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1261        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1262        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1263            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1264                return;
1265            }
1266            final Element bind = packet.findChild("bind");
1267            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1268                isBound = true;
1269                final Element jid = bind.findChild("jid");
1270                if (jid != null && jid.getContent() != null) {
1271                    try {
1272                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1273                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1274                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1275                            throw new StateChangingError(Account.State.BIND_FAILURE);
1276                        }
1277                        if (account.setJid(assignedJid)) {
1278                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1279                            mXmppConnectionService.databaseBackend.updateAccount(account);
1280                        }
1281                        if (streamFeatures.hasChild("session")
1282                                && !streamFeatures.findChild("session").hasChild("optional")) {
1283                            sendStartSession();
1284                        } else {
1285                            sendPostBindInitialization();
1286                        }
1287                        return;
1288                    } catch (final IllegalArgumentException e) {
1289                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1290                    }
1291                } else {
1292                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1293                }
1294            } else {
1295                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet);
1296            }
1297            final Element error = packet.findChild("error");
1298            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1299                account.setResource(createNewResource());
1300            }
1301            throw new StateChangingError(Account.State.BIND_FAILURE);
1302        }, true);
1303    }
1304
1305    private void clearIqCallbacks() {
1306        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1307        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1308        synchronized (this.packetCallbacks) {
1309            if (this.packetCallbacks.size() == 0) {
1310                return;
1311            }
1312            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1313            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1314            while (iterator.hasNext()) {
1315                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1316                callbacks.add(entry.second);
1317                iterator.remove();
1318            }
1319        }
1320        for (OnIqPacketReceived callback : callbacks) {
1321            try {
1322                callback.onIqPacketReceived(account, failurePacket);
1323            } catch (StateChangingError error) {
1324                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1325                //ignore
1326            }
1327        }
1328        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1329    }
1330
1331    public void sendDiscoTimeout() {
1332        if (mWaitForDisco.compareAndSet(true, false)) {
1333            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1334            finalizeBind();
1335        }
1336    }
1337
1338    private void sendStartSession() {
1339        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1340        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1341        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1342        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1343            if (packet.getType() == IqPacket.TYPE.RESULT) {
1344                sendPostBindInitialization();
1345            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1346                throw new StateChangingError(Account.State.SESSION_FAILURE);
1347            }
1348        }, true);
1349    }
1350
1351    private void sendPostBindInitialization() {
1352        smVersion = 0;
1353        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1354            smVersion = 3;
1355        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1356            smVersion = 2;
1357        }
1358        if (smVersion != 0) {
1359            synchronized (this.mStanzaQueue) {
1360                final EnablePacket enable = new EnablePacket(smVersion);
1361                tagWriter.writeStanzaAsync(enable);
1362                stanzasSent = 0;
1363                mStanzaQueue.clear();
1364            }
1365        }
1366        features.carbonsEnabled = false;
1367        features.blockListRequested = false;
1368        synchronized (this.disco) {
1369            this.disco.clear();
1370        }
1371        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1372        mPendingServiceDiscoveries.set(0);
1373        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain().toEscapedString())) {
1374            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1375            mWaitForDisco.set(false);
1376        } else {
1377            mWaitForDisco.set(true);
1378        }
1379        lastDiscoStarted = SystemClock.elapsedRealtime();
1380        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1381        Element caps = streamFeatures.findChild("c");
1382        final String hash = caps == null ? null : caps.getAttribute("hash");
1383        final String ver = caps == null ? null : caps.getAttribute("ver");
1384        ServiceDiscoveryResult discoveryResult = null;
1385        if (hash != null && ver != null) {
1386            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1387        }
1388        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1389        if (requestDiscoItemsFirst) {
1390            sendServiceDiscoveryItems(account.getDomain());
1391        }
1392        if (discoveryResult == null) {
1393            sendServiceDiscoveryInfo(account.getDomain());
1394        } else {
1395            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1396            disco.put(account.getDomain(), discoveryResult);
1397        }
1398        discoverMamPreferences();
1399        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1400        if (!requestDiscoItemsFirst) {
1401            sendServiceDiscoveryItems(account.getDomain());
1402        }
1403
1404        if (!mWaitForDisco.get()) {
1405            finalizeBind();
1406        }
1407        this.lastSessionStarted = SystemClock.elapsedRealtime();
1408    }
1409
1410    private void sendServiceDiscoveryInfo(final Jid jid) {
1411        mPendingServiceDiscoveries.incrementAndGet();
1412        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1413        iq.setTo(jid);
1414        iq.query("http://jabber.org/protocol/disco#info");
1415        this.sendIqPacket(iq, (account, packet) -> {
1416            if (packet.getType() == IqPacket.TYPE.RESULT) {
1417                boolean advancedStreamFeaturesLoaded;
1418                synchronized (XmppConnection.this.disco) {
1419                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1420                    if (jid.equals(account.getDomain())) {
1421                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1422                    }
1423                    disco.put(jid, result);
1424                    advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain())
1425                            && disco.containsKey(account.getJid().asBareJid());
1426                }
1427                if (advancedStreamFeaturesLoaded && (jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid()))) {
1428                    enableAdvancedStreamFeatures();
1429                }
1430            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1431                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1432                final boolean serverOrAccount = jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid());
1433                final boolean advancedStreamFeaturesLoaded;
1434                if (serverOrAccount) {
1435                    synchronized (XmppConnection.this.disco) {
1436                        disco.put(jid, ServiceDiscoveryResult.empty());
1437                        advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain()) && disco.containsKey(account.getJid().asBareJid());
1438                    }
1439                } else {
1440                    advancedStreamFeaturesLoaded = false;
1441                }
1442                if (advancedStreamFeaturesLoaded) {
1443                    enableAdvancedStreamFeatures();
1444                }
1445            }
1446            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1447                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1448                        && mWaitForDisco.compareAndSet(true, false)) {
1449                    finalizeBind();
1450                }
1451            }
1452        });
1453    }
1454
1455    private void discoverMamPreferences() {
1456        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1457        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1458        sendIqPacket(request, (account, response) -> {
1459            if (response.getType() == IqPacket.TYPE.RESULT) {
1460                Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1461                isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1462            }
1463        });
1464    }
1465
1466    private void discoverCommands() {
1467        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1468        request.setTo(account.getDomain());
1469        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1470        sendIqPacket(request, (account, response) -> {
1471            if (response.getType() == IqPacket.TYPE.RESULT) {
1472                final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1473                if (query == null) {
1474                    return;
1475                }
1476                final HashMap<String, Jid> commands = new HashMap<>();
1477                for (final Element child : query.getChildren()) {
1478                    if ("item".equals(child.getName())) {
1479                        final String node = child.getAttribute("node");
1480                        final Jid jid = child.getAttributeAsJid("jid");
1481                        if (node != null && jid != null) {
1482                            commands.put(node, jid);
1483                        }
1484                    }
1485                }
1486                Log.d(Config.LOGTAG, commands.toString());
1487                synchronized (this.commands) {
1488                    this.commands.clear();
1489                    this.commands.putAll(commands);
1490                }
1491            }
1492        });
1493    }
1494
1495    public boolean isMamPreferenceAlways() {
1496        return isMamPreferenceAlways;
1497    }
1498
1499    private void finalizeBind() {
1500        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1501        if (bindListener != null) {
1502            bindListener.onBind(account);
1503        }
1504        changeStatus(Account.State.ONLINE);
1505    }
1506
1507    private void enableAdvancedStreamFeatures() {
1508        if (getFeatures().blocking() && !features.blockListRequested) {
1509            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1510            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1511        }
1512        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1513            listener.onAdvancedStreamFeaturesAvailable(account);
1514        }
1515        if (getFeatures().carbons() && !features.carbonsEnabled) {
1516            sendEnableCarbons();
1517        }
1518        if (getFeatures().commands()) {
1519            discoverCommands();
1520        }
1521    }
1522
1523    private void sendServiceDiscoveryItems(final Jid server) {
1524        mPendingServiceDiscoveries.incrementAndGet();
1525        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1526        iq.setTo(server.getDomain());
1527        iq.query("http://jabber.org/protocol/disco#items");
1528        this.sendIqPacket(iq, (account, packet) -> {
1529            if (packet.getType() == IqPacket.TYPE.RESULT) {
1530                final HashSet<Jid> items = new HashSet<>();
1531                final List<Element> elements = packet.query().getChildren();
1532                for (final Element element : elements) {
1533                    if (element.getName().equals("item")) {
1534                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1535                        if (jid != null && !jid.equals(account.getDomain())) {
1536                            items.add(jid);
1537                        }
1538                    }
1539                }
1540                for (Jid jid : items) {
1541                    sendServiceDiscoveryInfo(jid);
1542                }
1543            } else {
1544                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1545            }
1546            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1547                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1548                        && mWaitForDisco.compareAndSet(true, false)) {
1549                    finalizeBind();
1550                }
1551            }
1552        });
1553    }
1554
1555    private void sendEnableCarbons() {
1556        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1557        iq.addChild("enable", "urn:xmpp:carbons:2");
1558        this.sendIqPacket(iq, (account, packet) -> {
1559            if (!packet.hasChild("error")) {
1560                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1561                        + ": successfully enabled carbons");
1562                features.carbonsEnabled = true;
1563            } else {
1564                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1565                        + ": could not enable carbons " + packet);
1566            }
1567        });
1568    }
1569
1570    private void processStreamError(final Tag currentTag) throws IOException {
1571        final Element streamError = tagReader.readElement(currentTag);
1572        if (streamError == null) {
1573            return;
1574        }
1575        if (streamError.hasChild("conflict")) {
1576            account.setResource(createNewResource());
1577            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1578            throw new IOException();
1579        } else if (streamError.hasChild("host-unknown")) {
1580            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1581        } else if (streamError.hasChild("policy-violation")) {
1582            this.lastConnect = SystemClock.elapsedRealtime();
1583            final String text = streamError.findChildContent("text");
1584            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1585            failPendingMessages(text);
1586            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1587        } else {
1588            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
1589            throw new StateChangingException(Account.State.STREAM_ERROR);
1590        }
1591    }
1592
1593    private void failPendingMessages(final String error) {
1594        synchronized (this.mStanzaQueue) {
1595            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1596                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1597                if (stanza instanceof MessagePacket) {
1598                    final MessagePacket packet = (MessagePacket) stanza;
1599                    final String id = packet.getId();
1600                    final Jid to = packet.getTo();
1601                    mXmppConnectionService.markMessage(account,
1602                            to.asBareJid(),
1603                            id,
1604                            Message.STATUS_SEND_FAILED,
1605                            error);
1606                }
1607            }
1608        }
1609    }
1610
1611    private void sendStartStream() throws IOException {
1612        final Tag stream = Tag.start("stream:stream");
1613        stream.setAttribute("to", account.getServer());
1614        stream.setAttribute("version", "1.0");
1615        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1616        stream.setAttribute("xmlns", "jabber:client");
1617        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1618        tagWriter.writeTag(stream);
1619    }
1620
1621    private String createNewResource() {
1622        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1623    }
1624
1625    private String nextRandomId() {
1626        return nextRandomId(false);
1627    }
1628
1629    private String nextRandomId(boolean s) {
1630        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1631    }
1632
1633    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1634        packet.setFrom(account.getJid());
1635        return this.sendUnmodifiedIqPacket(packet, callback, false);
1636    }
1637
1638    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1639        if (packet.getId() == null) {
1640            packet.setAttribute("id", nextRandomId());
1641        }
1642        if (callback != null) {
1643            synchronized (this.packetCallbacks) {
1644                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1645            }
1646        }
1647        this.sendPacket(packet, force);
1648        return packet.getId();
1649    }
1650
1651    public void sendMessagePacket(final MessagePacket packet) {
1652        this.sendPacket(packet);
1653    }
1654
1655    public void sendPresencePacket(final PresencePacket packet) {
1656        this.sendPacket(packet);
1657    }
1658
1659    private synchronized void sendPacket(final AbstractStanza packet) {
1660        sendPacket(packet, false);
1661    }
1662
1663    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1664        if (stanzasSent == Integer.MAX_VALUE) {
1665            resetStreamId();
1666            disconnect(true);
1667            return;
1668        }
1669        synchronized (this.mStanzaQueue) {
1670            if (force || isBound) {
1671                tagWriter.writeStanzaAsync(packet);
1672            } else {
1673                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1674            }
1675            if (packet instanceof AbstractAcknowledgeableStanza) {
1676                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1677
1678                if (this.mStanzaQueue.size() != 0) {
1679                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1680                    if (currentHighestKey != stanzasSent) {
1681                        throw new AssertionError("Stanza count messed up");
1682                    }
1683                }
1684
1685                ++stanzasSent;
1686                this.mStanzaQueue.append(stanzasSent, stanza);
1687                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1688                    if (Config.EXTENDED_SM_LOGGING) {
1689                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1690                    }
1691                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1692                }
1693            }
1694        }
1695    }
1696
1697    public void sendPing() {
1698        if (!r()) {
1699            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1700            iq.setFrom(account.getJid());
1701            iq.addChild("ping", Namespace.PING);
1702            this.sendIqPacket(iq, null);
1703        }
1704        this.lastPingSent = SystemClock.elapsedRealtime();
1705    }
1706
1707    public void setOnMessagePacketReceivedListener(
1708            final OnMessagePacketReceived listener) {
1709        this.messageListener = listener;
1710    }
1711
1712    public void setOnUnregisteredIqPacketReceivedListener(
1713            final OnIqPacketReceived listener) {
1714        this.unregisteredIqListener = listener;
1715    }
1716
1717    public void setOnPresencePacketReceivedListener(
1718            final OnPresencePacketReceived listener) {
1719        this.presenceListener = listener;
1720    }
1721
1722    public void setOnJinglePacketReceivedListener(
1723            final OnJinglePacketReceived listener) {
1724        this.jingleListener = listener;
1725    }
1726
1727    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1728        this.statusListener = listener;
1729    }
1730
1731    public void setOnBindListener(final OnBindListener listener) {
1732        this.bindListener = listener;
1733    }
1734
1735    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1736        this.acknowledgedListener = listener;
1737    }
1738
1739    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1740        this.advancedStreamFeaturesLoadedListeners.add(listener);
1741    }
1742
1743    private void forceCloseSocket() {
1744        FileBackend.close(this.socket);
1745        FileBackend.close(this.tagReader);
1746    }
1747
1748    public void interrupt() {
1749        if (this.mThread != null) {
1750            this.mThread.interrupt();
1751        }
1752    }
1753
1754    public void disconnect(final boolean force) {
1755        interrupt();
1756        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1757        if (force) {
1758            forceCloseSocket();
1759        } else {
1760            final TagWriter currentTagWriter = this.tagWriter;
1761            if (currentTagWriter.isActive()) {
1762                currentTagWriter.finish();
1763                final Socket currentSocket = this.socket;
1764                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1765                try {
1766                    currentTagWriter.await(1, TimeUnit.SECONDS);
1767                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1768                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1769                    if (streamCountDownLatch != null) {
1770                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1771                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1772                        } else {
1773                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1774                        }
1775                    }
1776                } catch (InterruptedException e) {
1777                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1778                } catch (final IOException e) {
1779                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1780                } finally {
1781                    FileBackend.close(currentSocket);
1782                }
1783            } else {
1784                forceCloseSocket();
1785            }
1786        }
1787    }
1788
1789    private void resetStreamId() {
1790        this.streamId = null;
1791    }
1792
1793    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1794        synchronized (this.disco) {
1795            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1796            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1797                if (cursor.getValue().getFeatures().contains(feature)) {
1798                    items.add(cursor);
1799                }
1800            }
1801            return items;
1802        }
1803    }
1804
1805    public Jid findDiscoItemByFeature(final String feature) {
1806        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1807        if (items.size() >= 1) {
1808            return items.get(0).getKey();
1809        }
1810        return null;
1811    }
1812
1813    public boolean r() {
1814        if (getFeatures().sm()) {
1815            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1816            return true;
1817        } else {
1818            return false;
1819        }
1820    }
1821
1822    public List<String> getMucServersWithholdAccount() {
1823        final List<String> servers = getMucServers();
1824        servers.remove(account.getDomain().toEscapedString());
1825        return servers;
1826    }
1827
1828    public List<String> getMucServers() {
1829        List<String> servers = new ArrayList<>();
1830        synchronized (this.disco) {
1831            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1832                final ServiceDiscoveryResult value = cursor.getValue();
1833                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1834                        && value.hasIdentity("conference", "text")
1835                        && !value.getFeatures().contains("jabber:iq:gateway")
1836                        && !value.hasIdentity("conference", "irc")) {
1837                    servers.add(cursor.getKey().toString());
1838                }
1839            }
1840        }
1841        return servers;
1842    }
1843
1844    public String getMucServer() {
1845        List<String> servers = getMucServers();
1846        return servers.size() > 0 ? servers.get(0) : null;
1847    }
1848
1849    public int getTimeToNextAttempt() {
1850        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1851        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1852        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1853        return interval - secondsSinceLast;
1854    }
1855
1856    public int getAttempt() {
1857        return this.attempt;
1858    }
1859
1860    public Features getFeatures() {
1861        return this.features;
1862    }
1863
1864    public long getLastSessionEstablished() {
1865        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1866        return System.currentTimeMillis() - diff;
1867    }
1868
1869    public long getLastConnect() {
1870        return this.lastConnect;
1871    }
1872
1873    public long getLastPingSent() {
1874        return this.lastPingSent;
1875    }
1876
1877    public long getLastDiscoStarted() {
1878        return this.lastDiscoStarted;
1879    }
1880
1881    public long getLastPacketReceived() {
1882        return this.lastPacketReceived;
1883    }
1884
1885    public void sendActive() {
1886        this.sendPacket(new ActivePacket());
1887    }
1888
1889    public void sendInactive() {
1890        this.sendPacket(new InactivePacket());
1891    }
1892
1893    public void resetAttemptCount(boolean resetConnectTime) {
1894        this.attempt = 0;
1895        if (resetConnectTime) {
1896            this.lastConnect = 0;
1897        }
1898    }
1899
1900    public void setInteractive(boolean interactive) {
1901        this.mInteractive = interactive;
1902    }
1903
1904    public Identity getServerIdentity() {
1905        synchronized (this.disco) {
1906            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1907            if (result == null) {
1908                return Identity.UNKNOWN;
1909            }
1910            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1911                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1912                    switch (id.getName()) {
1913                        case "Prosody":
1914                            return Identity.PROSODY;
1915                        case "ejabberd":
1916                            return Identity.EJABBERD;
1917                        case "Slack-XMPP":
1918                            return Identity.SLACK;
1919                    }
1920                }
1921            }
1922        }
1923        return Identity.UNKNOWN;
1924    }
1925
1926    private IqGenerator getIqGenerator() {
1927        return mXmppConnectionService.getIqGenerator();
1928    }
1929
1930    public enum Identity {
1931        FACEBOOK,
1932        SLACK,
1933        EJABBERD,
1934        PROSODY,
1935        NIMBUZZ,
1936        UNKNOWN
1937    }
1938
1939    private class MyKeyManager implements X509KeyManager {
1940        @Override
1941        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1942            return account.getPrivateKeyAlias();
1943        }
1944
1945        @Override
1946        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1947            return null;
1948        }
1949
1950        @Override
1951        public X509Certificate[] getCertificateChain(String alias) {
1952            Log.d(Config.LOGTAG, "getting certificate chain");
1953            try {
1954                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1955            } catch (final Exception e) {
1956                Log.d(Config.LOGTAG, "could not get certificate chain", e);
1957                return new X509Certificate[0];
1958            }
1959        }
1960
1961        @Override
1962        public String[] getClientAliases(String s, Principal[] principals) {
1963            final String alias = account.getPrivateKeyAlias();
1964            return alias != null ? new String[]{alias} : new String[0];
1965        }
1966
1967        @Override
1968        public String[] getServerAliases(String s, Principal[] principals) {
1969            return new String[0];
1970        }
1971
1972        @Override
1973        public PrivateKey getPrivateKey(String alias) {
1974            try {
1975                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1976            } catch (Exception e) {
1977                return null;
1978            }
1979        }
1980    }
1981
1982    private static class StateChangingError extends Error {
1983        private final Account.State state;
1984
1985        public StateChangingError(Account.State state) {
1986            this.state = state;
1987        }
1988    }
1989
1990    private static class StateChangingException extends IOException {
1991        private final Account.State state;
1992
1993        public StateChangingException(Account.State state) {
1994            this.state = state;
1995        }
1996    }
1997
1998    public class Features {
1999        XmppConnection connection;
2000        private boolean carbonsEnabled = false;
2001        private boolean encryptionEnabled = false;
2002        private boolean blockListRequested = false;
2003
2004        public Features(final XmppConnection connection) {
2005            this.connection = connection;
2006        }
2007
2008        private boolean hasDiscoFeature(final Jid server, final String feature) {
2009            synchronized (XmppConnection.this.disco) {
2010                return connection.disco.containsKey(server) &&
2011                        connection.disco.get(server).getFeatures().contains(feature);
2012            }
2013        }
2014
2015        public boolean carbons() {
2016            return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
2017        }
2018
2019        public boolean commands() {
2020            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2021        }
2022
2023        public boolean easyOnboardingInvites() {
2024            synchronized (commands) {
2025                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2026            }
2027        }
2028
2029        public boolean bookmarksConversion() {
2030            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
2031        }
2032
2033        public boolean avatarConversion() {
2034            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
2035        }
2036
2037        public boolean blocking() {
2038            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2039        }
2040
2041        public boolean spamReporting() {
2042            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
2043        }
2044
2045        public boolean flexibleOfflineMessageRetrieval() {
2046            return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2047        }
2048
2049        public boolean register() {
2050            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2051        }
2052
2053        public boolean invite() {
2054            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2055        }
2056
2057        public boolean sm() {
2058            return streamId != null
2059                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
2060        }
2061
2062        public boolean csi() {
2063            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
2064        }
2065
2066        public boolean pep() {
2067            synchronized (XmppConnection.this.disco) {
2068                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2069                return info != null && info.hasIdentity("pubsub", "pep");
2070            }
2071        }
2072
2073        public boolean pepPersistent() {
2074            synchronized (XmppConnection.this.disco) {
2075                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2076                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
2077            }
2078        }
2079
2080        public boolean pepPublishOptions() {
2081            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2082        }
2083
2084        public boolean pepOmemoWhitelisted() {
2085            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2086        }
2087
2088        public boolean mam() {
2089            return MessageArchiveService.Version.has(getAccountFeatures());
2090        }
2091
2092        public List<String> getAccountFeatures() {
2093            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2094            return result == null ? Collections.emptyList() : result.getFeatures();
2095        }
2096
2097        public boolean push() {
2098            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2099                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2100        }
2101
2102        public boolean rosterVersioning() {
2103            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2104        }
2105
2106        public void setBlockListRequested(boolean value) {
2107            this.blockListRequested = value;
2108        }
2109
2110        public boolean httpUpload(long filesize) {
2111            if (Config.DISABLE_HTTP_UPLOAD) {
2112                return false;
2113            } else {
2114                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2115                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2116                    if (items.size() > 0) {
2117                        try {
2118                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2119                            if (filesize <= maxsize) {
2120                                return true;
2121                            } else {
2122                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
2123                                return false;
2124                            }
2125                        } catch (Exception e) {
2126                            return true;
2127                        }
2128                    }
2129                }
2130                return false;
2131            }
2132        }
2133
2134        public boolean useLegacyHttpUpload() {
2135            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2136        }
2137
2138        public long getMaxHttpUploadSize() {
2139            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2140                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2141                if (items.size() > 0) {
2142                    try {
2143                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2144                    } catch (Exception e) {
2145                        //ignored
2146                    }
2147                }
2148            }
2149            return -1;
2150        }
2151
2152        public boolean stanzaIds() {
2153            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2154        }
2155
2156        public boolean bookmarks2() {
2157            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2158        }
2159
2160        public boolean externalServiceDiscovery() {
2161            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2162        }
2163    }
2164}