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