XmppConnection.java

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