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