XmppConnection.java

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