XmppConnection.java

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