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