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", Namespace.TLS)) {
 470                switchOverToTls();
 471            } else if (nextTag.isStart("success")) {
 472                final Element success = tagReader.readElement(nextTag);
 473                final SaslMechanism.Version version;
 474                try {
 475                    version = SaslMechanism.Version.of(success);
 476                } catch (final IllegalArgumentException e) {
 477                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 478                }
 479                final String challenge;
 480                if (version == SaslMechanism.Version.SASL) {
 481                    challenge = success.getContent();
 482                } else if (version == SaslMechanism.Version.SASL_2) {
 483                    challenge = success.findChildContent("additional-data");
 484                } else {
 485                    throw new AssertionError("Missing implementation for " + version);
 486                }
 487                try {
 488                    saslMechanism.getResponse(challenge);
 489                } catch (final SaslMechanism.AuthenticationException e) {
 490                    Log.e(Config.LOGTAG, String.valueOf(e));
 491                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 492                }
 493                Log.d(
 494                        Config.LOGTAG,
 495                        account.getJid().asBareJid().toString()
 496                                + ": logged in (using "
 497                                + version
 498                                + ")");
 499                account.setKey(
 500                        Account.PINNED_MECHANISM_KEY, String.valueOf(saslMechanism.getPriority()));
 501                if (version == SaslMechanism.Version.SASL_2) {
 502                    final String authorizationIdentifier =
 503                            success.findChildContent("authorization-identifier");
 504                    Log.d(
 505                            Config.LOGTAG,
 506                            account.getJid().asBareJid()
 507                                    + ": SASL 2.0 authorization identifier was "
 508                                    + authorizationIdentifier);
 509                }
 510                if (version == SaslMechanism.Version.SASL) {
 511                    tagReader.reset();
 512                    sendStartStream();
 513                    final Tag tag = tagReader.readTag();
 514                    if (tag != null && tag.isStart("stream")) {
 515                        processStream();
 516                    } else {
 517                        throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 518                    }
 519                    break;
 520                }
 521            } else if (nextTag.isStart("failure", Namespace.TLS)) {
 522                throw new StateChangingException(Account.State.TLS_ERROR);
 523            } else if (nextTag.isStart("failure")) {
 524                final Element failure = tagReader.readElement(nextTag);
 525                final SaslMechanism.Version version;
 526                try {
 527                    version = SaslMechanism.Version.of(failure);
 528                } catch (final IllegalArgumentException e) {
 529                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 530                }
 531                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
 532                if (failure.hasChild("temporary-auth-failure")) {
 533                    throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
 534                } else if (failure.hasChild("account-disabled")) {
 535                    final String text = failure.findChildContent("text");
 536                    if (Strings.isNullOrEmpty(text)) {
 537                        throw new StateChangingException(Account.State.UNAUTHORIZED);
 538                    }
 539                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 540                    if (matcher.find()) {
 541                        final HttpUrl url;
 542                        try {
 543                            url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
 544                        } catch (final IllegalArgumentException e) {
 545                            throw new StateChangingException(Account.State.UNAUTHORIZED);
 546                        }
 547                        if (url.isHttps()) {
 548                            this.redirectionUrl = url;
 549                            throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 550                        }
 551                    }
 552                }
 553                throw new StateChangingException(Account.State.UNAUTHORIZED);
 554            } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
 555                throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
 556            } else if (nextTag.isStart("challenge")) {
 557                final Element challenge = tagReader.readElement(nextTag);
 558                final SaslMechanism.Version version;
 559                try {
 560                    version = SaslMechanism.Version.of(challenge);
 561                } catch (final IllegalArgumentException e) {
 562                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 563                }
 564                final Element response;
 565                if (version == SaslMechanism.Version.SASL) {
 566                    response = new Element("response", Namespace.SASL);
 567                } else if (version == SaslMechanism.Version.SASL_2) {
 568                    response = new Element("response", Namespace.SASL_2);
 569                } else {
 570                    throw new AssertionError("Missing implementation for " + version);
 571                }
 572                try {
 573                    response.setContent(saslMechanism.getResponse(challenge.getContent()));
 574                } catch (final SaslMechanism.AuthenticationException e) {
 575                    // TODO: Send auth abort tag.
 576                    Log.e(Config.LOGTAG, e.toString());
 577                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 578                }
 579                tagWriter.writeElement(response);
 580            } else if (nextTag.isStart("enabled")) {
 581                final Element enabled = tagReader.readElement(nextTag);
 582                if ("true".equals(enabled.getAttribute("resume"))) {
 583                    this.streamId = enabled.getAttribute("id");
 584                    Log.d(
 585                            Config.LOGTAG,
 586                            account.getJid().asBareJid().toString()
 587                                    + ": stream management("
 588                                    + smVersion
 589                                    + ") enabled (resumable)");
 590                } else {
 591                    Log.d(
 592                            Config.LOGTAG,
 593                            account.getJid().asBareJid().toString()
 594                                    + ": stream management("
 595                                    + smVersion
 596                                    + ") enabled");
 597                }
 598                this.stanzasReceived = 0;
 599                this.inSmacksSession = true;
 600                final RequestPacket r = new RequestPacket(smVersion);
 601                tagWriter.writeStanzaAsync(r);
 602            } else if (nextTag.isStart("resumed")) {
 603                this.inSmacksSession = true;
 604                this.isBound = true;
 605                this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 606                lastPacketReceived = SystemClock.elapsedRealtime();
 607                final Element resumed = tagReader.readElement(nextTag);
 608                final String h = resumed.getAttribute("h");
 609                try {
 610                    ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 611                    final boolean acknowledgedMessages;
 612                    synchronized (this.mStanzaQueue) {
 613                        final int serverCount = Integer.parseInt(h);
 614                        if (serverCount < stanzasSent) {
 615                            Log.d(
 616                                    Config.LOGTAG,
 617                                    account.getJid().asBareJid().toString()
 618                                            + ": session resumed with lost packages");
 619                            stanzasSent = serverCount;
 620                        } else {
 621                            Log.d(
 622                                    Config.LOGTAG,
 623                                    account.getJid().asBareJid().toString() + ": session resumed");
 624                        }
 625                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 626                        for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 627                            failedStanzas.add(mStanzaQueue.valueAt(i));
 628                        }
 629                        mStanzaQueue.clear();
 630                    }
 631                    if (acknowledgedMessages) {
 632                        mXmppConnectionService.updateConversationUi();
 633                    }
 634                    Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 635                    for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 636                        if (packet instanceof MessagePacket) {
 637                            MessagePacket message = (MessagePacket) packet;
 638                            mXmppConnectionService.markMessage(
 639                                    account,
 640                                    message.getTo().asBareJid(),
 641                                    message.getId(),
 642                                    Message.STATUS_UNSEND);
 643                        }
 644                        sendPacket(packet);
 645                    }
 646                } catch (final NumberFormatException ignored) {
 647                }
 648                Log.d(
 649                        Config.LOGTAG,
 650                        account.getJid().asBareJid()
 651                                + ": online with resource "
 652                                + account.getResource());
 653                changeStatus(Account.State.ONLINE);
 654            } else if (nextTag.isStart("r")) {
 655                tagReader.readElement(nextTag);
 656                if (Config.EXTENDED_SM_LOGGING) {
 657                    Log.d(
 658                            Config.LOGTAG,
 659                            account.getJid().asBareJid()
 660                                    + ": acknowledging stanza #"
 661                                    + this.stanzasReceived);
 662                }
 663                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 664                tagWriter.writeStanzaAsync(ack);
 665            } else if (nextTag.isStart("a")) {
 666                boolean accountUiNeedsRefresh = false;
 667                synchronized (NotificationService.CATCHUP_LOCK) {
 668                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 669                        final int messageCount = mSmCatchupMessageCounter.get();
 670                        final int pendingIQs = packetCallbacks.size();
 671                        Log.d(
 672                                Config.LOGTAG,
 673                                account.getJid().asBareJid()
 674                                        + ": SM catchup complete (messages="
 675                                        + messageCount
 676                                        + ", pending IQs="
 677                                        + pendingIQs
 678                                        + ")");
 679                        accountUiNeedsRefresh = true;
 680                        if (messageCount > 0) {
 681                            mXmppConnectionService
 682                                    .getNotificationService()
 683                                    .finishBacklog(true, account);
 684                        }
 685                    }
 686                }
 687                if (accountUiNeedsRefresh) {
 688                    mXmppConnectionService.updateAccountUi();
 689                }
 690                final Element ack = tagReader.readElement(nextTag);
 691                lastPacketReceived = SystemClock.elapsedRealtime();
 692                try {
 693                    final boolean acknowledgedMessages;
 694                    synchronized (this.mStanzaQueue) {
 695                        final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
 696                        acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
 697                    }
 698                    if (acknowledgedMessages) {
 699                        mXmppConnectionService.updateConversationUi();
 700                    }
 701                } catch (NumberFormatException | NullPointerException e) {
 702                    Log.d(
 703                            Config.LOGTAG,
 704                            account.getJid().asBareJid()
 705                                    + ": server send ack without sequence number");
 706                }
 707            } else if (nextTag.isStart("failed")) {
 708                Element failed = tagReader.readElement(nextTag);
 709                try {
 710                    final int serverCount = Integer.parseInt(failed.getAttribute("h"));
 711                    Log.d(
 712                            Config.LOGTAG,
 713                            account.getJid().asBareJid()
 714                                    + ": resumption failed but server acknowledged stanza #"
 715                                    + serverCount);
 716                    final boolean acknowledgedMessages;
 717                    synchronized (this.mStanzaQueue) {
 718                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 719                    }
 720                    if (acknowledgedMessages) {
 721                        mXmppConnectionService.updateConversationUi();
 722                    }
 723                } catch (NumberFormatException | NullPointerException e) {
 724                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
 725                }
 726                resetStreamId();
 727                sendBindRequest();
 728            } else if (nextTag.isStart("iq")) {
 729                processIq(nextTag);
 730            } else if (nextTag.isStart("message")) {
 731                processMessage(nextTag);
 732            } else if (nextTag.isStart("presence")) {
 733                processPresence(nextTag);
 734            }
 735            nextTag = tagReader.readTag();
 736        }
 737        if (nextTag != null && nextTag.isEnd("stream")) {
 738            streamCountDownLatch.countDown();
 739        }
 740    }
 741
 742    private boolean acknowledgeStanzaUpTo(int serverCount) {
 743        if (serverCount > stanzasSent) {
 744            Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
 745        }
 746        boolean acknowledgedMessages = false;
 747        for (int i = 0; i < mStanzaQueue.size(); ++i) {
 748            if (serverCount >= mStanzaQueue.keyAt(i)) {
 749                if (Config.EXTENDED_SM_LOGGING) {
 750                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
 751                }
 752                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
 753                if (stanza instanceof MessagePacket && acknowledgedListener != null) {
 754                    final MessagePacket packet = (MessagePacket) stanza;
 755                    final String id = packet.getId();
 756                    final Jid to = packet.getTo();
 757                    if (id != null && to != null) {
 758                        acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, to, id);
 759                    }
 760                }
 761                mStanzaQueue.removeAt(i);
 762                i--;
 763            }
 764        }
 765        return acknowledgedMessages;
 766    }
 767
 768    private @NonNull
 769    Element processPacket(final Tag currentTag, final int packetType) throws IOException {
 770        final Element element;
 771        switch (packetType) {
 772            case PACKET_IQ:
 773                element = new IqPacket();
 774                break;
 775            case PACKET_MESSAGE:
 776                element = new MessagePacket();
 777                break;
 778            case PACKET_PRESENCE:
 779                element = new PresencePacket();
 780                break;
 781            default:
 782                throw new AssertionError("Should never encounter invalid type");
 783        }
 784        element.setAttributes(currentTag.getAttributes());
 785        Tag nextTag = tagReader.readTag();
 786        if (nextTag == null) {
 787            throw new IOException("interrupted mid tag");
 788        }
 789        while (!nextTag.isEnd(element.getName())) {
 790            if (!nextTag.isNo()) {
 791                element.addChild(tagReader.readElement(nextTag));
 792            }
 793            nextTag = tagReader.readTag();
 794            if (nextTag == null) {
 795                throw new IOException("interrupted mid tag");
 796            }
 797        }
 798        if (stanzasReceived == Integer.MAX_VALUE) {
 799            resetStreamId();
 800            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 801        }
 802        if (inSmacksSession) {
 803            ++stanzasReceived;
 804        } else if (features.sm()) {
 805            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 806        }
 807        lastPacketReceived = SystemClock.elapsedRealtime();
 808        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 809            Log.d(Config.LOGTAG, "[background stanza] " + element);
 810        }
 811        if (element instanceof IqPacket
 812                && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
 813                && element.hasChild("jingle", Namespace.JINGLE)) {
 814            return JinglePacket.upgrade((IqPacket) element);
 815        } else {
 816            return element;
 817        }
 818    }
 819
 820    private void processIq(final Tag currentTag) throws IOException {
 821        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 822        if (!packet.valid()) {
 823            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 824            return;
 825        }
 826        if (packet instanceof JinglePacket) {
 827            if (this.jingleListener != null) {
 828                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 829            }
 830        } else {
 831            OnIqPacketReceived callback = null;
 832            synchronized (this.packetCallbacks) {
 833                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 834                if (packetCallbackDuple != null) {
 835                    // Packets to the server should have responses from the server
 836                    if (packetCallbackDuple.first.toServer(account)) {
 837                        if (packet.fromServer(account)) {
 838                            callback = packetCallbackDuple.second;
 839                            packetCallbacks.remove(packet.getId());
 840                        } else {
 841                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 842                        }
 843                    } else {
 844                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 845                            callback = packetCallbackDuple.second;
 846                            packetCallbacks.remove(packet.getId());
 847                        } else {
 848                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 849                        }
 850                    }
 851                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 852                    callback = this.unregisteredIqListener;
 853                }
 854            }
 855            if (callback != null) {
 856                try {
 857                    callback.onIqPacketReceived(account, packet);
 858                } catch (StateChangingError error) {
 859                    throw new StateChangingException(error.state);
 860                }
 861            }
 862        }
 863    }
 864
 865    private void processMessage(final Tag currentTag) throws IOException {
 866        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 867        if (!packet.valid()) {
 868            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 869            return;
 870        }
 871        this.messageListener.onMessagePacketReceived(account, packet);
 872    }
 873
 874    private void processPresence(final Tag currentTag) throws IOException {
 875        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 876        if (!packet.valid()) {
 877            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 878            return;
 879        }
 880        this.presenceListener.onPresencePacketReceived(account, packet);
 881    }
 882
 883    private void sendStartTLS() throws IOException {
 884        final Tag startTLS = Tag.empty("starttls");
 885        startTLS.setAttribute("xmlns", Namespace.TLS);
 886        tagWriter.writeTag(startTLS);
 887    }
 888
 889    private void switchOverToTls() throws XmlPullParserException, IOException {
 890        tagReader.readTag();
 891        final Socket socket = this.socket;
 892        final SSLSocket sslSocket = upgradeSocketToTls(socket);
 893        tagReader.setInputStream(sslSocket.getInputStream());
 894        tagWriter.setOutputStream(sslSocket.getOutputStream());
 895        sendStartStream();
 896        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 897        features.encryptionEnabled = true;
 898        final Tag tag = tagReader.readTag();
 899        if (tag != null && tag.isStart("stream")) {
 900            SSLSocketHelper.log(account, sslSocket);
 901            processStream();
 902        } else {
 903            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 904        }
 905        sslSocket.close();
 906    }
 907
 908    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
 909        final SSLSocketFactory sslSocketFactory;
 910        try {
 911            sslSocketFactory = getSSLSocketFactory();
 912        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
 913            throw new StateChangingException(Account.State.TLS_ERROR);
 914        }
 915        final InetAddress address = socket.getInetAddress();
 916        final SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 917        SSLSocketHelper.setSecurity(sslSocket);
 918        SSLSocketHelper.setHostname(sslSocket, IDN.toASCII(account.getServer()));
 919        SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 920        final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
 921        try {
 922            if (!xmppDomainVerifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 923                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate domain verification failed");
 924                FileBackend.close(sslSocket);
 925                throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
 926            }
 927        } catch (final SSLPeerUnverifiedException e) {
 928            FileBackend.close(sslSocket);
 929            throw new StateChangingException(Account.State.TLS_ERROR);
 930        }
 931        return sslSocket;
 932    }
 933
 934    private void processStreamFeatures(final Tag currentTag) throws IOException {
 935        this.streamFeatures = tagReader.readElement(currentTag);
 936        final boolean isSecure =
 937                features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 938        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 939        if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
 940                && !features.encryptionEnabled) {
 941            sendStartTLS();
 942        } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
 943                && account.isOptionSet(Account.OPTION_REGISTER)) {
 944            if (isSecure) {
 945                register();
 946            } else {
 947                Log.d(
 948                        Config.LOGTAG,
 949                        account.getJid().asBareJid()
 950                                + ": unable to find STARTTLS for registration process "
 951                                + XmlHelper.printElementNames(this.streamFeatures));
 952                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 953            }
 954        } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
 955                && account.isOptionSet(Account.OPTION_REGISTER)) {
 956            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 957        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL_2)
 958                && shouldAuthenticate
 959                && isSecure) {
 960            authenticate(SaslMechanism.Version.SASL_2);
 961        } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
 962                && shouldAuthenticate
 963                && isSecure) {
 964            authenticate(SaslMechanism.Version.SASL);
 965        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion)
 966                && streamId != null) {
 967            if (Config.EXTENDED_SM_LOGGING) {
 968                Log.d(
 969                        Config.LOGTAG,
 970                        account.getJid().asBareJid()
 971                                + ": resuming after stanza #"
 972                                + stanzasReceived);
 973            }
 974            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 975            this.mSmCatchupMessageCounter.set(0);
 976            this.mWaitingForSmCatchup.set(true);
 977            this.tagWriter.writeStanzaAsync(resume);
 978        } else if (needsBinding) {
 979            if (this.streamFeatures.hasChild("bind", Namespace.BIND) && isSecure) {
 980                sendBindRequest();
 981            } else {
 982                Log.d(
 983                        Config.LOGTAG,
 984                        account.getJid().asBareJid()
 985                                + ": unable to find bind feature "
 986                                + XmlHelper.printElementNames(this.streamFeatures));
 987                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 988            }
 989        }
 990    }
 991
 992    private void authenticate(final SaslMechanism.Version version) throws IOException {
 993        final List<String> mechanisms = extractMechanisms(streamFeatures.findChild("mechanisms"));
 994        if (mechanisms.contains(External.MECHANISM) && account.getPrivateKeyAlias() != null) {
 995            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 996        } else if (mechanisms.contains(ScramSha512.MECHANISM)) {
 997            saslMechanism = new ScramSha512(tagWriter, account, mXmppConnectionService.getRNG());
 998        } else if (mechanisms.contains(ScramSha256.MECHANISM)) {
 999            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
1000        } else if (mechanisms.contains(ScramSha1.MECHANISM)) {
1001            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
1002        } else if (mechanisms.contains(Plain.MECHANISM) && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
1003            saslMechanism = new Plain(tagWriter, account);
1004        } else if (mechanisms.contains(DigestMd5.MECHANISM)) {
1005            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
1006        } else if (mechanisms.contains(Anonymous.MECHANISM)) {
1007            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
1008        }
1009        if (saslMechanism == null) {
1010            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find supported SASL mechanism in " + mechanisms);
1011            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1012        }
1013        final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
1014        if (pinnedMechanism > saslMechanism.getPriority()) {
1015            Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
1016                    " has lower priority (" + saslMechanism.getPriority() +
1017                    ") than pinned priority (" + pinnedMechanism +
1018                    "). Possible downgrade attack?");
1019            throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1020        }
1021        final String firstMessage = saslMechanism.getClientFirstMessage();
1022        final Element authenticate;
1023        if (version == SaslMechanism.Version.SASL) {
1024            authenticate = new Element("auth", Namespace.SASL);
1025            if (!Strings.isNullOrEmpty(firstMessage)) {
1026                authenticate.setContent(firstMessage);
1027            }
1028        } else if (version == SaslMechanism.Version.SASL_2) {
1029            authenticate = new Element("authenticate", Namespace.SASL_2);
1030            if (!Strings.isNullOrEmpty(firstMessage)) {
1031                authenticate.addChild("initial-response").setContent(firstMessage);
1032            }
1033            // TODO place to add extensions
1034        } else {
1035            throw new AssertionError("Missing implementation for " + version);
1036        }
1037
1038        Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with "+version+ "/" + saslMechanism.getMechanism());
1039        authenticate.setAttribute("mechanism", saslMechanism.getMechanism());
1040        tagWriter.writeElement(authenticate);
1041    }
1042
1043    private List<String> extractMechanisms(final Element stream) {
1044        final ArrayList<String> mechanisms = new ArrayList<>(stream
1045                .getChildren().size());
1046        for (final Element child : stream.getChildren()) {
1047            mechanisms.add(child.getContent());
1048        }
1049        return mechanisms;
1050    }
1051
1052
1053    private void register() {
1054        final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
1055        if (preAuth != null && features.invite()) {
1056            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1057            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1058            sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
1059                if (response.getType() == IqPacket.TYPE.RESULT) {
1060                    sendRegistryRequest();
1061                } else {
1062                    final String error = response.getErrorCondition();
1063                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to pre auth. " + error);
1064                    throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1065                }
1066            }, true);
1067        } else {
1068            sendRegistryRequest();
1069        }
1070    }
1071
1072    private void sendRegistryRequest() {
1073        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1074        register.query(Namespace.REGISTER);
1075        register.setTo(account.getDomain());
1076        sendUnmodifiedIqPacket(register, (account, packet) -> {
1077            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1078                return;
1079            }
1080            if (packet.getType() == IqPacket.TYPE.ERROR) {
1081                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1082            }
1083            final Element query = packet.query(Namespace.REGISTER);
1084            if (query.hasChild("username") && (query.hasChild("password"))) {
1085                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1086                final Element username = new Element("username").setContent(account.getUsername());
1087                final Element password = new Element("password").setContent(account.getPassword());
1088                register1.query(Namespace.REGISTER).addChild(username);
1089                register1.query().addChild(password);
1090                register1.setFrom(account.getJid().asBareJid());
1091                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1092            } else if (query.hasChild("x", Namespace.DATA)) {
1093                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1094                final Element blob = query.findChild("data", "urn:xmpp:bob");
1095                final String id = packet.getId();
1096                InputStream is;
1097                if (blob != null) {
1098                    try {
1099                        final String base64Blob = blob.getContent();
1100                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1101                        is = new ByteArrayInputStream(strBlob);
1102                    } catch (Exception e) {
1103                        is = null;
1104                    }
1105                } else {
1106                    final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
1107                    try {
1108                        final String url = data.getValue("url");
1109                        final String fallbackUrl = data.getValue("captcha-fallback-url");
1110                        if (url != null) {
1111                            is = HttpConnectionManager.open(url, useTor);
1112                        } else if (fallbackUrl != null) {
1113                            is = HttpConnectionManager.open(fallbackUrl, useTor);
1114                        } else {
1115                            is = null;
1116                        }
1117                    } catch (final IOException e) {
1118                        Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to fetch captcha", e);
1119                        is = null;
1120                    }
1121                }
1122
1123                if (is != null) {
1124                    Bitmap captcha = BitmapFactory.decodeStream(is);
1125                    try {
1126                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
1127                            return;
1128                        }
1129                    } catch (Exception e) {
1130                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1131                    }
1132                }
1133                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1134            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
1135                final String instructions = query.findChildContent("instructions");
1136                final Element oob = query.findChild("x", Namespace.OOB);
1137                final String url = oob == null ? null : oob.findChildContent("url");
1138                if (url != null) {
1139                    setAccountCreationFailed(url);
1140                } else if (instructions != null) {
1141                    final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1142                    if (matcher.find()) {
1143                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1144                    }
1145                }
1146                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1147            }
1148        }, true);
1149    }
1150
1151    private void setAccountCreationFailed(final String url) {
1152        final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1153        if (httpUrl != null && httpUrl.isHttps()) {
1154            this.redirectionUrl = httpUrl;
1155            throw new StateChangingError(Account.State.REGISTRATION_WEB);
1156        }
1157        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1158    }
1159
1160    public HttpUrl getRedirectionUrl() {
1161        return this.redirectionUrl;
1162    }
1163
1164    public void resetEverything() {
1165        resetAttemptCount(true);
1166        resetStreamId();
1167        clearIqCallbacks();
1168        this.stanzasSent = 0;
1169        mStanzaQueue.clear();
1170        this.redirectionUrl = null;
1171        synchronized (this.disco) {
1172            disco.clear();
1173        }
1174        synchronized (this.commands) {
1175            this.commands.clear();
1176        }
1177    }
1178
1179    private void sendBindRequest() {
1180        try {
1181            mXmppConnectionService.restoredFromDatabaseLatch.await();
1182        } catch (InterruptedException e) {
1183            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1184            return;
1185        }
1186        clearIqCallbacks();
1187        if (account.getJid().isBareJid()) {
1188            account.setResource(this.createNewResource());
1189        } else {
1190            fixResource(mXmppConnectionService, account);
1191        }
1192        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1193        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1194        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1195        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1196            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1197                return;
1198            }
1199            final Element bind = packet.findChild("bind");
1200            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1201                isBound = true;
1202                final Element jid = bind.findChild("jid");
1203                if (jid != null && jid.getContent() != null) {
1204                    try {
1205                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1206                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1207                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1208                            throw new StateChangingError(Account.State.BIND_FAILURE);
1209                        }
1210                        if (account.setJid(assignedJid)) {
1211                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1212                            mXmppConnectionService.databaseBackend.updateAccount(account);
1213                        }
1214                        if (streamFeatures.hasChild("session")
1215                                && !streamFeatures.findChild("session").hasChild("optional")) {
1216                            sendStartSession();
1217                        } else {
1218                            sendPostBindInitialization();
1219                        }
1220                        return;
1221                    } catch (final IllegalArgumentException e) {
1222                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1223                    }
1224                } else {
1225                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1226                }
1227            } else {
1228                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet);
1229            }
1230            final Element error = packet.findChild("error");
1231            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1232                account.setResource(createNewResource());
1233            }
1234            throw new StateChangingError(Account.State.BIND_FAILURE);
1235        }, true);
1236    }
1237
1238    private void clearIqCallbacks() {
1239        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1240        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1241        synchronized (this.packetCallbacks) {
1242            if (this.packetCallbacks.size() == 0) {
1243                return;
1244            }
1245            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1246            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1247            while (iterator.hasNext()) {
1248                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1249                callbacks.add(entry.second);
1250                iterator.remove();
1251            }
1252        }
1253        for (OnIqPacketReceived callback : callbacks) {
1254            try {
1255                callback.onIqPacketReceived(account, failurePacket);
1256            } catch (StateChangingError error) {
1257                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1258                //ignore
1259            }
1260        }
1261        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1262    }
1263
1264    public void sendDiscoTimeout() {
1265        if (mWaitForDisco.compareAndSet(true, false)) {
1266            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1267            finalizeBind();
1268        }
1269    }
1270
1271    private void sendStartSession() {
1272        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1273        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1274        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1275        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1276            if (packet.getType() == IqPacket.TYPE.RESULT) {
1277                sendPostBindInitialization();
1278            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1279                throw new StateChangingError(Account.State.SESSION_FAILURE);
1280            }
1281        }, true);
1282    }
1283
1284    private void sendPostBindInitialization() {
1285        smVersion = 0;
1286        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1287            smVersion = 3;
1288        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1289            smVersion = 2;
1290        }
1291        if (smVersion != 0) {
1292            synchronized (this.mStanzaQueue) {
1293                final EnablePacket enable = new EnablePacket(smVersion);
1294                tagWriter.writeStanzaAsync(enable);
1295                stanzasSent = 0;
1296                mStanzaQueue.clear();
1297            }
1298        }
1299        features.carbonsEnabled = false;
1300        features.blockListRequested = false;
1301        synchronized (this.disco) {
1302            this.disco.clear();
1303        }
1304        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1305        mPendingServiceDiscoveries.set(0);
1306        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain().toEscapedString())) {
1307            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1308            mWaitForDisco.set(false);
1309        } else {
1310            mWaitForDisco.set(true);
1311        }
1312        lastDiscoStarted = SystemClock.elapsedRealtime();
1313        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1314        Element caps = streamFeatures.findChild("c");
1315        final String hash = caps == null ? null : caps.getAttribute("hash");
1316        final String ver = caps == null ? null : caps.getAttribute("ver");
1317        ServiceDiscoveryResult discoveryResult = null;
1318        if (hash != null && ver != null) {
1319            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1320        }
1321        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1322        if (requestDiscoItemsFirst) {
1323            sendServiceDiscoveryItems(account.getDomain());
1324        }
1325        if (discoveryResult == null) {
1326            sendServiceDiscoveryInfo(account.getDomain());
1327        } else {
1328            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1329            disco.put(account.getDomain(), discoveryResult);
1330        }
1331        discoverMamPreferences();
1332        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1333        if (!requestDiscoItemsFirst) {
1334            sendServiceDiscoveryItems(account.getDomain());
1335        }
1336
1337        if (!mWaitForDisco.get()) {
1338            finalizeBind();
1339        }
1340        this.lastSessionStarted = SystemClock.elapsedRealtime();
1341    }
1342
1343    private void sendServiceDiscoveryInfo(final Jid jid) {
1344        mPendingServiceDiscoveries.incrementAndGet();
1345        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1346        iq.setTo(jid);
1347        iq.query("http://jabber.org/protocol/disco#info");
1348        this.sendIqPacket(iq, (account, packet) -> {
1349            if (packet.getType() == IqPacket.TYPE.RESULT) {
1350                boolean advancedStreamFeaturesLoaded;
1351                synchronized (XmppConnection.this.disco) {
1352                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1353                    if (jid.equals(account.getDomain())) {
1354                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1355                    }
1356                    disco.put(jid, result);
1357                    advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain())
1358                            && disco.containsKey(account.getJid().asBareJid());
1359                }
1360                if (advancedStreamFeaturesLoaded && (jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid()))) {
1361                    enableAdvancedStreamFeatures();
1362                }
1363            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1364                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1365                final boolean serverOrAccount = jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid());
1366                final boolean advancedStreamFeaturesLoaded;
1367                if (serverOrAccount) {
1368                    synchronized (XmppConnection.this.disco) {
1369                        disco.put(jid, ServiceDiscoveryResult.empty());
1370                        advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain()) && disco.containsKey(account.getJid().asBareJid());
1371                    }
1372                } else {
1373                    advancedStreamFeaturesLoaded = false;
1374                }
1375                if (advancedStreamFeaturesLoaded) {
1376                    enableAdvancedStreamFeatures();
1377                }
1378            }
1379            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1380                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1381                        && mWaitForDisco.compareAndSet(true, false)) {
1382                    finalizeBind();
1383                }
1384            }
1385        });
1386    }
1387
1388    private void discoverMamPreferences() {
1389        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1390        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1391        sendIqPacket(request, (account, response) -> {
1392            if (response.getType() == IqPacket.TYPE.RESULT) {
1393                Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1394                isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1395            }
1396        });
1397    }
1398
1399    private void discoverCommands() {
1400        final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1401        request.setTo(account.getDomain());
1402        request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1403        sendIqPacket(request, (account, response) -> {
1404            if (response.getType() == IqPacket.TYPE.RESULT) {
1405                final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1406                if (query == null) {
1407                    return;
1408                }
1409                final HashMap<String, Jid> commands = new HashMap<>();
1410                for (final Element child : query.getChildren()) {
1411                    if ("item".equals(child.getName())) {
1412                        final String node = child.getAttribute("node");
1413                        final Jid jid = child.getAttributeAsJid("jid");
1414                        if (node != null && jid != null) {
1415                            commands.put(node, jid);
1416                        }
1417                    }
1418                }
1419                Log.d(Config.LOGTAG, commands.toString());
1420                synchronized (this.commands) {
1421                    this.commands.clear();
1422                    this.commands.putAll(commands);
1423                }
1424            }
1425        });
1426    }
1427
1428    public boolean isMamPreferenceAlways() {
1429        return isMamPreferenceAlways;
1430    }
1431
1432    private void finalizeBind() {
1433        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1434        if (bindListener != null) {
1435            bindListener.onBind(account);
1436        }
1437        changeStatus(Account.State.ONLINE);
1438    }
1439
1440    private void enableAdvancedStreamFeatures() {
1441        if (getFeatures().blocking() && !features.blockListRequested) {
1442            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1443            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1444        }
1445        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1446            listener.onAdvancedStreamFeaturesAvailable(account);
1447        }
1448        if (getFeatures().carbons() && !features.carbonsEnabled) {
1449            sendEnableCarbons();
1450        }
1451        if (getFeatures().commands()) {
1452            discoverCommands();
1453        }
1454    }
1455
1456    private void sendServiceDiscoveryItems(final Jid server) {
1457        mPendingServiceDiscoveries.incrementAndGet();
1458        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1459        iq.setTo(server.getDomain());
1460        iq.query("http://jabber.org/protocol/disco#items");
1461        this.sendIqPacket(iq, (account, packet) -> {
1462            if (packet.getType() == IqPacket.TYPE.RESULT) {
1463                final HashSet<Jid> items = new HashSet<>();
1464                final List<Element> elements = packet.query().getChildren();
1465                for (final Element element : elements) {
1466                    if (element.getName().equals("item")) {
1467                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1468                        if (jid != null && !jid.equals(account.getDomain())) {
1469                            items.add(jid);
1470                        }
1471                    }
1472                }
1473                for (Jid jid : items) {
1474                    sendServiceDiscoveryInfo(jid);
1475                }
1476            } else {
1477                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1478            }
1479            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1480                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1481                        && mWaitForDisco.compareAndSet(true, false)) {
1482                    finalizeBind();
1483                }
1484            }
1485        });
1486    }
1487
1488    private void sendEnableCarbons() {
1489        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1490        iq.addChild("enable", "urn:xmpp:carbons:2");
1491        this.sendIqPacket(iq, (account, packet) -> {
1492            if (!packet.hasChild("error")) {
1493                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1494                        + ": successfully enabled carbons");
1495                features.carbonsEnabled = true;
1496            } else {
1497                Log.d(Config.LOGTAG, account.getJid().asBareJid()
1498                        + ": could not enable carbons " + packet);
1499            }
1500        });
1501    }
1502
1503    private void processStreamError(final Tag currentTag) throws IOException {
1504        final Element streamError = tagReader.readElement(currentTag);
1505        if (streamError == null) {
1506            return;
1507        }
1508        if (streamError.hasChild("conflict")) {
1509            account.setResource(createNewResource());
1510            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1511            throw new IOException();
1512        } else if (streamError.hasChild("host-unknown")) {
1513            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1514        } else if (streamError.hasChild("policy-violation")) {
1515            this.lastConnect = SystemClock.elapsedRealtime();
1516            final String text = streamError.findChildContent("text");
1517            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1518            failPendingMessages(text);
1519            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1520        } else {
1521            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
1522            throw new StateChangingException(Account.State.STREAM_ERROR);
1523        }
1524    }
1525
1526    private void failPendingMessages(final String error) {
1527        synchronized (this.mStanzaQueue) {
1528            for (int i = 0; i < mStanzaQueue.size(); ++i) {
1529                final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1530                if (stanza instanceof MessagePacket) {
1531                    final MessagePacket packet = (MessagePacket) stanza;
1532                    final String id = packet.getId();
1533                    final Jid to = packet.getTo();
1534                    mXmppConnectionService.markMessage(account,
1535                            to.asBareJid(),
1536                            id,
1537                            Message.STATUS_SEND_FAILED,
1538                            error);
1539                }
1540            }
1541        }
1542    }
1543
1544    private void sendStartStream() throws IOException {
1545        final Tag stream = Tag.start("stream:stream");
1546        stream.setAttribute("to", account.getServer());
1547        stream.setAttribute("version", "1.0");
1548        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1549        stream.setAttribute("xmlns", "jabber:client");
1550        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1551        tagWriter.writeTag(stream);
1552    }
1553
1554    private String createNewResource() {
1555        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1556    }
1557
1558    private String nextRandomId() {
1559        return nextRandomId(false);
1560    }
1561
1562    private String nextRandomId(boolean s) {
1563        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1564    }
1565
1566    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1567        packet.setFrom(account.getJid());
1568        return this.sendUnmodifiedIqPacket(packet, callback, false);
1569    }
1570
1571    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1572        if (packet.getId() == null) {
1573            packet.setAttribute("id", nextRandomId());
1574        }
1575        if (callback != null) {
1576            synchronized (this.packetCallbacks) {
1577                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1578            }
1579        }
1580        this.sendPacket(packet, force);
1581        return packet.getId();
1582    }
1583
1584    public void sendMessagePacket(final MessagePacket packet) {
1585        this.sendPacket(packet);
1586    }
1587
1588    public void sendPresencePacket(final PresencePacket packet) {
1589        this.sendPacket(packet);
1590    }
1591
1592    private synchronized void sendPacket(final AbstractStanza packet) {
1593        sendPacket(packet, false);
1594    }
1595
1596    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1597        if (stanzasSent == Integer.MAX_VALUE) {
1598            resetStreamId();
1599            disconnect(true);
1600            return;
1601        }
1602        synchronized (this.mStanzaQueue) {
1603            if (force || isBound) {
1604                tagWriter.writeStanzaAsync(packet);
1605            } else {
1606                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1607            }
1608            if (packet instanceof AbstractAcknowledgeableStanza) {
1609                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1610
1611                if (this.mStanzaQueue.size() != 0) {
1612                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1613                    if (currentHighestKey != stanzasSent) {
1614                        throw new AssertionError("Stanza count messed up");
1615                    }
1616                }
1617
1618                ++stanzasSent;
1619                this.mStanzaQueue.append(stanzasSent, stanza);
1620                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1621                    if (Config.EXTENDED_SM_LOGGING) {
1622                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1623                    }
1624                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1625                }
1626            }
1627        }
1628    }
1629
1630    public void sendPing() {
1631        if (!r()) {
1632            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1633            iq.setFrom(account.getJid());
1634            iq.addChild("ping", Namespace.PING);
1635            this.sendIqPacket(iq, null);
1636        }
1637        this.lastPingSent = SystemClock.elapsedRealtime();
1638    }
1639
1640    public void setOnMessagePacketReceivedListener(
1641            final OnMessagePacketReceived listener) {
1642        this.messageListener = listener;
1643    }
1644
1645    public void setOnUnregisteredIqPacketReceivedListener(
1646            final OnIqPacketReceived listener) {
1647        this.unregisteredIqListener = listener;
1648    }
1649
1650    public void setOnPresencePacketReceivedListener(
1651            final OnPresencePacketReceived listener) {
1652        this.presenceListener = listener;
1653    }
1654
1655    public void setOnJinglePacketReceivedListener(
1656            final OnJinglePacketReceived listener) {
1657        this.jingleListener = listener;
1658    }
1659
1660    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1661        this.statusListener = listener;
1662    }
1663
1664    public void setOnBindListener(final OnBindListener listener) {
1665        this.bindListener = listener;
1666    }
1667
1668    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1669        this.acknowledgedListener = listener;
1670    }
1671
1672    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1673        this.advancedStreamFeaturesLoadedListeners.add(listener);
1674    }
1675
1676    private void forceCloseSocket() {
1677        FileBackend.close(this.socket);
1678        FileBackend.close(this.tagReader);
1679    }
1680
1681    public void interrupt() {
1682        if (this.mThread != null) {
1683            this.mThread.interrupt();
1684        }
1685    }
1686
1687    public void disconnect(final boolean force) {
1688        interrupt();
1689        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1690        if (force) {
1691            forceCloseSocket();
1692        } else {
1693            final TagWriter currentTagWriter = this.tagWriter;
1694            if (currentTagWriter.isActive()) {
1695                currentTagWriter.finish();
1696                final Socket currentSocket = this.socket;
1697                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1698                try {
1699                    currentTagWriter.await(1, TimeUnit.SECONDS);
1700                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1701                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1702                    if (streamCountDownLatch != null) {
1703                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1704                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1705                        } else {
1706                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1707                        }
1708                    }
1709                } catch (InterruptedException e) {
1710                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1711                } catch (final IOException e) {
1712                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1713                } finally {
1714                    FileBackend.close(currentSocket);
1715                }
1716            } else {
1717                forceCloseSocket();
1718            }
1719        }
1720    }
1721
1722    private void resetStreamId() {
1723        this.streamId = null;
1724    }
1725
1726    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1727        synchronized (this.disco) {
1728            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1729            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1730                if (cursor.getValue().getFeatures().contains(feature)) {
1731                    items.add(cursor);
1732                }
1733            }
1734            return items;
1735        }
1736    }
1737
1738    public Jid findDiscoItemByFeature(final String feature) {
1739        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1740        if (items.size() >= 1) {
1741            return items.get(0).getKey();
1742        }
1743        return null;
1744    }
1745
1746    public boolean r() {
1747        if (getFeatures().sm()) {
1748            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1749            return true;
1750        } else {
1751            return false;
1752        }
1753    }
1754
1755    public List<String> getMucServersWithholdAccount() {
1756        final List<String> servers = getMucServers();
1757        servers.remove(account.getDomain().toEscapedString());
1758        return servers;
1759    }
1760
1761    public List<String> getMucServers() {
1762        List<String> servers = new ArrayList<>();
1763        synchronized (this.disco) {
1764            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1765                final ServiceDiscoveryResult value = cursor.getValue();
1766                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1767                        && value.hasIdentity("conference", "text")
1768                        && !value.getFeatures().contains("jabber:iq:gateway")
1769                        && !value.hasIdentity("conference", "irc")) {
1770                    servers.add(cursor.getKey().toString());
1771                }
1772            }
1773        }
1774        return servers;
1775    }
1776
1777    public String getMucServer() {
1778        List<String> servers = getMucServers();
1779        return servers.size() > 0 ? servers.get(0) : null;
1780    }
1781
1782    public int getTimeToNextAttempt() {
1783        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1784        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1785        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1786        return interval - secondsSinceLast;
1787    }
1788
1789    public int getAttempt() {
1790        return this.attempt;
1791    }
1792
1793    public Features getFeatures() {
1794        return this.features;
1795    }
1796
1797    public long getLastSessionEstablished() {
1798        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1799        return System.currentTimeMillis() - diff;
1800    }
1801
1802    public long getLastConnect() {
1803        return this.lastConnect;
1804    }
1805
1806    public long getLastPingSent() {
1807        return this.lastPingSent;
1808    }
1809
1810    public long getLastDiscoStarted() {
1811        return this.lastDiscoStarted;
1812    }
1813
1814    public long getLastPacketReceived() {
1815        return this.lastPacketReceived;
1816    }
1817
1818    public void sendActive() {
1819        this.sendPacket(new ActivePacket());
1820    }
1821
1822    public void sendInactive() {
1823        this.sendPacket(new InactivePacket());
1824    }
1825
1826    public void resetAttemptCount(boolean resetConnectTime) {
1827        this.attempt = 0;
1828        if (resetConnectTime) {
1829            this.lastConnect = 0;
1830        }
1831    }
1832
1833    public void setInteractive(boolean interactive) {
1834        this.mInteractive = interactive;
1835    }
1836
1837    public Identity getServerIdentity() {
1838        synchronized (this.disco) {
1839            ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1840            if (result == null) {
1841                return Identity.UNKNOWN;
1842            }
1843            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1844                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1845                    switch (id.getName()) {
1846                        case "Prosody":
1847                            return Identity.PROSODY;
1848                        case "ejabberd":
1849                            return Identity.EJABBERD;
1850                        case "Slack-XMPP":
1851                            return Identity.SLACK;
1852                    }
1853                }
1854            }
1855        }
1856        return Identity.UNKNOWN;
1857    }
1858
1859    private IqGenerator getIqGenerator() {
1860        return mXmppConnectionService.getIqGenerator();
1861    }
1862
1863    public enum Identity {
1864        FACEBOOK,
1865        SLACK,
1866        EJABBERD,
1867        PROSODY,
1868        NIMBUZZ,
1869        UNKNOWN
1870    }
1871
1872    private class MyKeyManager implements X509KeyManager {
1873        @Override
1874        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1875            return account.getPrivateKeyAlias();
1876        }
1877
1878        @Override
1879        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1880            return null;
1881        }
1882
1883        @Override
1884        public X509Certificate[] getCertificateChain(String alias) {
1885            Log.d(Config.LOGTAG, "getting certificate chain");
1886            try {
1887                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1888            } catch (final Exception e) {
1889                Log.d(Config.LOGTAG, "could not get certificate chain", e);
1890                return new X509Certificate[0];
1891            }
1892        }
1893
1894        @Override
1895        public String[] getClientAliases(String s, Principal[] principals) {
1896            final String alias = account.getPrivateKeyAlias();
1897            return alias != null ? new String[]{alias} : new String[0];
1898        }
1899
1900        @Override
1901        public String[] getServerAliases(String s, Principal[] principals) {
1902            return new String[0];
1903        }
1904
1905        @Override
1906        public PrivateKey getPrivateKey(String alias) {
1907            try {
1908                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1909            } catch (Exception e) {
1910                return null;
1911            }
1912        }
1913    }
1914
1915    private static class StateChangingError extends Error {
1916        private final Account.State state;
1917
1918        public StateChangingError(Account.State state) {
1919            this.state = state;
1920        }
1921    }
1922
1923    private static class StateChangingException extends IOException {
1924        private final Account.State state;
1925
1926        public StateChangingException(Account.State state) {
1927            this.state = state;
1928        }
1929    }
1930
1931    public class Features {
1932        XmppConnection connection;
1933        private boolean carbonsEnabled = false;
1934        private boolean encryptionEnabled = false;
1935        private boolean blockListRequested = false;
1936
1937        public Features(final XmppConnection connection) {
1938            this.connection = connection;
1939        }
1940
1941        private boolean hasDiscoFeature(final Jid server, final String feature) {
1942            synchronized (XmppConnection.this.disco) {
1943                return connection.disco.containsKey(server) &&
1944                        connection.disco.get(server).getFeatures().contains(feature);
1945            }
1946        }
1947
1948        public boolean carbons() {
1949            return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
1950        }
1951
1952        public boolean commands() {
1953            return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
1954        }
1955
1956        public boolean easyOnboardingInvites() {
1957            synchronized (commands) {
1958                return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
1959            }
1960        }
1961
1962        public boolean bookmarksConversion() {
1963            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1964        }
1965
1966        public boolean avatarConversion() {
1967            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1968        }
1969
1970        public boolean blocking() {
1971            return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
1972        }
1973
1974        public boolean spamReporting() {
1975            return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
1976        }
1977
1978        public boolean flexibleOfflineMessageRetrieval() {
1979            return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1980        }
1981
1982        public boolean register() {
1983            return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
1984        }
1985
1986        public boolean invite() {
1987            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1988        }
1989
1990        public boolean sm() {
1991            return streamId != null
1992                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1993        }
1994
1995        public boolean csi() {
1996            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1997        }
1998
1999        public boolean pep() {
2000            synchronized (XmppConnection.this.disco) {
2001                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2002                return info != null && info.hasIdentity("pubsub", "pep");
2003            }
2004        }
2005
2006        public boolean pepPersistent() {
2007            synchronized (XmppConnection.this.disco) {
2008                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2009                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
2010            }
2011        }
2012
2013        public boolean pepPublishOptions() {
2014            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2015        }
2016
2017        public boolean pepOmemoWhitelisted() {
2018            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2019        }
2020
2021        public boolean mam() {
2022            return MessageArchiveService.Version.has(getAccountFeatures());
2023        }
2024
2025        public List<String> getAccountFeatures() {
2026            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2027            return result == null ? Collections.emptyList() : result.getFeatures();
2028        }
2029
2030        public boolean push() {
2031            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2032                    || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2033        }
2034
2035        public boolean rosterVersioning() {
2036            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2037        }
2038
2039        public void setBlockListRequested(boolean value) {
2040            this.blockListRequested = value;
2041        }
2042
2043        public boolean httpUpload(long filesize) {
2044            if (Config.DISABLE_HTTP_UPLOAD) {
2045                return false;
2046            } else {
2047                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2048                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2049                    if (items.size() > 0) {
2050                        try {
2051                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2052                            if (filesize <= maxsize) {
2053                                return true;
2054                            } else {
2055                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
2056                                return false;
2057                            }
2058                        } catch (Exception e) {
2059                            return true;
2060                        }
2061                    }
2062                }
2063                return false;
2064            }
2065        }
2066
2067        public boolean useLegacyHttpUpload() {
2068            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2069        }
2070
2071        public long getMaxHttpUploadSize() {
2072            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2073                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2074                if (items.size() > 0) {
2075                    try {
2076                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2077                    } catch (Exception e) {
2078                        //ignored
2079                    }
2080                }
2081            }
2082            return -1;
2083        }
2084
2085        public boolean stanzaIds() {
2086            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2087        }
2088
2089        public boolean bookmarks2() {
2090            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2091        }
2092
2093        public boolean externalServiceDiscovery() {
2094            return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2095        }
2096    }
2097}