XmppConnection.java

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