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