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