XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.graphics.Bitmap;
   5import android.graphics.BitmapFactory;
   6import android.os.SystemClock;
   7import android.security.KeyChain;
   8import android.support.annotation.NonNull;
   9import android.util.Base64;
  10import android.util.Log;
  11import android.util.Pair;
  12import android.util.SparseArray;
  13
  14import org.xmlpull.v1.XmlPullParserException;
  15
  16import java.io.ByteArrayInputStream;
  17import java.io.IOException;
  18import java.io.InputStream;
  19import java.net.ConnectException;
  20import java.net.IDN;
  21import java.net.InetAddress;
  22import java.net.InetSocketAddress;
  23import java.net.MalformedURLException;
  24import java.net.Socket;
  25import java.net.URL;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.security.Principal;
  30import java.security.PrivateKey;
  31import java.security.cert.X509Certificate;
  32import java.util.ArrayList;
  33import java.util.Arrays;
  34import java.util.Collections;
  35import java.util.HashMap;
  36import java.util.HashSet;
  37import java.util.Hashtable;
  38import java.util.Iterator;
  39import java.util.List;
  40import java.util.Map.Entry;
  41import java.util.Set;
  42import java.util.concurrent.CountDownLatch;
  43import java.util.concurrent.TimeUnit;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47
  48import javax.net.ssl.KeyManager;
  49import javax.net.ssl.SSLContext;
  50import javax.net.ssl.SSLSocket;
  51import javax.net.ssl.SSLSocketFactory;
  52import javax.net.ssl.X509KeyManager;
  53import javax.net.ssl.X509TrustManager;
  54
  55import eu.siacs.conversations.Config;
  56import eu.siacs.conversations.R;
  57import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  58import eu.siacs.conversations.crypto.XmppDomainVerifier;
  59import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  60import eu.siacs.conversations.crypto.sasl.Anonymous;
  61import eu.siacs.conversations.crypto.sasl.DigestMd5;
  62import eu.siacs.conversations.crypto.sasl.External;
  63import eu.siacs.conversations.crypto.sasl.Plain;
  64import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  65import eu.siacs.conversations.crypto.sasl.ScramSha1;
  66import eu.siacs.conversations.crypto.sasl.ScramSha256;
  67import eu.siacs.conversations.entities.Account;
  68import eu.siacs.conversations.entities.Message;
  69import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  70import eu.siacs.conversations.generator.IqGenerator;
  71import eu.siacs.conversations.persistance.FileBackend;
  72import eu.siacs.conversations.services.MemorizingTrustManager;
  73import eu.siacs.conversations.services.MessageArchiveService;
  74import eu.siacs.conversations.services.NotificationService;
  75import eu.siacs.conversations.services.XmppConnectionService;
  76import eu.siacs.conversations.utils.CryptoHelper;
  77import eu.siacs.conversations.utils.Patterns;
  78import eu.siacs.conversations.utils.Resolver;
  79import eu.siacs.conversations.utils.SSLSocketHelper;
  80import eu.siacs.conversations.utils.SocksSocketFactory;
  81import eu.siacs.conversations.utils.XmlHelper;
  82import eu.siacs.conversations.xml.Element;
  83import eu.siacs.conversations.xml.LocalizedContent;
  84import eu.siacs.conversations.xml.Namespace;
  85import eu.siacs.conversations.xml.Tag;
  86import eu.siacs.conversations.xml.TagWriter;
  87import eu.siacs.conversations.xml.XmlReader;
  88import eu.siacs.conversations.xmpp.forms.Data;
  89import eu.siacs.conversations.xmpp.forms.Field;
  90import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  91import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  92import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  93import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  94import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  95import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  96import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  97import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  98import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  99import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
 100import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 101import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 102import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 103
 104public class XmppConnection implements Runnable {
 105
 106    private static final int PACKET_IQ = 0;
 107    private static final int PACKET_MESSAGE = 1;
 108    private static final int PACKET_PRESENCE = 2;
 109    public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
 110        @Override
 111        public void onIqPacketReceived(Account account, IqPacket packet) {
 112            if (packet.getType() == IqPacket.TYPE.RESULT) {
 113                account.setOption(Account.OPTION_REGISTER, false);
 114                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully registered new account on server");
 115                throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 116            } else {
 117                final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 118                        "The password is too weak",
 119                        "Please use a longer password.");
 120                Element error = packet.findChild("error");
 121                Account.State state = Account.State.REGISTRATION_FAILED;
 122                if (error != null) {
 123                    if (error.hasChild("conflict")) {
 124                        state = Account.State.REGISTRATION_CONFLICT;
 125                    } else if (error.hasChild("resource-constraint")
 126                            && "wait".equals(error.getAttribute("type"))) {
 127                        state = Account.State.REGISTRATION_PLEASE_WAIT;
 128                    } else if (error.hasChild("not-acceptable")
 129                            && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 130                        state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 131                    }
 132                }
 133                throw new StateChangingError(state);
 134            }
 135        }
 136    };
 137    protected final Account account;
 138    private final Features features = new Features(this);
 139    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 140    private final HashMap<String, Jid> commands = new HashMap<>();
 141    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 142    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 143    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
 144    private final XmppConnectionService mXmppConnectionService;
 145    private Socket socket;
 146    private XmlReader tagReader;
 147    private TagWriter tagWriter = new TagWriter();
 148    private boolean shouldAuthenticate = true;
 149    private boolean inSmacksSession = false;
 150    private boolean isBound = false;
 151    private Element streamFeatures;
 152    private String streamId = null;
 153    private int smVersion = 3;
 154    private int stanzasReceived = 0;
 155    private int stanzasSent = 0;
 156    private long lastPacketReceived = 0;
 157    private long lastPingSent = 0;
 158    private long lastConnect = 0;
 159    private long lastSessionStarted = 0;
 160    private long lastDiscoStarted = 0;
 161    private boolean isMamPreferenceAlways = false;
 162    private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
 163    private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
 164    private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
 165    private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
 166    private boolean mInteractive = false;
 167    private int attempt = 0;
 168    private OnPresencePacketReceived presenceListener = null;
 169    private OnJinglePacketReceived jingleListener = null;
 170    private OnIqPacketReceived unregisteredIqListener = null;
 171    private OnMessagePacketReceived messageListener = null;
 172    private OnStatusChanged statusListener = null;
 173    private OnBindListener bindListener = null;
 174    private OnMessageAcknowledged acknowledgedListener = null;
 175    private SaslMechanism saslMechanism;
 176    private URL redirectionUrl = null;
 177    private String verifiedHostname = null;
 178    private volatile Thread mThread;
 179    private CountDownLatch mStreamCountDownLatch;
 180
 181
 182    public XmppConnection(final Account account, final XmppConnectionService service) {
 183        this.account = account;
 184        this.mXmppConnectionService = service;
 185    }
 186
 187    private static void fixResource(Context context, Account account) {
 188        String resource = account.getResource();
 189        int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
 190        int randomPartLength = 4; // 3 bytes
 191        if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
 192            if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
 193                account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
 194            }
 195        }
 196    }
 197
 198    private static boolean validBase64(String input) {
 199        try {
 200            return Base64.decode(input, Base64.URL_SAFE).length == 3;
 201        } catch (Throwable throwable) {
 202            return false;
 203        }
 204    }
 205
 206    private void changeStatus(final Account.State nextStatus) {
 207        synchronized (this) {
 208            if (Thread.currentThread().isInterrupted()) {
 209                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
 210                return;
 211            }
 212            if (account.getStatus() != nextStatus) {
 213                if ((nextStatus == Account.State.OFFLINE)
 214                        && (account.getStatus() != Account.State.CONNECTING)
 215                        && (account.getStatus() != Account.State.ONLINE)
 216                        && (account.getStatus() != Account.State.DISABLED)) {
 217                    return;
 218                }
 219                if (nextStatus == Account.State.ONLINE) {
 220                    this.attempt = 0;
 221                }
 222                account.setStatus(nextStatus);
 223            } else {
 224                return;
 225            }
 226        }
 227        if (statusListener != null) {
 228            statusListener.onStatusChanged(account);
 229        }
 230    }
 231
 232    public Jid getJidForCommand(final String node) {
 233        synchronized (this.commands) {
 234            return this.commands.get(node);
 235        }
 236    }
 237
 238    public void prepareNewConnection() {
 239        this.lastConnect = SystemClock.elapsedRealtime();
 240        this.lastPingSent = SystemClock.elapsedRealtime();
 241        this.lastDiscoStarted = Long.MAX_VALUE;
 242        this.mWaitingForSmCatchup.set(false);
 243        this.changeStatus(Account.State.CONNECTING);
 244    }
 245
 246    public boolean isWaitingForSmCatchup() {
 247        return mWaitingForSmCatchup.get();
 248    }
 249
 250    public void incrementSmCatchupMessageCounter() {
 251        this.mSmCatchupMessageCounter.incrementAndGet();
 252    }
 253
 254    protected void connect() {
 255        if (mXmppConnectionService.areMessagesInitialized()) {
 256            mXmppConnectionService.resetSendingToWaiting(account);
 257        }
 258        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
 259        features.encryptionEnabled = false;
 260        inSmacksSession = false;
 261        isBound = false;
 262        this.attempt++;
 263        this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
 264        try {
 265            Socket localSocket;
 266            shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
 267            this.changeStatus(Account.State.CONNECTING);
 268            final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
 269            final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
 270            if (useTor) {
 271                String destination;
 272                if (account.getHostname().isEmpty() || account.isOnion()) {
 273                    destination = account.getServer();
 274                } else {
 275                    destination = account.getHostname();
 276                    this.verifiedHostname = destination;
 277                }
 278
 279                final int port = account.getPort();
 280                final boolean directTls = Resolver.useDirectTls(port);
 281
 282                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor. directTls=" + directTls);
 283                localSocket = SocksSocketFactory.createSocketOverTor(destination, port);
 284
 285                if (directTls) {
 286                    localSocket = upgradeSocketToTls(localSocket);
 287                    features.encryptionEnabled = true;
 288                }
 289
 290                try {
 291                    startXmpp(localSocket);
 292                } catch (InterruptedException e) {
 293                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 294                    return;
 295                } catch (Exception e) {
 296                    throw new IOException(e.getMessage());
 297                }
 298            } else {
 299                final String domain = account.getServer();
 300                final List<Resolver.Result> results;
 301                final boolean hardcoded = extended && !account.getHostname().isEmpty();
 302                if (hardcoded) {
 303                    results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
 304                } else {
 305                    results = Resolver.resolve(domain);
 306                }
 307                if (Thread.currentThread().isInterrupted()) {
 308                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 309                    return;
 310                }
 311                if (results.size() == 0) {
 312                    Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": Resolver results were empty");
 313                    return;
 314                }
 315                final Resolver.Result storedBackupResult;
 316                if (hardcoded) {
 317                    storedBackupResult = null;
 318                } else {
 319                    storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
 320                    if (storedBackupResult != null && !results.contains(storedBackupResult)) {
 321                        results.add(storedBackupResult);
 322                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
 323                    }
 324                }
 325                for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
 326                    final Resolver.Result result = iterator.next();
 327                    if (Thread.currentThread().isInterrupted()) {
 328                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
 329                        return;
 330                    }
 331                    try {
 332                        // if tls is true, encryption is implied and must not be started
 333                        features.encryptionEnabled = result.isDirectTls();
 334                        verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
 335                        Log.d(Config.LOGTAG, "verified hostname " + verifiedHostname);
 336                        final InetSocketAddress addr;
 337                        if (result.getIp() != null) {
 338                            addr = new InetSocketAddress(result.getIp(), result.getPort());
 339                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 340                                    + ": using values from resolver " + (result.getHostname() == null ? "" : result.getHostname().toString()
 341                                    + "/") + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 342                        } else {
 343                            addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
 344                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 345                                    + ": using values from resolver "
 346                                    + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
 347                        }
 348
 349                        localSocket = new Socket();
 350                        localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
 351
 352                        if (features.encryptionEnabled) {
 353                            localSocket = upgradeSocketToTls(localSocket);
 354                        }
 355
 356                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 357                        if (startXmpp(localSocket)) {
 358                            localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
 359                            if (!hardcoded && !result.equals(storedBackupResult)) {
 360                                mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
 361                            }
 362                            break; // successfully connected to server that speaks xmpp
 363                        } else {
 364                            FileBackend.close(localSocket);
 365                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 366                        }
 367                    } catch (final StateChangingException e) {
 368                        if (!iterator.hasNext()) {
 369                            throw e;
 370                        }
 371                    } catch (InterruptedException e) {
 372                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 373                        return;
 374                    } catch (final Throwable e) {
 375                        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
 376                        if (!iterator.hasNext()) {
 377                            throw new UnknownHostException();
 378                        }
 379                    }
 380                }
 381            }
 382            processStream();
 383        } catch (final SecurityException e) {
 384            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 385        } catch (final StateChangingException e) {
 386            this.changeStatus(e.state);
 387        } catch (final UnknownHostException | ConnectException e) {
 388            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 389        } catch (final SocksSocketFactory.HostNotFoundException e) {
 390            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 391        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 392            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 393        } catch (final IOException | XmlPullParserException e) {
 394            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 395            this.changeStatus(Account.State.OFFLINE);
 396            this.attempt = Math.max(0, this.attempt - 1);
 397        } finally {
 398            if (!Thread.currentThread().isInterrupted()) {
 399                forceCloseSocket();
 400            } else {
 401                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
 402            }
 403        }
 404    }
 405
 406    /**
 407     * Starts xmpp protocol, call after connecting to socket
 408     *
 409     * @return true if server returns with valid xmpp, false otherwise
 410     */
 411    private boolean startXmpp(Socket socket) throws Exception {
 412        if (Thread.currentThread().isInterrupted()) {
 413            throw new InterruptedException();
 414        }
 415        this.socket = socket;
 416        tagReader = new XmlReader();
 417        if (tagWriter != null) {
 418            tagWriter.forceClose();
 419        }
 420        tagWriter = new TagWriter();
 421        tagWriter.setOutputStream(socket.getOutputStream());
 422        tagReader.setInputStream(socket.getInputStream());
 423        tagWriter.beginDocument();
 424        sendStartStream();
 425        final Tag tag = tagReader.readTag();
 426        if (Thread.currentThread().isInterrupted()) {
 427            throw new InterruptedException();
 428        }
 429        if (socket instanceof SSLSocket) {
 430            SSLSocketHelper.log(account, (SSLSocket) socket);
 431        }
 432        return tag != null && tag.isStart("stream");
 433    }
 434
 435    private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
 436        final SSLContext sc = SSLSocketHelper.getSSLContext();
 437        final MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 438        final KeyManager[] keyManager;
 439        if (account.getPrivateKeyAlias() != null) {
 440            keyManager = new KeyManager[]{new MyKeyManager()};
 441        } else {
 442            keyManager = null;
 443        }
 444        final String domain = account.getServer();
 445        sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 446        final SSLSocketFactory factory = sc.getSocketFactory();
 447        final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
 448        return new TlsFactoryVerifier(factory, verifier);
 449    }
 450
 451    @Override
 452    public void run() {
 453        synchronized (this) {
 454            this.mThread = Thread.currentThread();
 455            if (this.mThread.isInterrupted()) {
 456                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
 457                return;
 458            }
 459            forceCloseSocket();
 460        }
 461        connect();
 462    }
 463
 464    private void processStream() throws XmlPullParserException, IOException {
 465        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 466        this.mStreamCountDownLatch = streamCountDownLatch;
 467        Tag nextTag = tagReader.readTag();
 468        while (nextTag != null && !nextTag.isEnd("stream")) {
 469            if (nextTag.isStart("error")) {
 470                processStreamError(nextTag);
 471            } else if (nextTag.isStart("features")) {
 472                processStreamFeatures(nextTag);
 473            } else if (nextTag.isStart("proceed")) {
 474                switchOverToTls();
 475            } else if (nextTag.isStart("success")) {
 476                final String challenge = tagReader.readElement(nextTag).getContent();
 477                try {
 478                    saslMechanism.getResponse(challenge);
 479                } catch (final SaslMechanism.AuthenticationException e) {
 480                    Log.e(Config.LOGTAG, String.valueOf(e));
 481                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 482                }
 483                Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
 484                account.setKey(Account.PINNED_MECHANISM_KEY,
 485                        String.valueOf(saslMechanism.getPriority()));
 486                tagReader.reset();
 487                sendStartStream();
 488                final Tag tag = tagReader.readTag();
 489                if (tag != null && tag.isStart("stream")) {
 490                    processStream();
 491                } else {
 492                    throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 493                }
 494                break;
 495            } else if (nextTag.isStart("failure")) {
 496                final Element failure = tagReader.readElement(nextTag);
 497                if (Namespace.SASL.equals(failure.getNamespace())) {
 498                    final String text = failure.findChildContent("text");
 499                    if (failure.hasChild("account-disabled") && text != null) {
 500                        Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 501                        if (matcher.find()) {
 502                            try {
 503                                URL url = new URL(text.substring(matcher.start(), matcher.end()));
 504                                if (url.getProtocol().equals("https")) {
 505                                    this.redirectionUrl = url;
 506                                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 507                                }
 508                            } catch (MalformedURLException e) {
 509                                throw new StateChangingException(Account.State.UNAUTHORIZED);
 510                            }
 511                        }
 512                    }
 513                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 514                } else if (Namespace.TLS.equals(failure.getNamespace())) {
 515                    throw new StateChangingException(Account.State.TLS_ERROR);
 516                } else {
 517                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 518                }
 519            } else if (nextTag.isStart("challenge")) {
 520                final String challenge = tagReader.readElement(nextTag).getContent();
 521                final Element response = new Element("response", Namespace.SASL);
 522                try {
 523                    response.setContent(saslMechanism.getResponse(challenge));
 524                } catch (final SaslMechanism.AuthenticationException e) {
 525                    // TODO: Send auth abort tag.
 526                    Log.e(Config.LOGTAG, e.toString());
 527                }
 528                tagWriter.writeElement(response);
 529            } else if (nextTag.isStart("enabled")) {
 530                final Element enabled = tagReader.readElement(nextTag);
 531                if ("true".equals(enabled.getAttribute("resume"))) {
 532                    this.streamId = enabled.getAttribute("id");
 533                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 534                            + ": stream management(" + smVersion
 535                            + ") enabled (resumable)");
 536                } else {
 537                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 538                            + ": stream management(" + smVersion + ") enabled");
 539                }
 540                this.stanzasReceived = 0;
 541                this.inSmacksSession = true;
 542                final RequestPacket r = new RequestPacket(smVersion);
 543                tagWriter.writeStanzaAsync(r);
 544            } else if (nextTag.isStart("resumed")) {
 545                this.inSmacksSession = true;
 546                this.isBound = true;
 547                this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 548                lastPacketReceived = SystemClock.elapsedRealtime();
 549                final Element resumed = tagReader.readElement(nextTag);
 550                final String h = resumed.getAttribute("h");
 551                try {
 552                    ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 553                    final boolean acknowledgedMessages;
 554                    synchronized (this.mStanzaQueue) {
 555                        final int serverCount = Integer.parseInt(h);
 556                        if (serverCount < stanzasSent) {
 557                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 558                                    + ": session resumed with lost packages");
 559                            stanzasSent = serverCount;
 560                        } else {
 561                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
 562                        }
 563                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 564                        for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 565                            failedStanzas.add(mStanzaQueue.valueAt(i));
 566                        }
 567                        mStanzaQueue.clear();
 568                    }
 569                    if (acknowledgedMessages) {
 570                        mXmppConnectionService.updateConversationUi();
 571                    }
 572                    Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 573                    for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 574                        if (packet instanceof MessagePacket) {
 575                            MessagePacket message = (MessagePacket) packet;
 576                            mXmppConnectionService.markMessage(account,
 577                                    message.getTo().asBareJid(),
 578                                    message.getId(),
 579                                    Message.STATUS_UNSEND);
 580                        }
 581                        sendPacket(packet);
 582                    }
 583                } catch (final NumberFormatException ignored) {
 584                }
 585                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
 586                changeStatus(Account.State.ONLINE);
 587            } else if (nextTag.isStart("r")) {
 588                tagReader.readElement(nextTag);
 589                if (Config.EXTENDED_SM_LOGGING) {
 590                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 591                }
 592                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 593                tagWriter.writeStanzaAsync(ack);
 594            } else if (nextTag.isStart("a")) {
 595                boolean accountUiNeedsRefresh = false;
 596                synchronized (NotificationService.CATCHUP_LOCK) {
 597                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 598                        final int messageCount = mSmCatchupMessageCounter.get();
 599                        final int pendingIQs = packetCallbacks.size();
 600                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (messages=" + messageCount + ", pending IQs=" + pendingIQs + ")");
 601                        accountUiNeedsRefresh = true;
 602                        if (messageCount > 0) {
 603                            mXmppConnectionService.getNotificationService().finishBacklog(true, account);
 604                        }
 605                    }
 606                }
 607                if (accountUiNeedsRefresh) {
 608                    mXmppConnectionService.updateAccountUi();
 609                }
 610                final Element ack = tagReader.readElement(nextTag);
 611                lastPacketReceived = SystemClock.elapsedRealtime();
 612                try {
 613                    final boolean acknowledgedMessages;
 614                    synchronized (this.mStanzaQueue) {
 615                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 616                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 617                    }
 618                    if (acknowledgedMessages) {
 619                        mXmppConnectionService.updateConversationUi();
 620                    }
 621                } catch (NumberFormatException | NullPointerException e) {
 622                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
 623                }
 624            } else if (nextTag.isStart("failed")) {
 625                Element failed = tagReader.readElement(nextTag);
 626                try {
 627                    final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 628                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
 629                    final boolean acknowledgedMessages;
 630                    synchronized (this.mStanzaQueue) {
 631                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 632                    }
 633                    if (acknowledgedMessages) {
 634                        mXmppConnectionService.updateConversationUi();
 635                    }
 636                } catch (NumberFormatException | NullPointerException e) {
 637                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 638                }
 639                resetStreamId();
 640                sendBindRequest();
 641            } else if (nextTag.isStart("iq")) {
 642                processIq(nextTag);
 643            } else if (nextTag.isStart("message")) {
 644                processMessage(nextTag);
 645            } else if (nextTag.isStart("presence")) {
 646                processPresence(nextTag);
 647            }
 648            nextTag = tagReader.readTag();
 649        }
 650        if (nextTag != null && nextTag.isEnd("stream")) {
 651            streamCountDownLatch.countDown();
 652        }
 653    }
 654
 655    private boolean acknowledgeStanzaUpTo(int serverCount) {
 656        if (serverCount > stanzasSent) {
 657            Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 658        }
 659        boolean acknowledgedMessages = false;
 660        for (int i = 0; i < mStanzaQueue.size(); ++i) {
 661            if (serverCount >= mStanzaQueue.keyAt(i)) {
 662                if (Config.EXTENDED_SM_LOGGING) {
 663                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 664                }
 665                AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 666                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 667                    MessagePacket packet = (MessagePacket) stanza;
 668                    acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, packet.getId());
 669                }
 670                mStanzaQueue.removeAt(i);
 671                i--;
 672            }
 673        }
 674        return acknowledgedMessages;
 675    }
 676
 677    private @NonNull
 678    Element processPacket(final Tag currentTag, final int packetType) throws IOException {
 679        final Element element;
 680        switch (packetType) {
 681            case PACKET_IQ:
 682                element = new IqPacket();
 683                break;
 684            case PACKET_MESSAGE:
 685                element = new MessagePacket();
 686                break;
 687            case PACKET_PRESENCE:
 688                element = new PresencePacket();
 689                break;
 690            default:
 691                throw new AssertionError("Should never encounter invalid type");
 692        }
 693        element.setAttributes(currentTag.getAttributes());
 694        Tag nextTag = tagReader.readTag();
 695        if (nextTag == null) {
 696            throw new IOException("interrupted mid tag");
 697        }
 698        while (!nextTag.isEnd(element.getName())) {
 699            if (!nextTag.isNo()) {
 700                element.addChild(tagReader.readElement(nextTag));
 701            }
 702            nextTag = tagReader.readTag();
 703            if (nextTag == null) {
 704                throw new IOException("interrupted mid tag");
 705            }
 706        }
 707        if (stanzasReceived == Integer.MAX_VALUE) {
 708            resetStreamId();
 709            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 710        }
 711        if (inSmacksSession) {
 712            ++stanzasReceived;
 713        } else if (features.sm()) {
 714            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 715        }
 716        lastPacketReceived = SystemClock.elapsedRealtime();
 717        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 718            Log.d(Config.LOGTAG, "[background stanza] " + element);
 719        }
 720        if (element instanceof IqPacket
 721                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
 722                && element.hasChild("jingle", Namespace.JINGLE)) {
 723            return JinglePacket.upgrade((IqPacket) element);
 724        } else {
 725            return element;
 726        }
 727    }
 728
 729    private void processIq(final Tag currentTag) throws IOException {
 730        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 731        if (!packet.valid()) {
 732            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 733            return;
 734        }
 735        if (packet instanceof JinglePacket) {
 736            if (this.jingleListener != null) {
 737                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 738            }
 739        } else {
 740            OnIqPacketReceived callback = null;
 741            synchronized (this.packetCallbacks) {
 742                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 743                if (packetCallbackDuple != null) {
 744                    // Packets to the server should have responses from the server
 745                    if (packetCallbackDuple.first.toServer(account)) {
 746                        if (packet.fromServer(account)) {
 747                            callback = packetCallbackDuple.second;
 748                            packetCallbacks.remove(packet.getId());
 749                        } else {
 750                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 751                        }
 752                    } else {
 753                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 754                            callback = packetCallbackDuple.second;
 755                            packetCallbacks.remove(packet.getId());
 756                        } else {
 757                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 758                        }
 759                    }
 760                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 761                    callback = this.unregisteredIqListener;
 762                }
 763            }
 764            if (callback != null) {
 765                try {
 766                    callback.onIqPacketReceived(account, packet);
 767                } catch (StateChangingError error) {
 768                    throw new StateChangingException(error.state);
 769                }
 770            }
 771        }
 772    }
 773
 774    private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 775        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 776        if (!packet.valid()) {
 777            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 778            return;
 779        }
 780        this.messageListener.onMessagePacketReceived(account, packet);
 781    }
 782
 783    private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 784        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 785        if (!packet.valid()) {
 786            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 787            return;
 788        }
 789        this.presenceListener.onPresencePacketReceived(account, packet);
 790    }
 791
 792    private void sendStartTLS() throws IOException {
 793        final Tag startTLS = Tag.empty("starttls");
 794        startTLS.setAttribute("xmlns", Namespace.TLS);
 795        tagWriter.writeTag(startTLS);
 796    }
 797
 798    private void switchOverToTls() throws XmlPullParserException, IOException {
 799        tagReader.readTag();
 800        final Socket socket = this.socket;
 801        final SSLSocket sslSocket = upgradeSocketToTls(socket);
 802        tagReader.setInputStream(sslSocket.getInputStream());
 803        tagWriter.setOutputStream(sslSocket.getOutputStream());
 804        sendStartStream();
 805        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 806        features.encryptionEnabled = true;
 807        final Tag tag = tagReader.readTag();
 808        if (tag != null && tag.isStart("stream")) {
 809            SSLSocketHelper.log(account, sslSocket);
 810            processStream();
 811        } else {
 812            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 813        }
 814        sslSocket.close();
 815    }
 816
 817    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
 818        final TlsFactoryVerifier tlsFactoryVerifier;
 819        try {
 820            tlsFactoryVerifier = getTlsFactoryVerifier();
 821        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
 822            throw new StateChangingException(Account.State.TLS_ERROR);
 823        }
 824        final InetAddress address = socket.getInetAddress();
 825        final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 826        SSLSocketHelper.setSecurity(sslSocket);
 827        SSLSocketHelper.setHostname(sslSocket, account.getServer());
 828        SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 829        if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 830            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 831            FileBackend.close(sslSocket);
 832            throw new StateChangingException(Account.State.TLS_ERROR);
 833        }
 834        return sslSocket;
 835    }
 836
 837    private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
 838        this.streamFeatures = tagReader.readElement(currentTag);
 839        final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 840        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 841        if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 842            sendStartTLS();
 843        } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 844            if (isSecure) {
 845                register();
 846            } else {
 847                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find STARTTLS for registration process " + XmlHelper.printElementNames(this.streamFeatures));
 848                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 849            }
 850        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 851            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 852        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 853            authenticate();
 854        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 855            if (Config.EXTENDED_SM_LOGGING) {
 856                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 857            }
 858            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 859            this.mSmCatchupMessageCounter.set(0);
 860            this.mWaitingForSmCatchup.set(true);
 861            this.tagWriter.writeStanzaAsync(resume);
 862        } else if (needsBinding) {
 863            if (this.streamFeatures.hasChild("bind") && isSecure) {
 864                sendBindRequest();
 865            } else {
 866                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find bind feature " + XmlHelper.printElementNames(this.streamFeatures));
 867                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 868            }
 869        }
 870    }
 871
 872    private void authenticate() throws IOException {
 873        final List<String> mechanisms = extractMechanisms(streamFeatures
 874                .findChild("mechanisms"));
 875        final Element auth = new Element("auth", Namespace.SASL);
 876        if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 877            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 878        } else if (mechanisms.contains("SCRAM-SHA-256")) {
 879            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 880        } else if (mechanisms.contains("SCRAM-SHA-1")) {
 881            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 882        } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
 883            saslMechanism = new Plain(tagWriter, account);
 884        } else if (mechanisms.contains("DIGEST-MD5")) {
 885            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 886        } else if (mechanisms.contains("ANONYMOUS")) {
 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                HashSet<Jid> items = new HashSet<Jid>();
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, new OnIqPacketReceived() {
1356
1357            @Override
1358            public void onIqPacketReceived(final Account account, final IqPacket packet) {
1359                if (!packet.hasChild("error")) {
1360                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1361                            + ": successfully enabled carbons");
1362                    features.carbonsEnabled = true;
1363                } else {
1364                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1365                            + ": error enableing carbons " + packet.toString());
1366                }
1367            }
1368        });
1369    }
1370
1371    private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1372        final Element streamError = tagReader.readElement(currentTag);
1373        if (streamError == null) {
1374            return;
1375        }
1376        if (streamError.hasChild("conflict")) {
1377            account.setResource(createNewResource());
1378            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1379            throw new IOException();
1380        } else if (streamError.hasChild("host-unknown")) {
1381            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1382        } else if (streamError.hasChild("policy-violation")) {
1383            this.lastConnect = SystemClock.elapsedRealtime();
1384            final String text = streamError.findChildContent("text");
1385            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1386            failPendingMessages(text);
1387            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1388        } else {
1389            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1390            throw new StateChangingException(Account.State.STREAM_ERROR);
1391        }
1392    }
1393
1394    private void failPendingMessages(final String error) {
1395        synchronized (this.mStanzaQueue) {
1396            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1397                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1398                if (stanza instanceof MessagePacket) {
1399                    final MessagePacket packet = (MessagePacket) stanza;
1400                    final String id = packet.getId();
1401                    final Jid to = packet.getTo();
1402                    mXmppConnectionService.markMessage(account,
1403                            to.asBareJid(),
1404                            id,
1405                            Message.STATUS_SEND_FAILED,
1406                            error);
1407                }
1408            }
1409        }
1410    }
1411
1412    private void sendStartStream() throws IOException {
1413        final Tag stream = Tag.start("stream:stream");
1414        stream.setAttribute("to", account.getServer());
1415        stream.setAttribute("version", "1.0");
1416        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1417        stream.setAttribute("xmlns", "jabber:client");
1418        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1419        tagWriter.writeTag(stream);
1420    }
1421
1422    private String createNewResource() {
1423        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1424    }
1425
1426    private String nextRandomId() {
1427        return nextRandomId(false);
1428    }
1429
1430    private String nextRandomId(boolean s) {
1431        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1432    }
1433
1434    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1435        packet.setFrom(account.getJid());
1436        return this.sendUnmodifiedIqPacket(packet, callback, false);
1437    }
1438
1439    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1440        if (packet.getId() == null) {
1441            packet.setAttribute("id", nextRandomId());
1442        }
1443        if (callback != null) {
1444            synchronized (this.packetCallbacks) {
1445                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1446            }
1447        }
1448        this.sendPacket(packet, force);
1449        return packet.getId();
1450    }
1451
1452    public void sendMessagePacket(final MessagePacket packet) {
1453        this.sendPacket(packet);
1454    }
1455
1456    public void sendPresencePacket(final PresencePacket packet) {
1457        this.sendPacket(packet);
1458    }
1459
1460    private synchronized void sendPacket(final AbstractStanza packet) {
1461        sendPacket(packet, false);
1462    }
1463
1464    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1465        if (stanzasSent == Integer.MAX_VALUE) {
1466            resetStreamId();
1467            disconnect(true);
1468            return;
1469        }
1470        synchronized (this.mStanzaQueue) {
1471            if (force || isBound) {
1472                tagWriter.writeStanzaAsync(packet);
1473            } else {
1474                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1475            }
1476            if (packet instanceof AbstractAcknowledgeableStanza) {
1477                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1478
1479                if (this.mStanzaQueue.size() != 0) {
1480                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1481                    if (currentHighestKey != stanzasSent) {
1482                        throw new AssertionError("Stanza count messed up");
1483                    }
1484                }
1485
1486                ++stanzasSent;
1487                this.mStanzaQueue.append(stanzasSent, stanza);
1488                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1489                    if (Config.EXTENDED_SM_LOGGING) {
1490                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1491                    }
1492                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1493                }
1494            }
1495        }
1496    }
1497
1498    public void sendPing() {
1499        if (!r()) {
1500            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1501            iq.setFrom(account.getJid());
1502            iq.addChild("ping", Namespace.PING);
1503            this.sendIqPacket(iq, null);
1504        }
1505        this.lastPingSent = SystemClock.elapsedRealtime();
1506    }
1507
1508    public void setOnMessagePacketReceivedListener(
1509            final OnMessagePacketReceived listener) {
1510        this.messageListener = listener;
1511    }
1512
1513    public void setOnUnregisteredIqPacketReceivedListener(
1514            final OnIqPacketReceived listener) {
1515        this.unregisteredIqListener = listener;
1516    }
1517
1518    public void setOnPresencePacketReceivedListener(
1519            final OnPresencePacketReceived listener) {
1520        this.presenceListener = listener;
1521    }
1522
1523    public void setOnJinglePacketReceivedListener(
1524            final OnJinglePacketReceived listener) {
1525        this.jingleListener = listener;
1526    }
1527
1528    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1529        this.statusListener = listener;
1530    }
1531
1532    public void setOnBindListener(final OnBindListener listener) {
1533        this.bindListener = listener;
1534    }
1535
1536    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1537        this.acknowledgedListener = listener;
1538    }
1539
1540    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1541        this.advancedStreamFeaturesLoadedListeners.add(listener);
1542    }
1543
1544    private void forceCloseSocket() {
1545        FileBackend.close(this.socket);
1546        FileBackend.close(this.tagReader);
1547    }
1548
1549    public void interrupt() {
1550        if (this.mThread != null) {
1551            this.mThread.interrupt();
1552        }
1553    }
1554
1555    public void disconnect(final boolean force) {
1556        interrupt();
1557        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1558        if (force) {
1559            forceCloseSocket();
1560        } else {
1561            final TagWriter currentTagWriter = this.tagWriter;
1562            if (currentTagWriter.isActive()) {
1563                currentTagWriter.finish();
1564                final Socket currentSocket = this.socket;
1565                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1566                try {
1567                    currentTagWriter.await(1, TimeUnit.SECONDS);
1568                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1569                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1570                    if (streamCountDownLatch != null) {
1571                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1572                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1573                        } else {
1574                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1575                        }
1576                    }
1577                } catch (InterruptedException e) {
1578                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1579                } catch (final IOException e) {
1580                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1581                } finally {
1582                    FileBackend.close(currentSocket);
1583                }
1584            } else {
1585                forceCloseSocket();
1586            }
1587        }
1588    }
1589
1590    private void resetStreamId() {
1591        this.streamId = null;
1592    }
1593
1594    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1595        synchronized (this.disco) {
1596            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1597            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1598                if (cursor.getValue().getFeatures().contains(feature)) {
1599                    items.add(cursor);
1600                }
1601            }
1602            return items;
1603        }
1604    }
1605
1606    public Jid findDiscoItemByFeature(final String feature) {
1607        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1608        if (items.size() >= 1) {
1609            return items.get(0).getKey();
1610        }
1611        return null;
1612    }
1613
1614    public boolean r() {
1615        if (getFeatures().sm()) {
1616            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1617            return true;
1618        } else {
1619            return false;
1620        }
1621    }
1622
1623    public List<String> getMucServersWithholdAccount() {
1624        List<String> servers = getMucServers();
1625        servers.remove(account.getDomain());
1626        return servers;
1627    }
1628
1629    public List<String> getMucServers() {
1630        List<String> servers = new ArrayList<>();
1631        synchronized (this.disco) {
1632            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1633                final ServiceDiscoveryResult value = cursor.getValue();
1634                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1635                        && value.hasIdentity("conference", "text")
1636                        && !value.getFeatures().contains("jabber:iq:gateway")
1637                        && !value.hasIdentity("conference", "irc")) {
1638                    servers.add(cursor.getKey().toString());
1639                }
1640            }
1641        }
1642        return servers;
1643    }
1644
1645    public String getMucServer() {
1646        List<String> servers = getMucServers();
1647        return servers.size() > 0 ? servers.get(0) : null;
1648    }
1649
1650    public int getTimeToNextAttempt() {
1651        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1652        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1653        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1654        return interval - secondsSinceLast;
1655    }
1656
1657    public int getAttempt() {
1658        return this.attempt;
1659    }
1660
1661    public Features getFeatures() {
1662        return this.features;
1663    }
1664
1665    public long getLastSessionEstablished() {
1666        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1667        return System.currentTimeMillis() - diff;
1668    }
1669
1670    public long getLastConnect() {
1671        return this.lastConnect;
1672    }
1673
1674    public long getLastPingSent() {
1675        return this.lastPingSent;
1676    }
1677
1678    public long getLastDiscoStarted() {
1679        return this.lastDiscoStarted;
1680    }
1681
1682    public long getLastPacketReceived() {
1683        return this.lastPacketReceived;
1684    }
1685
1686    public void sendActive() {
1687        this.sendPacket(new ActivePacket());
1688    }
1689
1690    public void sendInactive() {
1691        this.sendPacket(new InactivePacket());
1692    }
1693
1694    public void resetAttemptCount(boolean resetConnectTime) {
1695        this.attempt = 0;
1696        if (resetConnectTime) {
1697            this.lastConnect = 0;
1698        }
1699    }
1700
1701    public void setInteractive(boolean interactive) {
1702        this.mInteractive = interactive;
1703    }
1704
1705    public Identity getServerIdentity() {
1706        synchronized (this.disco) {
1707            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1708            if (result == null) {
1709                return Identity.UNKNOWN;
1710            }
1711            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1712                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1713                    switch (id.getName()) {
1714                        case "Prosody":
1715                            return Identity.PROSODY;
1716                        case "ejabberd":
1717                            return Identity.EJABBERD;
1718                        case "Slack-XMPP":
1719                            return Identity.SLACK;
1720                    }
1721                }
1722            }
1723        }
1724        return Identity.UNKNOWN;
1725    }
1726
1727    private IqGenerator getIqGenerator() {
1728        return mXmppConnectionService.getIqGenerator();
1729    }
1730
1731    public enum Identity {
1732        FACEBOOK,
1733        SLACK,
1734        EJABBERD,
1735        PROSODY,
1736        NIMBUZZ,
1737        UNKNOWN
1738    }
1739
1740    private static class TlsFactoryVerifier {
1741        private final SSLSocketFactory factory;
1742        private final DomainHostnameVerifier verifier;
1743
1744        TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1745            this.factory = factory;
1746            this.verifier = verifier;
1747            if (factory == null || verifier == null) {
1748                throw new IOException("could not setup ssl");
1749            }
1750        }
1751    }
1752
1753    private class MyKeyManager implements X509KeyManager {
1754        @Override
1755        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1756            return account.getPrivateKeyAlias();
1757        }
1758
1759        @Override
1760        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1761            return null;
1762        }
1763
1764        @Override
1765        public X509Certificate[] getCertificateChain(String alias) {
1766            Log.d(Config.LOGTAG, "getting certificate chain");
1767            try {
1768                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1769            } catch (Exception e) {
1770                Log.d(Config.LOGTAG, e.getMessage());
1771                return new X509Certificate[0];
1772            }
1773        }
1774
1775        @Override
1776        public String[] getClientAliases(String s, Principal[] principals) {
1777            final String alias = account.getPrivateKeyAlias();
1778            return alias != null ? new String[]{alias} : new String[0];
1779        }
1780
1781        @Override
1782        public String[] getServerAliases(String s, Principal[] principals) {
1783            return new String[0];
1784        }
1785
1786        @Override
1787        public PrivateKey getPrivateKey(String alias) {
1788            try {
1789                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1790            } catch (Exception e) {
1791                return null;
1792            }
1793        }
1794    }
1795
1796    private class StateChangingError extends Error {
1797        private final Account.State state;
1798
1799        public StateChangingError(Account.State state) {
1800            this.state = state;
1801        }
1802    }
1803
1804    private class StateChangingException extends IOException {
1805        private final Account.State state;
1806
1807        public StateChangingException(Account.State state) {
1808            this.state = state;
1809        }
1810    }
1811
1812    public class Features {
1813        XmppConnection connection;
1814        private boolean carbonsEnabled = false;
1815        private boolean encryptionEnabled = false;
1816        private boolean blockListRequested = false;
1817
1818        public Features(final XmppConnection connection) {
1819            this.connection = connection;
1820        }
1821
1822        private boolean hasDiscoFeature(final Jid server, final String feature) {
1823            synchronized (XmppConnection.this.disco) {
1824                return connection.disco.containsKey(server) &&
1825                        connection.disco.get(server).getFeatures().contains(feature);
1826            }
1827        }
1828
1829        public boolean carbons() {
1830            return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
1831        }
1832
1833        public boolean commands() {
1834            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
1835        }
1836
1837        public boolean easyOnboardingInvites() {
1838            synchronized (commands) {
1839                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
1840            }
1841        }
1842
1843        public boolean bookmarksConversion() {
1844            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1845        }
1846
1847        public boolean avatarConversion() {
1848            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1849        }
1850
1851        public boolean blocking() {
1852            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
1853        }
1854
1855        public boolean spamReporting() {
1856            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
1857        }
1858
1859        public boolean flexibleOfflineMessageRetrieval() {
1860            return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1861        }
1862
1863        public boolean register() {
1864            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
1865        }
1866
1867        public boolean invite() {
1868            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1869        }
1870
1871        public boolean sm() {
1872            return streamId != null
1873                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1874        }
1875
1876        public boolean csi() {
1877            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1878        }
1879
1880        public boolean pep() {
1881            synchronized (XmppConnection.this.disco) {
1882                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1883                return info != null && info.hasIdentity("pubsub", "pep");
1884            }
1885        }
1886
1887        public boolean pepPersistent() {
1888            synchronized (XmppConnection.this.disco) {
1889                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1890                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1891            }
1892        }
1893
1894        public boolean pepPublishOptions() {
1895            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1896        }
1897
1898        public boolean pepOmemoWhitelisted() {
1899            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1900        }
1901
1902        public boolean mam() {
1903            return MessageArchiveService.Version.has(getAccountFeatures());
1904        }
1905
1906        public List<String> getAccountFeatures() {
1907            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1908            return result == null ? Collections.emptyList() : result.getFeatures();
1909        }
1910
1911        public boolean push() {
1912            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1913                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
1914        }
1915
1916        public boolean rosterVersioning() {
1917            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1918        }
1919
1920        public void setBlockListRequested(boolean value) {
1921            this.blockListRequested = value;
1922        }
1923
1924        public boolean p1S3FileTransfer() {
1925            return hasDiscoFeature(account.getDomain(), Namespace.P1_S3_FILE_TRANSFER);
1926        }
1927
1928        public boolean httpUpload(long filesize) {
1929            if (Config.DISABLE_HTTP_UPLOAD) {
1930                return false;
1931            } else {
1932                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1933                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1934                    if (items.size() > 0) {
1935                        try {
1936                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1937                            if (filesize <= maxsize) {
1938                                return true;
1939                            } else {
1940                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1941                                return false;
1942                            }
1943                        } catch (Exception e) {
1944                            return true;
1945                        }
1946                    }
1947                }
1948                return false;
1949            }
1950        }
1951
1952        public boolean useLegacyHttpUpload() {
1953            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1954        }
1955
1956        public long getMaxHttpUploadSize() {
1957            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1958                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1959                if (items.size() > 0) {
1960                    try {
1961                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1962                    } catch (Exception e) {
1963                        //ignored
1964                    }
1965                }
1966            }
1967            return -1;
1968        }
1969
1970        public boolean stanzaIds() {
1971            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1972        }
1973
1974        public boolean bookmarks2() {
1975            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
1976        }
1977
1978        public boolean externalServiceDiscovery() {
1979            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
1980        }
1981    }
1982}