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