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