XmppConnection.java

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