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.SSLSocket;
  50import javax.net.ssl.SSLSocketFactory;
  51import javax.net.ssl.X509KeyManager;
  52import javax.net.ssl.X509TrustManager;
  53
  54import eu.siacs.conversations.Config;
  55import eu.siacs.conversations.R;
  56import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  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        if (!xmppDomainVerifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 830            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate domain verification failed");
 831            FileBackend.close(sslSocket);
 832            throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
 833        }
 834        return sslSocket;
 835    }
 836
 837    private void processStreamFeatures(final Tag currentTag) throws IOException {
 838        this.streamFeatures = tagReader.readElement(currentTag);
 839        final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 840        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 841        if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 842            sendStartTLS();
 843        } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 844            if (isSecure) {
 845                register();
 846            } else {
 847                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find STARTTLS for registration process " + XmlHelper.printElementNames(this.streamFeatures));
 848                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 849            }
 850        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 851            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 852        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 853            authenticate();
 854        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 855            if (Config.EXTENDED_SM_LOGGING) {
 856                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 857            }
 858            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 859            this.mSmCatchupMessageCounter.set(0);
 860            this.mWaitingForSmCatchup.set(true);
 861            this.tagWriter.writeStanzaAsync(resume);
 862        } else if (needsBinding) {
 863            if (this.streamFeatures.hasChild("bind") && isSecure) {
 864                sendBindRequest();
 865            } else {
 866                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find bind feature " + XmlHelper.printElementNames(this.streamFeatures));
 867                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 868            }
 869        }
 870    }
 871
 872    private void authenticate() throws IOException {
 873        final List<String> mechanisms = extractMechanisms(streamFeatures.findChild("mechanisms"));
 874        final Element auth = new Element("auth", Namespace.SASL);
 875        if (mechanisms.contains(External.MECHANISM) && account.getPrivateKeyAlias() != null) {
 876            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 877        } else if (mechanisms.contains(ScramSha512.MECHANISM)) {
 878            saslMechanism = new ScramSha512(tagWriter, account, mXmppConnectionService.getRNG());
 879        } else if (mechanisms.contains(ScramSha256.MECHANISM)) {
 880            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 881        } else if (mechanisms.contains(ScramSha1.MECHANISM)) {
 882            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 883        } else if (mechanisms.contains(Plain.MECHANISM) && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
 884            saslMechanism = new Plain(tagWriter, account);
 885        } else if (mechanisms.contains(DigestMd5.MECHANISM)) {
 886            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 887        } else if (mechanisms.contains(Anonymous.MECHANISM)) {
 888            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 889        }
 890        if (saslMechanism != null) {
 891            final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 892            if (pinnedMechanism > saslMechanism.getPriority()) {
 893                Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 894                        " has lower priority (" + saslMechanism.getPriority() +
 895                        ") than pinned priority (" + pinnedMechanism +
 896                        "). Possible downgrade attack?");
 897                throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 898            }
 899            Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 900            auth.setAttribute("mechanism", saslMechanism.getMechanism());
 901            if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 902                auth.setContent(saslMechanism.getClientFirstMessage());
 903            }
 904            tagWriter.writeElement(auth);
 905        } else {
 906            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find supported SASL mechanism in " + mechanisms);
 907            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 908        }
 909    }
 910
 911    private List<String> extractMechanisms(final Element stream) {
 912        final ArrayList<String> mechanisms = new ArrayList<>(stream
 913                .getChildren().size());
 914        for (final Element child : stream.getChildren()) {
 915            mechanisms.add(child.getContent());
 916        }
 917        return mechanisms;
 918    }
 919
 920
 921    private void register() {
 922        final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
 923        if (preAuth != null && features.invite()) {
 924            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
 925            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
 926            sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
 927                if (response.getType() == IqPacket.TYPE.RESULT) {
 928                    sendRegistryRequest();
 929                } else {
 930                    final String error = response.getErrorCondition();
 931                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to pre auth. " + error);
 932                    throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
 933                }
 934            }, true);
 935        } else {
 936            sendRegistryRequest();
 937        }
 938    }
 939
 940    private void sendRegistryRequest() {
 941        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 942        register.query(Namespace.REGISTER);
 943        register.setTo(account.getDomain());
 944        sendUnmodifiedIqPacket(register, (account, packet) -> {
 945            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 946                return;
 947            }
 948            if (packet.getType() == IqPacket.TYPE.ERROR) {
 949                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 950            }
 951            final Element query = packet.query(Namespace.REGISTER);
 952            if (query.hasChild("username") && (query.hasChild("password"))) {
 953                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 954                final Element username = new Element("username").setContent(account.getUsername());
 955                final Element password = new Element("password").setContent(account.getPassword());
 956                register1.query(Namespace.REGISTER).addChild(username);
 957                register1.query().addChild(password);
 958                register1.setFrom(account.getJid().asBareJid());
 959                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 960            } else if (query.hasChild("x", Namespace.DATA)) {
 961                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 962                final Element blob = query.findChild("data", "urn:xmpp:bob");
 963                final String id = packet.getId();
 964                InputStream is;
 965                if (blob != null) {
 966                    try {
 967                        final String base64Blob = blob.getContent();
 968                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 969                        is = new ByteArrayInputStream(strBlob);
 970                    } catch (Exception e) {
 971                        is = null;
 972                    }
 973                } else {
 974                    final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 975                    try {
 976                        final String url = data.getValue("url");
 977                        final String fallbackUrl = data.getValue("captcha-fallback-url");
 978                        if (url != null) {
 979                            is = HttpConnectionManager.open(url, useTor);
 980                        } else if (fallbackUrl != null) {
 981                            is = HttpConnectionManager.open(fallbackUrl, useTor);
 982                        } else {
 983                            is = null;
 984                        }
 985                    } catch (final IOException e) {
 986                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to fetch captcha", e);
 987                        is = null;
 988                    }
 989                }
 990
 991                if (is != null) {
 992                    Bitmap captcha = BitmapFactory.decodeStream(is);
 993                    try {
 994                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
 995                            return;
 996                        }
 997                    } catch (Exception e) {
 998                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 999                    }
1000                }
1001                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1002            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
1003                final String instructions = query.findChildContent("instructions");
1004                final Element oob = query.findChild("x", Namespace.OOB);
1005                final String url = oob == null ? null : oob.findChildContent("url");
1006                if (url != null) {
1007                    setAccountCreationFailed(url);
1008                } else if (instructions != null) {
1009                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1010                    if (matcher.find()) {
1011                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1012                    }
1013                }
1014                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1015            }
1016        }, true);
1017    }
1018
1019    private void setAccountCreationFailed(final String url) {
1020        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1021        if (httpUrl != null && httpUrl.isHttps()) {
1022            this.redirectionUrl = httpUrl;
1023            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1024        }
1025        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1026    }
1027
1028    public HttpUrl getRedirectionUrl() {
1029        return this.redirectionUrl;
1030    }
1031
1032    public void resetEverything() {
1033        resetAttemptCount(true);
1034        resetStreamId();
1035        clearIqCallbacks();
1036        this.stanzasSent = 0;
1037        mStanzaQueue.clear();
1038        this.redirectionUrl = null;
1039        synchronized (this.disco) {
1040            disco.clear();
1041        }
1042        synchronized (this.commands) {
1043            this.commands.clear();
1044        }
1045    }
1046
1047    private void sendBindRequest() {
1048        try {
1049            mXmppConnectionService.restoredFromDatabaseLatch.await();
1050        } catch (InterruptedException e) {
1051            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1052            return;
1053        }
1054        clearIqCallbacks();
1055        if (account.getJid().isBareJid()) {
1056            account.setResource(this.createNewResource());
1057        } else {
1058            fixResource(mXmppConnectionService, account);
1059        }
1060        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1061        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1062        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1063        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1064            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1065                return;
1066            }
1067            final Element bind = packet.findChild("bind");
1068            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1069                isBound = true;
1070                final Element jid = bind.findChild("jid");
1071                if (jid != null && jid.getContent() != null) {
1072                    try {
1073                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1074                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1075                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1076                            throw new StateChangingError(Account.State.BIND_FAILURE);
1077                        }
1078                        if (account.setJid(assignedJid)) {
1079                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1080                            mXmppConnectionService.databaseBackend.updateAccount(account);
1081                        }
1082                        if (streamFeatures.hasChild("session")
1083                                && !streamFeatures.findChild("session").hasChild("optional")) {
1084                            sendStartSession();
1085                        } else {
1086                            sendPostBindInitialization();
1087                        }
1088                        return;
1089                    } catch (final IllegalArgumentException e) {
1090                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1091                    }
1092                } else {
1093                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1094                }
1095            } else {
1096                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1097            }
1098            final Element error = packet.findChild("error");
1099            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1100                account.setResource(createNewResource());
1101            }
1102            throw new StateChangingError(Account.State.BIND_FAILURE);
1103        }, true);
1104    }
1105
1106    private void clearIqCallbacks() {
1107        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1108        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1109        synchronized (this.packetCallbacks) {
1110            if (this.packetCallbacks.size() == 0) {
1111                return;
1112            }
1113            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1114            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1115            while (iterator.hasNext()) {
1116                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1117                callbacks.add(entry.second);
1118                iterator.remove();
1119            }
1120        }
1121        for (OnIqPacketReceived callback : callbacks) {
1122            try {
1123                callback.onIqPacketReceived(account, failurePacket);
1124            } catch (StateChangingError error) {
1125                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1126                //ignore
1127            }
1128        }
1129        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1130    }
1131
1132    public void sendDiscoTimeout() {
1133        if (mWaitForDisco.compareAndSet(true, false)) {
1134            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1135            finalizeBind();
1136        }
1137    }
1138
1139    private void sendStartSession() {
1140        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1141        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1142        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1143        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1144            if (packet.getType() == IqPacket.TYPE.RESULT) {
1145                sendPostBindInitialization();
1146            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1147                throw new StateChangingError(Account.State.SESSION_FAILURE);
1148            }
1149        }, true);
1150    }
1151
1152    private void sendPostBindInitialization() {
1153        smVersion = 0;
1154        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1155            smVersion = 3;
1156        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1157            smVersion = 2;
1158        }
1159        if (smVersion != 0) {
1160            synchronized (this.mStanzaQueue) {
1161                final EnablePacket enable = new EnablePacket(smVersion);
1162                tagWriter.writeStanzaAsync(enable);
1163                stanzasSent = 0;
1164                mStanzaQueue.clear();
1165            }
1166        }
1167        features.carbonsEnabled = false;
1168        features.blockListRequested = false;
1169        synchronized (this.disco) {
1170            this.disco.clear();
1171        }
1172        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1173        mPendingServiceDiscoveries.set(0);
1174        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain().toEscapedString())) {
1175            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1176            mWaitForDisco.set(false);
1177        } else {
1178            mWaitForDisco.set(true);
1179        }
1180        lastDiscoStarted = SystemClock.elapsedRealtime();
1181        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1182        Element caps = streamFeatures.findChild("c");
1183        final String hash = caps == null ? null : caps.getAttribute("hash");
1184        final String ver = caps == null ? null : caps.getAttribute("ver");
1185        ServiceDiscoveryResult discoveryResult = null;
1186        if (hash != null && ver != null) {
1187            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1188        }
1189        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1190        if (requestDiscoItemsFirst) {
1191            sendServiceDiscoveryItems(account.getDomain());
1192        }
1193        if (discoveryResult == null) {
1194            sendServiceDiscoveryInfo(account.getDomain());
1195        } else {
1196            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1197            disco.put(account.getDomain(), discoveryResult);
1198        }
1199        discoverMamPreferences();
1200        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1201        if (!requestDiscoItemsFirst) {
1202            sendServiceDiscoveryItems(account.getDomain());
1203        }
1204
1205        if (!mWaitForDisco.get()) {
1206            finalizeBind();
1207        }
1208        this.lastSessionStarted = SystemClock.elapsedRealtime();
1209    }
1210
1211    private void sendServiceDiscoveryInfo(final Jid jid) {
1212        mPendingServiceDiscoveries.incrementAndGet();
1213        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1214        iq.setTo(jid);
1215        iq.query("http://jabber.org/protocol/disco#info");
1216        this.sendIqPacket(iq, (account, packet) -> {
1217            if (packet.getType() == IqPacket.TYPE.RESULT) {
1218                boolean advancedStreamFeaturesLoaded;
1219                synchronized (XmppConnection.this.disco) {
1220                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1221                    if (jid.equals(account.getDomain())) {
1222                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1223                    }
1224                    disco.put(jid, result);
1225                    advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain())
1226                            && disco.containsKey(account.getJid().asBareJid());
1227                }
1228                if (advancedStreamFeaturesLoaded && (jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid()))) {
1229                    enableAdvancedStreamFeatures();
1230                }
1231            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1232                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1233                final boolean serverOrAccount = jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid());
1234                final boolean advancedStreamFeaturesLoaded;
1235                if (serverOrAccount) {
1236                    synchronized (XmppConnection.this.disco) {
1237                        disco.put(jid, ServiceDiscoveryResult.empty());
1238                        advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain()) && disco.containsKey(account.getJid().asBareJid());
1239                    }
1240                } else {
1241                    advancedStreamFeaturesLoaded = false;
1242                }
1243                if (advancedStreamFeaturesLoaded) {
1244                    enableAdvancedStreamFeatures();
1245                }
1246            }
1247            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1248                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1249                        && mWaitForDisco.compareAndSet(true, false)) {
1250                    finalizeBind();
1251                }
1252            }
1253        });
1254    }
1255
1256    private void discoverMamPreferences() {
1257        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1258        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1259        sendIqPacket(request, (account, response) -> {
1260            if (response.getType() == IqPacket.TYPE.RESULT) {
1261                Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1262                isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1263            }
1264        });
1265    }
1266
1267    private void discoverCommands() {
1268        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1269        request.setTo(account.getDomain());
1270        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1271        sendIqPacket(request, (account, response) -> {
1272            if (response.getType() == IqPacket.TYPE.RESULT) {
1273                final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1274                if (query == null) {
1275                    return;
1276                }
1277                final HashMap<String, Jid> commands = new HashMap<>();
1278                for (final Element child : query.getChildren()) {
1279                    if ("item".equals(child.getName())) {
1280                        final String node = child.getAttribute("node");
1281                        final Jid jid = child.getAttributeAsJid("jid");
1282                        if (node != null && jid != null) {
1283                            commands.put(node, jid);
1284                        }
1285                    }
1286                }
1287                Log.d(Config.LOGTAG, commands.toString());
1288                synchronized (this.commands) {
1289                    this.commands.clear();
1290                    this.commands.putAll(commands);
1291                }
1292            }
1293        });
1294    }
1295
1296    public boolean isMamPreferenceAlways() {
1297        return isMamPreferenceAlways;
1298    }
1299
1300    private void finalizeBind() {
1301        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1302        if (bindListener != null) {
1303            bindListener.onBind(account);
1304        }
1305        changeStatus(Account.State.ONLINE);
1306    }
1307
1308    private void enableAdvancedStreamFeatures() {
1309        if (getFeatures().blocking() && !features.blockListRequested) {
1310            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1311            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1312        }
1313        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1314            listener.onAdvancedStreamFeaturesAvailable(account);
1315        }
1316        if (getFeatures().carbons() && !features.carbonsEnabled) {
1317            sendEnableCarbons();
1318        }
1319        if (getFeatures().commands()) {
1320            discoverCommands();
1321        }
1322    }
1323
1324    private void sendServiceDiscoveryItems(final Jid server) {
1325        mPendingServiceDiscoveries.incrementAndGet();
1326        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1327        iq.setTo(server.getDomain());
1328        iq.query("http://jabber.org/protocol/disco#items");
1329        this.sendIqPacket(iq, (account, packet) -> {
1330            if (packet.getType() == IqPacket.TYPE.RESULT) {
1331                final HashSet<Jid> items = new HashSet<>();
1332                final List<Element> elements = packet.query().getChildren();
1333                for (final Element element : elements) {
1334                    if (element.getName().equals("item")) {
1335                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1336                        if (jid != null && !jid.equals(account.getDomain())) {
1337                            items.add(jid);
1338                        }
1339                    }
1340                }
1341                for (Jid jid : items) {
1342                    sendServiceDiscoveryInfo(jid);
1343                }
1344            } else {
1345                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1346            }
1347            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1348                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1349                        && mWaitForDisco.compareAndSet(true, false)) {
1350                    finalizeBind();
1351                }
1352            }
1353        });
1354    }
1355
1356    private void sendEnableCarbons() {
1357        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1358        iq.addChild("enable", "urn:xmpp:carbons:2");
1359        this.sendIqPacket(iq, (account, packet) -> {
1360            if (!packet.hasChild("error")) {
1361                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1362                        + ": successfully enabled carbons");
1363                features.carbonsEnabled = true;
1364            } else {
1365                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1366                        + ": error enableing carbons " + packet.toString());
1367            }
1368        });
1369    }
1370
1371    private void processStreamError(final Tag currentTag) throws IOException {
1372        final Element streamError = tagReader.readElement(currentTag);
1373        if (streamError == null) {
1374            return;
1375        }
1376        if (streamError.hasChild("conflict")) {
1377            account.setResource(createNewResource());
1378            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1379            throw new IOException();
1380        } else if (streamError.hasChild("host-unknown")) {
1381            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1382        } else if (streamError.hasChild("policy-violation")) {
1383            this.lastConnect = SystemClock.elapsedRealtime();
1384            final String text = streamError.findChildContent("text");
1385            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1386            failPendingMessages(text);
1387            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1388        } else {
1389            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1390            throw new StateChangingException(Account.State.STREAM_ERROR);
1391        }
1392    }
1393
1394    private void failPendingMessages(final String error) {
1395        synchronized (this.mStanzaQueue) {
1396            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1397                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1398                if (stanza instanceof MessagePacket) {
1399                    final MessagePacket packet = (MessagePacket) stanza;
1400                    final String id = packet.getId();
1401                    final Jid to = packet.getTo();
1402                    mXmppConnectionService.markMessage(account,
1403                            to.asBareJid(),
1404                            id,
1405                            Message.STATUS_SEND_FAILED,
1406                            error);
1407                }
1408            }
1409        }
1410    }
1411
1412    private void sendStartStream() throws IOException {
1413        final Tag stream = Tag.start("stream:stream");
1414        stream.setAttribute("to", account.getServer());
1415        stream.setAttribute("version", "1.0");
1416        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1417        stream.setAttribute("xmlns", "jabber:client");
1418        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1419        tagWriter.writeTag(stream);
1420    }
1421
1422    private String createNewResource() {
1423        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1424    }
1425
1426    private String nextRandomId() {
1427        return nextRandomId(false);
1428    }
1429
1430    private String nextRandomId(boolean s) {
1431        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1432    }
1433
1434    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1435        packet.setFrom(account.getJid());
1436        return this.sendUnmodifiedIqPacket(packet, callback, false);
1437    }
1438
1439    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1440        if (packet.getId() == null) {
1441            packet.setAttribute("id", nextRandomId());
1442        }
1443        if (callback != null) {
1444            synchronized (this.packetCallbacks) {
1445                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1446            }
1447        }
1448        this.sendPacket(packet, force);
1449        return packet.getId();
1450    }
1451
1452    public void sendMessagePacket(final MessagePacket packet) {
1453        this.sendPacket(packet);
1454    }
1455
1456    public void sendPresencePacket(final PresencePacket packet) {
1457        this.sendPacket(packet);
1458    }
1459
1460    private synchronized void sendPacket(final AbstractStanza packet) {
1461        sendPacket(packet, false);
1462    }
1463
1464    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1465        if (stanzasSent == Integer.MAX_VALUE) {
1466            resetStreamId();
1467            disconnect(true);
1468            return;
1469        }
1470        synchronized (this.mStanzaQueue) {
1471            if (force || isBound) {
1472                tagWriter.writeStanzaAsync(packet);
1473            } else {
1474                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1475            }
1476            if (packet instanceof AbstractAcknowledgeableStanza) {
1477                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1478
1479                if (this.mStanzaQueue.size() != 0) {
1480                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1481                    if (currentHighestKey != stanzasSent) {
1482                        throw new AssertionError("Stanza count messed up");
1483                    }
1484                }
1485
1486                ++stanzasSent;
1487                this.mStanzaQueue.append(stanzasSent, stanza);
1488                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1489                    if (Config.EXTENDED_SM_LOGGING) {
1490                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1491                    }
1492                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1493                }
1494            }
1495        }
1496    }
1497
1498    public void sendPing() {
1499        if (!r()) {
1500            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1501            iq.setFrom(account.getJid());
1502            iq.addChild("ping", Namespace.PING);
1503            this.sendIqPacket(iq, null);
1504        }
1505        this.lastPingSent = SystemClock.elapsedRealtime();
1506    }
1507
1508    public void setOnMessagePacketReceivedListener(
1509            final OnMessagePacketReceived listener) {
1510        this.messageListener = listener;
1511    }
1512
1513    public void setOnUnregisteredIqPacketReceivedListener(
1514            final OnIqPacketReceived listener) {
1515        this.unregisteredIqListener = listener;
1516    }
1517
1518    public void setOnPresencePacketReceivedListener(
1519            final OnPresencePacketReceived listener) {
1520        this.presenceListener = listener;
1521    }
1522
1523    public void setOnJinglePacketReceivedListener(
1524            final OnJinglePacketReceived listener) {
1525        this.jingleListener = listener;
1526    }
1527
1528    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1529        this.statusListener = listener;
1530    }
1531
1532    public void setOnBindListener(final OnBindListener listener) {
1533        this.bindListener = listener;
1534    }
1535
1536    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1537        this.acknowledgedListener = listener;
1538    }
1539
1540    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1541        this.advancedStreamFeaturesLoadedListeners.add(listener);
1542    }
1543
1544    private void forceCloseSocket() {
1545        FileBackend.close(this.socket);
1546        FileBackend.close(this.tagReader);
1547    }
1548
1549    public void interrupt() {
1550        if (this.mThread != null) {
1551            this.mThread.interrupt();
1552        }
1553    }
1554
1555    public void disconnect(final boolean force) {
1556        interrupt();
1557        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1558        if (force) {
1559            forceCloseSocket();
1560        } else {
1561            final TagWriter currentTagWriter = this.tagWriter;
1562            if (currentTagWriter.isActive()) {
1563                currentTagWriter.finish();
1564                final Socket currentSocket = this.socket;
1565                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1566                try {
1567                    currentTagWriter.await(1, TimeUnit.SECONDS);
1568                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1569                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1570                    if (streamCountDownLatch != null) {
1571                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1572                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1573                        } else {
1574                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1575                        }
1576                    }
1577                } catch (InterruptedException e) {
1578                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1579                } catch (final IOException e) {
1580                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1581                } finally {
1582                    FileBackend.close(currentSocket);
1583                }
1584            } else {
1585                forceCloseSocket();
1586            }
1587        }
1588    }
1589
1590    private void resetStreamId() {
1591        this.streamId = null;
1592    }
1593
1594    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1595        synchronized (this.disco) {
1596            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1597            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1598                if (cursor.getValue().getFeatures().contains(feature)) {
1599                    items.add(cursor);
1600                }
1601            }
1602            return items;
1603        }
1604    }
1605
1606    public Jid findDiscoItemByFeature(final String feature) {
1607        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1608        if (items.size() >= 1) {
1609            return items.get(0).getKey();
1610        }
1611        return null;
1612    }
1613
1614    public boolean r() {
1615        if (getFeatures().sm()) {
1616            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1617            return true;
1618        } else {
1619            return false;
1620        }
1621    }
1622
1623    public List<String> getMucServersWithholdAccount() {
1624        final List<String> servers = getMucServers();
1625        servers.remove(account.getDomain().toEscapedString());
1626        return servers;
1627    }
1628
1629    public List<String> getMucServers() {
1630        List<String> servers = new ArrayList<>();
1631        synchronized (this.disco) {
1632            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1633                final ServiceDiscoveryResult value = cursor.getValue();
1634                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1635                        && value.hasIdentity("conference", "text")
1636                        && !value.getFeatures().contains("jabber:iq:gateway")
1637                        && !value.hasIdentity("conference", "irc")) {
1638                    servers.add(cursor.getKey().toString());
1639                }
1640            }
1641        }
1642        return servers;
1643    }
1644
1645    public String getMucServer() {
1646        List<String> servers = getMucServers();
1647        return servers.size() > 0 ? servers.get(0) : null;
1648    }
1649
1650    public int getTimeToNextAttempt() {
1651        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1652        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1653        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1654        return interval - secondsSinceLast;
1655    }
1656
1657    public int getAttempt() {
1658        return this.attempt;
1659    }
1660
1661    public Features getFeatures() {
1662        return this.features;
1663    }
1664
1665    public long getLastSessionEstablished() {
1666        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1667        return System.currentTimeMillis() - diff;
1668    }
1669
1670    public long getLastConnect() {
1671        return this.lastConnect;
1672    }
1673
1674    public long getLastPingSent() {
1675        return this.lastPingSent;
1676    }
1677
1678    public long getLastDiscoStarted() {
1679        return this.lastDiscoStarted;
1680    }
1681
1682    public long getLastPacketReceived() {
1683        return this.lastPacketReceived;
1684    }
1685
1686    public void sendActive() {
1687        this.sendPacket(new ActivePacket());
1688    }
1689
1690    public void sendInactive() {
1691        this.sendPacket(new InactivePacket());
1692    }
1693
1694    public void resetAttemptCount(boolean resetConnectTime) {
1695        this.attempt = 0;
1696        if (resetConnectTime) {
1697            this.lastConnect = 0;
1698        }
1699    }
1700
1701    public void setInteractive(boolean interactive) {
1702        this.mInteractive = interactive;
1703    }
1704
1705    public Identity getServerIdentity() {
1706        synchronized (this.disco) {
1707            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1708            if (result == null) {
1709                return Identity.UNKNOWN;
1710            }
1711            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1712                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1713                    switch (id.getName()) {
1714                        case "Prosody":
1715                            return Identity.PROSODY;
1716                        case "ejabberd":
1717                            return Identity.EJABBERD;
1718                        case "Slack-XMPP":
1719                            return Identity.SLACK;
1720                    }
1721                }
1722            }
1723        }
1724        return Identity.UNKNOWN;
1725    }
1726
1727    private IqGenerator getIqGenerator() {
1728        return mXmppConnectionService.getIqGenerator();
1729    }
1730
1731    public enum Identity {
1732        FACEBOOK,
1733        SLACK,
1734        EJABBERD,
1735        PROSODY,
1736        NIMBUZZ,
1737        UNKNOWN
1738    }
1739
1740    private class MyKeyManager implements X509KeyManager {
1741        @Override
1742        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1743            return account.getPrivateKeyAlias();
1744        }
1745
1746        @Override
1747        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1748            return null;
1749        }
1750
1751        @Override
1752        public X509Certificate[] getCertificateChain(String alias) {
1753            Log.d(Config.LOGTAG, "getting certificate chain");
1754            try {
1755                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1756            } catch (Exception e) {
1757                Log.d(Config.LOGTAG, e.getMessage());
1758                return new X509Certificate[0];
1759            }
1760        }
1761
1762        @Override
1763        public String[] getClientAliases(String s, Principal[] principals) {
1764            final String alias = account.getPrivateKeyAlias();
1765            return alias != null ? new String[]{alias} : new String[0];
1766        }
1767
1768        @Override
1769        public String[] getServerAliases(String s, Principal[] principals) {
1770            return new String[0];
1771        }
1772
1773        @Override
1774        public PrivateKey getPrivateKey(String alias) {
1775            try {
1776                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1777            } catch (Exception e) {
1778                return null;
1779            }
1780        }
1781    }
1782
1783    private static class StateChangingError extends Error {
1784        private final Account.State state;
1785
1786        public StateChangingError(Account.State state) {
1787            this.state = state;
1788        }
1789    }
1790
1791    private static class StateChangingException extends IOException {
1792        private final Account.State state;
1793
1794        public StateChangingException(Account.State state) {
1795            this.state = state;
1796        }
1797    }
1798
1799    public class Features {
1800        XmppConnection connection;
1801        private boolean carbonsEnabled = false;
1802        private boolean encryptionEnabled = false;
1803        private boolean blockListRequested = false;
1804
1805        public Features(final XmppConnection connection) {
1806            this.connection = connection;
1807        }
1808
1809        private boolean hasDiscoFeature(final Jid server, final String feature) {
1810            synchronized (XmppConnection.this.disco) {
1811                return connection.disco.containsKey(server) &&
1812                        connection.disco.get(server).getFeatures().contains(feature);
1813            }
1814        }
1815
1816        public boolean carbons() {
1817            return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
1818        }
1819
1820        public boolean commands() {
1821            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
1822        }
1823
1824        public boolean easyOnboardingInvites() {
1825            synchronized (commands) {
1826                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
1827            }
1828        }
1829
1830        public boolean bookmarksConversion() {
1831            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1832        }
1833
1834        public boolean avatarConversion() {
1835            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1836        }
1837
1838        public boolean blocking() {
1839            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
1840        }
1841
1842        public boolean spamReporting() {
1843            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
1844        }
1845
1846        public boolean flexibleOfflineMessageRetrieval() {
1847            return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1848        }
1849
1850        public boolean register() {
1851            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
1852        }
1853
1854        public boolean invite() {
1855            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1856        }
1857
1858        public boolean sm() {
1859            return streamId != null
1860                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1861        }
1862
1863        public boolean csi() {
1864            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1865        }
1866
1867        public boolean pep() {
1868            synchronized (XmppConnection.this.disco) {
1869                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1870                return info != null && info.hasIdentity("pubsub", "pep");
1871            }
1872        }
1873
1874        public boolean pepPersistent() {
1875            synchronized (XmppConnection.this.disco) {
1876                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1877                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1878            }
1879        }
1880
1881        public boolean pepPublishOptions() {
1882            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1883        }
1884
1885        public boolean pepOmemoWhitelisted() {
1886            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1887        }
1888
1889        public boolean mam() {
1890            return MessageArchiveService.Version.has(getAccountFeatures());
1891        }
1892
1893        public List<String> getAccountFeatures() {
1894            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1895            return result == null ? Collections.emptyList() : result.getFeatures();
1896        }
1897
1898        public boolean push() {
1899            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1900                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
1901        }
1902
1903        public boolean rosterVersioning() {
1904            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1905        }
1906
1907        public void setBlockListRequested(boolean value) {
1908            this.blockListRequested = value;
1909        }
1910
1911        public boolean httpUpload(long filesize) {
1912            if (Config.DISABLE_HTTP_UPLOAD) {
1913                return false;
1914            } else {
1915                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1916                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1917                    if (items.size() > 0) {
1918                        try {
1919                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1920                            if (filesize <= maxsize) {
1921                                return true;
1922                            } else {
1923                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1924                                return false;
1925                            }
1926                        } catch (Exception e) {
1927                            return true;
1928                        }
1929                    }
1930                }
1931                return false;
1932            }
1933        }
1934
1935        public boolean useLegacyHttpUpload() {
1936            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1937        }
1938
1939        public long getMaxHttpUploadSize() {
1940            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1941                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1942                if (items.size() > 0) {
1943                    try {
1944                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1945                    } catch (Exception e) {
1946                        //ignored
1947                    }
1948                }
1949            }
1950            return -1;
1951        }
1952
1953        public boolean stanzaIds() {
1954            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1955        }
1956
1957        public boolean bookmarks2() {
1958            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
1959        }
1960
1961        public boolean externalServiceDiscovery() {
1962            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
1963        }
1964    }
1965}