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