XmppConnection.java

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