XmppConnection.java

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