XmppConnection.java

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