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