XmppConnection.java

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