XmppConnection.java

   1package eu.siacs.conversations.xmpp;
   2
   3import android.content.Context;
   4import android.graphics.Bitmap;
   5import android.graphics.BitmapFactory;
   6import android.os.SystemClock;
   7import android.security.KeyChain;
   8import android.support.annotation.NonNull;
   9import android.util.Base64;
  10import android.util.Log;
  11import android.util.Pair;
  12import android.util.SparseArray;
  13
  14import org.xmlpull.v1.XmlPullParserException;
  15
  16import java.io.ByteArrayInputStream;
  17import java.io.IOException;
  18import java.io.InputStream;
  19import java.net.ConnectException;
  20import java.net.IDN;
  21import java.net.InetAddress;
  22import java.net.InetSocketAddress;
  23import java.net.MalformedURLException;
  24import java.net.Socket;
  25import java.net.URL;
  26import java.net.UnknownHostException;
  27import java.security.KeyManagementException;
  28import java.security.NoSuchAlgorithmException;
  29import java.security.Principal;
  30import java.security.PrivateKey;
  31import java.security.cert.X509Certificate;
  32import java.util.ArrayList;
  33import java.util.Arrays;
  34import java.util.Collections;
  35import java.util.HashMap;
  36import java.util.HashSet;
  37import java.util.Hashtable;
  38import java.util.Iterator;
  39import java.util.List;
  40import java.util.Map.Entry;
  41import java.util.Set;
  42import java.util.concurrent.CountDownLatch;
  43import java.util.concurrent.TimeUnit;
  44import java.util.concurrent.atomic.AtomicBoolean;
  45import java.util.concurrent.atomic.AtomicInteger;
  46import java.util.regex.Matcher;
  47
  48import javax.net.ssl.KeyManager;
  49import javax.net.ssl.SSLContext;
  50import javax.net.ssl.SSLSocket;
  51import javax.net.ssl.SSLSocketFactory;
  52import javax.net.ssl.X509KeyManager;
  53import javax.net.ssl.X509TrustManager;
  54
  55import eu.siacs.conversations.Config;
  56import eu.siacs.conversations.R;
  57import eu.siacs.conversations.crypto.DomainHostnameVerifier;
  58import eu.siacs.conversations.crypto.XmppDomainVerifier;
  59import eu.siacs.conversations.crypto.axolotl.AxolotlService;
  60import eu.siacs.conversations.crypto.sasl.Anonymous;
  61import eu.siacs.conversations.crypto.sasl.DigestMd5;
  62import eu.siacs.conversations.crypto.sasl.External;
  63import eu.siacs.conversations.crypto.sasl.Plain;
  64import eu.siacs.conversations.crypto.sasl.SaslMechanism;
  65import eu.siacs.conversations.crypto.sasl.ScramSha1;
  66import eu.siacs.conversations.crypto.sasl.ScramSha256;
  67import eu.siacs.conversations.entities.Account;
  68import eu.siacs.conversations.entities.Message;
  69import eu.siacs.conversations.entities.ServiceDiscoveryResult;
  70import eu.siacs.conversations.generator.IqGenerator;
  71import eu.siacs.conversations.persistance.FileBackend;
  72import eu.siacs.conversations.services.MemorizingTrustManager;
  73import eu.siacs.conversations.services.MessageArchiveService;
  74import eu.siacs.conversations.services.NotificationService;
  75import eu.siacs.conversations.services.XmppConnectionService;
  76import eu.siacs.conversations.utils.CryptoHelper;
  77import eu.siacs.conversations.utils.Patterns;
  78import eu.siacs.conversations.utils.Resolver;
  79import eu.siacs.conversations.utils.SSLSocketHelper;
  80import eu.siacs.conversations.utils.SocksSocketFactory;
  81import eu.siacs.conversations.utils.XmlHelper;
  82import eu.siacs.conversations.xml.Element;
  83import eu.siacs.conversations.xml.Namespace;
  84import eu.siacs.conversations.xml.Tag;
  85import eu.siacs.conversations.xml.TagWriter;
  86import eu.siacs.conversations.xml.XmlReader;
  87import eu.siacs.conversations.xmpp.forms.Data;
  88import eu.siacs.conversations.xmpp.forms.Field;
  89import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
  90import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
  91import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
  92import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
  93import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  94import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  95import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
  96import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
  97import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
  98import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
  99import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
 100import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
 101import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
 102import rocks.xmpp.addr.Jid;
 103
 104public class XmppConnection implements Runnable {
 105
 106    private static final int PACKET_IQ = 0;
 107    private static final int PACKET_MESSAGE = 1;
 108    private static final int PACKET_PRESENCE = 2;
 109    public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
 110        @Override
 111        public void onIqPacketReceived(Account account, IqPacket packet) {
 112            if (packet.getType() == IqPacket.TYPE.RESULT) {
 113                account.setOption(Account.OPTION_REGISTER, false);
 114                throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
 115            } else {
 116                final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
 117                        "The password is too weak",
 118                        "Please use a longer password.");
 119                Element error = packet.findChild("error");
 120                Account.State state = Account.State.REGISTRATION_FAILED;
 121                if (error != null) {
 122                    if (error.hasChild("conflict")) {
 123                        state = Account.State.REGISTRATION_CONFLICT;
 124                    } else if (error.hasChild("resource-constraint")
 125                            && "wait".equals(error.getAttribute("type"))) {
 126                        state = Account.State.REGISTRATION_PLEASE_WAIT;
 127                    } else if (error.hasChild("not-acceptable")
 128                            && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
 129                        state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
 130                    }
 131                }
 132                throw new StateChangingError(state);
 133            }
 134        }
 135    };
 136    protected final Account account;
 137    private final Features features = new Features(this);
 138    private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
 139    private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
 140    private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
 141    private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
 142    private final XmppConnectionService mXmppConnectionService;
 143    private Socket socket;
 144    private XmlReader tagReader;
 145    private TagWriter tagWriter = new TagWriter();
 146    private boolean shouldAuthenticate = true;
 147    private boolean inSmacksSession = false;
 148    private boolean isBound = false;
 149    private Element streamFeatures;
 150    private String streamId = null;
 151    private int smVersion = 3;
 152    private int stanzasReceived = 0;
 153    private int stanzasSent = 0;
 154    private long lastPacketReceived = 0;
 155    private long lastPingSent = 0;
 156    private long lastConnect = 0;
 157    private long lastSessionStarted = 0;
 158    private long lastDiscoStarted = 0;
 159    private boolean isMamPreferenceAlways = false;
 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() || account.isOnion()) {
 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                                FileBackend.close(localSocket);
 351                                throw new StateChangingException(Account.State.TLS_ERROR);
 352                            }
 353                        }
 354                        localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
 355                        if (startXmpp(localSocket)) {
 356                            localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
 357                            if (!hardcoded && !result.equals(storedBackupResult)) {
 358                                mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
 359                            }
 360                            break; // successfully connected to server that speaks xmpp
 361                        } else {
 362                            FileBackend.close(localSocket);
 363                            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 364                        }
 365                    } catch (final StateChangingException e) {
 366                        if (!iterator.hasNext()) {
 367                            throw e;
 368                        }
 369                    } catch (InterruptedException e) {
 370                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
 371                        return;
 372                    } catch (final Throwable e) {
 373                        Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
 374                        if (!iterator.hasNext()) {
 375                            throw new UnknownHostException();
 376                        }
 377                    }
 378                }
 379            }
 380            processStream();
 381        } catch (final SecurityException e) {
 382            this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
 383        } catch (final StateChangingException e) {
 384            this.changeStatus(e.state);
 385        } catch (final UnknownHostException | ConnectException e) {
 386            this.changeStatus(Account.State.SERVER_NOT_FOUND);
 387        } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
 388            this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
 389        } catch (final IOException | XmlPullParserException  e) {
 390            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
 391            this.changeStatus(Account.State.OFFLINE);
 392            this.attempt = Math.max(0, this.attempt - 1);
 393        } finally {
 394            if (!Thread.currentThread().isInterrupted()) {
 395                forceCloseSocket();
 396            } else {
 397                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
 398            }
 399        }
 400    }
 401
 402    /**
 403     * Starts xmpp protocol, call after connecting to socket
 404     *
 405     * @return true if server returns with valid xmpp, false otherwise
 406     */
 407    private boolean startXmpp(Socket socket) throws Exception {
 408        if (Thread.currentThread().isInterrupted()) {
 409            throw new InterruptedException();
 410        }
 411        this.socket = socket;
 412        tagReader = new XmlReader();
 413        if (tagWriter != null) {
 414            tagWriter.forceClose();
 415        }
 416        tagWriter = new TagWriter();
 417        tagWriter.setOutputStream(socket.getOutputStream());
 418        tagReader.setInputStream(socket.getInputStream());
 419        tagWriter.beginDocument();
 420        sendStartStream();
 421        final Tag tag = tagReader.readTag();
 422        if (Thread.currentThread().isInterrupted()) {
 423            throw new InterruptedException();
 424        }
 425        if (socket instanceof SSLSocket) {
 426            SSLSocketHelper.log(account, (SSLSocket) socket);
 427        }
 428        return tag != null && tag.isStart("stream");
 429    }
 430
 431    private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
 432        final SSLContext sc = SSLSocketHelper.getSSLContext();
 433        MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
 434        KeyManager[] keyManager;
 435        if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
 436            keyManager = new KeyManager[]{new MyKeyManager()};
 437        } else {
 438            keyManager = null;
 439        }
 440        String domain = account.getJid().getDomain();
 441        sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
 442        final SSLSocketFactory factory = sc.getSocketFactory();
 443        final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
 444        return new TlsFactoryVerifier(factory, verifier);
 445    }
 446
 447    @Override
 448    public void run() {
 449        synchronized (this) {
 450            this.mThread = Thread.currentThread();
 451            if (this.mThread.isInterrupted()) {
 452                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
 453                return;
 454            }
 455            forceCloseSocket();
 456        }
 457        connect();
 458    }
 459
 460    private void processStream() throws XmlPullParserException, IOException {
 461        final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
 462        this.mStreamCountDownLatch = streamCountDownLatch;
 463        Tag nextTag = tagReader.readTag();
 464        while (nextTag != null && !nextTag.isEnd("stream")) {
 465            if (nextTag.isStart("error")) {
 466                processStreamError(nextTag);
 467            } else if (nextTag.isStart("features")) {
 468                processStreamFeatures(nextTag);
 469            } else if (nextTag.isStart("proceed")) {
 470                switchOverToTls();
 471            } else if (nextTag.isStart("success")) {
 472                final String challenge = tagReader.readElement(nextTag).getContent();
 473                try {
 474                    saslMechanism.getResponse(challenge);
 475                } catch (final SaslMechanism.AuthenticationException e) {
 476                    Log.e(Config.LOGTAG, String.valueOf(e));
 477                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 478                }
 479                Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
 480                account.setKey(Account.PINNED_MECHANISM_KEY,
 481                        String.valueOf(saslMechanism.getPriority()));
 482                tagReader.reset();
 483                sendStartStream();
 484                final Tag tag = tagReader.readTag();
 485                if (tag != null && tag.isStart("stream")) {
 486                    processStream();
 487                } else {
 488                    throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 489                }
 490                break;
 491            } else if (nextTag.isStart("failure")) {
 492                final Element failure = tagReader.readElement(nextTag);
 493                if (Namespace.SASL.equals(failure.getNamespace())) {
 494                    final String text = failure.findChildContent("text");
 495                    if (failure.hasChild("account-disabled") && text != null) {
 496                        Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
 497                        if (matcher.find()) {
 498                            try {
 499                                URL url = new URL(text.substring(matcher.start(), matcher.end()));
 500                                if (url.getProtocol().equals("https")) {
 501                                    this.redirectionUrl = url;
 502                                    throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
 503                                }
 504                            } catch (MalformedURLException e) {
 505                                throw new StateChangingException(Account.State.UNAUTHORIZED);
 506                            }
 507                        }
 508                    }
 509                    throw new StateChangingException(Account.State.UNAUTHORIZED);
 510                } else if (Namespace.TLS.equals(failure.getNamespace())) {
 511                    throw new StateChangingException(Account.State.TLS_ERROR);
 512                } else {
 513                    throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 514                }
 515            } else if (nextTag.isStart("challenge")) {
 516                final String challenge = tagReader.readElement(nextTag).getContent();
 517                final Element response = new Element("response", Namespace.SASL);
 518                try {
 519                    response.setContent(saslMechanism.getResponse(challenge));
 520                } catch (final SaslMechanism.AuthenticationException e) {
 521                    // TODO: Send auth abort tag.
 522                    Log.e(Config.LOGTAG, e.toString());
 523                }
 524                tagWriter.writeElement(response);
 525            } else if (nextTag.isStart("enabled")) {
 526                final Element enabled = tagReader.readElement(nextTag);
 527                if ("true".equals(enabled.getAttribute("resume"))) {
 528                    this.streamId = enabled.getAttribute("id");
 529                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 530                            + ": stream management(" + smVersion
 531                            + ") enabled (resumable)");
 532                } else {
 533                    Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 534                            + ": stream management(" + smVersion + ") enabled");
 535                }
 536                this.stanzasReceived = 0;
 537                this.inSmacksSession = true;
 538                final RequestPacket r = new RequestPacket(smVersion);
 539                tagWriter.writeStanzaAsync(r);
 540            } else if (nextTag.isStart("resumed")) {
 541                this.inSmacksSession = true;
 542                this.isBound = true;
 543                this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
 544                lastPacketReceived = SystemClock.elapsedRealtime();
 545                final Element resumed = tagReader.readElement(nextTag);
 546                final String h = resumed.getAttribute("h");
 547                try {
 548                    ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
 549                    final boolean acknowledgedMessages;
 550                    synchronized (this.mStanzaQueue) {
 551                        final int serverCount = Integer.parseInt(h);
 552                        if (serverCount < stanzasSent) {
 553                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
 554                                    + ": session resumed with lost packages");
 555                            stanzasSent = serverCount;
 556                        } else {
 557                            Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
 558                        }
 559                        acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
 560                        for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
 561                            failedStanzas.add(mStanzaQueue.valueAt(i));
 562                        }
 563                        mStanzaQueue.clear();
 564                    }
 565                    if (acknowledgedMessages) {
 566                        mXmppConnectionService.updateConversationUi();
 567                    }
 568                    Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
 569                    for (AbstractAcknowledgeableStanza packet : failedStanzas) {
 570                        if (packet instanceof MessagePacket) {
 571                            MessagePacket message = (MessagePacket) packet;
 572                            mXmppConnectionService.markMessage(account,
 573                                    message.getTo().asBareJid(),
 574                                    message.getId(),
 575                                    Message.STATUS_UNSEND);
 576                        }
 577                        sendPacket(packet);
 578                    }
 579                } catch (final NumberFormatException ignored) {
 580                }
 581                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
 582                changeStatus(Account.State.ONLINE);
 583            } else if (nextTag.isStart("r")) {
 584                tagReader.readElement(nextTag);
 585                if (Config.EXTENDED_SM_LOGGING) {
 586                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
 587                }
 588                final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
 589                tagWriter.writeStanzaAsync(ack);
 590            } else if (nextTag.isStart("a")) {
 591                boolean accountUiNeedsRefresh = false;
 592                synchronized (NotificationService.CATCHUP_LOCK) {
 593                    if (mWaitingForSmCatchup.compareAndSet(true, false)) {
 594                        final int messageCount = mSmCatchupMessageCounter.get();
 595                        final int pendingIQs = packetCallbacks.size();
 596                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (messages=" + messageCount + ", pending IQs="+pendingIQs+")");
 597                        accountUiNeedsRefresh = true;
 598                        if (messageCount > 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 || account.isOnion();
 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                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find STARTTLS for registration process "+ XmlHelper.printElementNames(this.streamFeatures));
 852                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 853            }
 854        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 855            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 856        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 857            authenticate();
 858        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 859            if (Config.EXTENDED_SM_LOGGING) {
 860                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 861            }
 862            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 863            this.mSmCatchupMessageCounter.set(0);
 864            this.mWaitingForSmCatchup.set(true);
 865            this.tagWriter.writeStanzaAsync(resume);
 866        } else if (needsBinding) {
 867            if (this.streamFeatures.hasChild("bind") && isSecure) {
 868                sendBindRequest();
 869            } else {
 870                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find bind feature "+ XmlHelper.printElementNames(this.streamFeatures));
 871                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 872            }
 873        }
 874    }
 875
 876    private void authenticate() throws IOException {
 877        final List<String> mechanisms = extractMechanisms(streamFeatures
 878                .findChild("mechanisms"));
 879        final Element auth = new Element("auth", Namespace.SASL);
 880        if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 881            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 882        } else if (mechanisms.contains("SCRAM-SHA-256")) {
 883            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 884        } else if (mechanisms.contains("SCRAM-SHA-1")) {
 885            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 886        } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
 887            saslMechanism = new Plain(tagWriter, account);
 888        } else if (mechanisms.contains("DIGEST-MD5")) {
 889            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 890        } else if (mechanisms.contains("ANONYMOUS")) {
 891            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 892        }
 893        if (saslMechanism != null) {
 894            final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 895            if (pinnedMechanism > saslMechanism.getPriority()) {
 896                Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 897                        " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 898                        ") than pinned priority (" + pinnedMechanism +
 899                        "). Possible downgrade attack?");
 900                throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 901            }
 902            Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 903            auth.setAttribute("mechanism", saslMechanism.getMechanism());
 904            if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 905                auth.setContent(saslMechanism.getClientFirstMessage());
 906            }
 907            tagWriter.writeElement(auth);
 908        } else {
 909            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find SASL mechanism "+ saslMechanism.toString());
 910            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 911        }
 912    }
 913
 914    private List<String> extractMechanisms(final Element stream) {
 915        final ArrayList<String> mechanisms = new ArrayList<>(stream
 916                .getChildren().size());
 917        for (final Element child : stream.getChildren()) {
 918            mechanisms.add(child.getContent());
 919        }
 920        return mechanisms;
 921    }
 922
 923    private void sendRegistryRequest() {
 924        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 925        register.query(Namespace.REGISTER);
 926        register.setTo(Jid.of(account.getServer()));
 927        sendUnmodifiedIqPacket(register, (account, packet) -> {
 928            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 929                return;
 930            }
 931            if (packet.getType() == IqPacket.TYPE.ERROR) {
 932                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 933            }
 934            final Element query = packet.query(Namespace.REGISTER);
 935            if (query.hasChild("username") && (query.hasChild("password"))) {
 936                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 937                final Element username = new Element("username").setContent(account.getUsername());
 938                final Element password = new Element("password").setContent(account.getPassword());
 939                register1.query(Namespace.REGISTER).addChild(username);
 940                register1.query().addChild(password);
 941                register1.setFrom(account.getJid().asBareJid());
 942                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 943            } else if (query.hasChild("x", Namespace.DATA)) {
 944                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 945                final Element blob = query.findChild("data", "urn:xmpp:bob");
 946                final String id = packet.getId();
 947                InputStream is;
 948                if (blob != null) {
 949                    try {
 950                        final String base64Blob = blob.getContent();
 951                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 952                        is = new ByteArrayInputStream(strBlob);
 953                    } catch (Exception e) {
 954                        is = null;
 955                    }
 956                } else {
 957                    try {
 958                        Field field = data.getFieldByName("url");
 959                        URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
 960                        is = url != null ? url.openStream() : null;
 961                    } catch (IOException e) {
 962                        is = null;
 963                    }
 964                }
 965
 966                if (is != null) {
 967                    Bitmap captcha = BitmapFactory.decodeStream(is);
 968                    try {
 969                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
 970                            return;
 971                        }
 972                    } catch (Exception e) {
 973                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 974                    }
 975                }
 976                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 977            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
 978                final String instructions = query.findChildContent("instructions");
 979                final Element oob = query.findChild("x", Namespace.OOB);
 980                final String url = oob == null ? null : oob.findChildContent("url");
 981                if (url != null) {
 982                    setAccountCreationFailed(url);
 983                } else if (instructions != null) {
 984                    Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
 985                    if (matcher.find()) {
 986                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
 987                    }
 988                }
 989                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 990            }
 991        }, true);
 992    }
 993
 994    private void setAccountCreationFailed(String url) {
 995        if (url != null) {
 996            try {
 997                this.redirectionUrl = new URL(url);
 998                if (this.redirectionUrl.getProtocol().equals("https")) {
 999                    throw new StateChangingError(Account.State.REGISTRATION_WEB);
1000                }
1001            } catch (MalformedURLException e) {
1002                //fall through
1003            }
1004        }
1005        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1006    }
1007
1008    public URL getRedirectionUrl() {
1009        return this.redirectionUrl;
1010    }
1011
1012    public void resetEverything() {
1013        resetAttemptCount(true);
1014        resetStreamId();
1015        clearIqCallbacks();
1016        this.stanzasSent = 0;
1017        mStanzaQueue.clear();
1018        this.redirectionUrl = null;
1019        synchronized (this.disco) {
1020            disco.clear();
1021        }
1022    }
1023
1024    private void sendBindRequest() {
1025        try {
1026            mXmppConnectionService.restoredFromDatabaseLatch.await();
1027        } catch (InterruptedException e) {
1028            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1029            return;
1030        }
1031        clearIqCallbacks();
1032        if (account.getJid().isBareJid()) {
1033            account.setResource(this.createNewResource());
1034        } else {
1035            fixResource(mXmppConnectionService, account);
1036        }
1037        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1038        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1039        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1040        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1041            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1042                return;
1043            }
1044            final Element bind = packet.findChild("bind");
1045            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1046                isBound = true;
1047                final Element jid = bind.findChild("jid");
1048                if (jid != null && jid.getContent() != null) {
1049                    try {
1050                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1051                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1052                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1053                            throw new StateChangingError(Account.State.BIND_FAILURE);
1054                        }
1055                        if (account.setJid(assignedJid)) {
1056                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1057                            mXmppConnectionService.databaseBackend.updateAccount(account);
1058                        }
1059                        if (streamFeatures.hasChild("session")
1060                                && !streamFeatures.findChild("session").hasChild("optional")) {
1061                            sendStartSession();
1062                        } else {
1063                            sendPostBindInitialization();
1064                        }
1065                        return;
1066                    } catch (final IllegalArgumentException e) {
1067                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1068                    }
1069                } else {
1070                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1071                }
1072            } else {
1073                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1074            }
1075            final Element error = packet.findChild("error");
1076            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1077                account.setResource(createNewResource());
1078            }
1079            throw new StateChangingError(Account.State.BIND_FAILURE);
1080        }, true);
1081    }
1082
1083    private void clearIqCallbacks() {
1084        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1085        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1086        synchronized (this.packetCallbacks) {
1087            if (this.packetCallbacks.size() == 0) {
1088                return;
1089            }
1090            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1091            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1092            while (iterator.hasNext()) {
1093                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1094                callbacks.add(entry.second);
1095                iterator.remove();
1096            }
1097        }
1098        for (OnIqPacketReceived callback : callbacks) {
1099            try {
1100                callback.onIqPacketReceived(account, failurePacket);
1101            } catch (StateChangingError error) {
1102                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1103                //ignore
1104            }
1105        }
1106        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1107    }
1108
1109    public void sendDiscoTimeout() {
1110        if (mWaitForDisco.compareAndSet(true, false)) {
1111            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1112            finalizeBind();
1113        }
1114    }
1115
1116    private void sendStartSession() {
1117        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1118        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1119        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1120        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1121            if (packet.getType() == IqPacket.TYPE.RESULT) {
1122                sendPostBindInitialization();
1123            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1124                throw new StateChangingError(Account.State.SESSION_FAILURE);
1125            }
1126        }, true);
1127    }
1128
1129    private void sendPostBindInitialization() {
1130        smVersion = 0;
1131        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1132            smVersion = 3;
1133        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1134            smVersion = 2;
1135        }
1136        if (smVersion != 0) {
1137            synchronized (this.mStanzaQueue) {
1138                final EnablePacket enable = new EnablePacket(smVersion);
1139                tagWriter.writeStanzaAsync(enable);
1140                stanzasSent = 0;
1141                mStanzaQueue.clear();
1142            }
1143        }
1144        features.carbonsEnabled = false;
1145        features.blockListRequested = false;
1146        synchronized (this.disco) {
1147            this.disco.clear();
1148        }
1149        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1150        mPendingServiceDiscoveries.set(0);
1151        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
1152            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1153            mWaitForDisco.set(false);
1154        } else {
1155            mWaitForDisco.set(true);
1156        }
1157        lastDiscoStarted = SystemClock.elapsedRealtime();
1158        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1159        Element caps = streamFeatures.findChild("c");
1160        final String hash = caps == null ? null : caps.getAttribute("hash");
1161        final String ver = caps == null ? null : caps.getAttribute("ver");
1162        ServiceDiscoveryResult discoveryResult = null;
1163        if (hash != null && ver != null) {
1164            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1165        }
1166        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1167        if (requestDiscoItemsFirst) {
1168            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1169        }
1170        if (discoveryResult == null) {
1171            sendServiceDiscoveryInfo(Jid.of(account.getServer()));
1172        } else {
1173            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1174            disco.put(Jid.of(account.getServer()), discoveryResult);
1175        }
1176        discoverMamPreferences();
1177        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1178        if (!requestDiscoItemsFirst) {
1179            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1180        }
1181
1182        if (!mWaitForDisco.get()) {
1183            finalizeBind();
1184        }
1185        this.lastSessionStarted = SystemClock.elapsedRealtime();
1186    }
1187
1188    private void sendServiceDiscoveryInfo(final Jid jid) {
1189        mPendingServiceDiscoveries.incrementAndGet();
1190        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1191        iq.setTo(jid);
1192        iq.query("http://jabber.org/protocol/disco#info");
1193        this.sendIqPacket(iq, (account, packet) -> {
1194            if (packet.getType() == IqPacket.TYPE.RESULT) {
1195                boolean advancedStreamFeaturesLoaded;
1196                synchronized (XmppConnection.this.disco) {
1197                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1198                    if (jid.equals(Jid.of(account.getServer()))) {
1199                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1200                    }
1201                    disco.put(jid, result);
1202                    advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
1203                            && disco.containsKey(account.getJid().asBareJid());
1204                }
1205                if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
1206                    enableAdvancedStreamFeatures();
1207                }
1208            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1209                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1210                final boolean serverOrAccount = jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid());
1211                final boolean advancedStreamFeaturesLoaded;
1212                if (serverOrAccount) {
1213                    synchronized (XmppConnection.this.disco) {
1214                        disco.put(jid, ServiceDiscoveryResult.empty());
1215                        advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer())) && disco.containsKey(account.getJid().asBareJid());
1216                    }
1217                } else {
1218                    advancedStreamFeaturesLoaded = false;
1219                }
1220                if (advancedStreamFeaturesLoaded) {
1221                    enableAdvancedStreamFeatures();
1222                }
1223            }
1224            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1225                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1226                        && mWaitForDisco.compareAndSet(true, false)) {
1227                    finalizeBind();
1228                }
1229            }
1230        });
1231    }
1232
1233    private void discoverMamPreferences() {
1234        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1235        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1236        sendIqPacket(request, (account, response) -> {
1237           if (response.getType() == IqPacket.TYPE.RESULT) {
1238               Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1239               isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1240           }
1241        });
1242    }
1243
1244    public boolean isMamPreferenceAlways() {
1245        return isMamPreferenceAlways;
1246    }
1247
1248    private void finalizeBind() {
1249        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1250        if (bindListener != null) {
1251            bindListener.onBind(account);
1252        }
1253        changeStatus(Account.State.ONLINE);
1254    }
1255
1256    private void enableAdvancedStreamFeatures() {
1257        if (getFeatures().carbons() && !features.carbonsEnabled) {
1258            sendEnableCarbons();
1259        }
1260        if (getFeatures().blocking() && !features.blockListRequested) {
1261            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1262            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1263        }
1264        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1265            listener.onAdvancedStreamFeaturesAvailable(account);
1266        }
1267    }
1268
1269    private void sendServiceDiscoveryItems(final Jid server) {
1270        mPendingServiceDiscoveries.incrementAndGet();
1271        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1272        iq.setTo(Jid.ofDomain(server.getDomain()));
1273        iq.query("http://jabber.org/protocol/disco#items");
1274        this.sendIqPacket(iq, (account, packet) -> {
1275            if (packet.getType() == IqPacket.TYPE.RESULT) {
1276                HashSet<Jid> items = new HashSet<Jid>();
1277                final List<Element> elements = packet.query().getChildren();
1278                for (final Element element : elements) {
1279                    if (element.getName().equals("item")) {
1280                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1281                        if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
1282                            items.add(jid);
1283                        }
1284                    }
1285                }
1286                for (Jid jid : items) {
1287                    sendServiceDiscoveryInfo(jid);
1288                }
1289            } else {
1290                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1291            }
1292            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1293                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1294                        && mWaitForDisco.compareAndSet(true, false)) {
1295                    finalizeBind();
1296                }
1297            }
1298        });
1299    }
1300
1301    private void sendEnableCarbons() {
1302        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1303        iq.addChild("enable", "urn:xmpp:carbons:2");
1304        this.sendIqPacket(iq, new OnIqPacketReceived() {
1305
1306            @Override
1307            public void onIqPacketReceived(final Account account, final IqPacket packet) {
1308                if (!packet.hasChild("error")) {
1309                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1310                            + ": successfully enabled carbons");
1311                    features.carbonsEnabled = true;
1312                } else {
1313                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1314                            + ": error enableing carbons " + packet.toString());
1315                }
1316            }
1317        });
1318    }
1319
1320    private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1321        final Element streamError = tagReader.readElement(currentTag);
1322        if (streamError == null) {
1323            return;
1324        }
1325        if (streamError.hasChild("conflict")) {
1326            account.setResource(createNewResource());
1327            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1328            throw new IOException();
1329        } else if (streamError.hasChild("host-unknown")) {
1330            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1331        } else if (streamError.hasChild("policy-violation")) { ;
1332            final String text = streamError.findChildContent("text");
1333            if (text != null) {
1334                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": policy violation. "+text);
1335            }
1336            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1337        } else {
1338            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1339            throw new StateChangingException(Account.State.STREAM_ERROR);
1340        }
1341    }
1342
1343    private void sendStartStream() throws IOException {
1344        final Tag stream = Tag.start("stream:stream");
1345        stream.setAttribute("to", account.getServer());
1346        stream.setAttribute("version", "1.0");
1347        stream.setAttribute("xml:lang", "en");
1348        stream.setAttribute("xmlns", "jabber:client");
1349        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1350        tagWriter.writeTag(stream);
1351    }
1352
1353    private String createNewResource() {
1354        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1355    }
1356
1357    private String nextRandomId() {
1358        return nextRandomId(false);
1359    }
1360
1361    private String nextRandomId(boolean s) {
1362        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1363    }
1364
1365    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1366        packet.setFrom(account.getJid());
1367        return this.sendUnmodifiedIqPacket(packet, callback, false);
1368    }
1369
1370    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1371        if (packet.getId() == null) {
1372            packet.setAttribute("id", nextRandomId());
1373        }
1374        if (callback != null) {
1375            synchronized (this.packetCallbacks) {
1376                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1377            }
1378        }
1379        this.sendPacket(packet, force);
1380        return packet.getId();
1381    }
1382
1383    public void sendMessagePacket(final MessagePacket packet) {
1384        this.sendPacket(packet);
1385    }
1386
1387    public void sendPresencePacket(final PresencePacket packet) {
1388        this.sendPacket(packet);
1389    }
1390
1391    private synchronized void sendPacket(final AbstractStanza packet) {
1392        sendPacket(packet, false);
1393    }
1394
1395    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1396        if (stanzasSent == Integer.MAX_VALUE) {
1397            resetStreamId();
1398            disconnect(true);
1399            return;
1400        }
1401        synchronized (this.mStanzaQueue) {
1402            if (force || isBound) {
1403                tagWriter.writeStanzaAsync(packet);
1404            } else {
1405                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1406            }
1407            if (packet instanceof AbstractAcknowledgeableStanza) {
1408                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1409
1410                if (this.mStanzaQueue.size() != 0) {
1411                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1412                    if (currentHighestKey != stanzasSent) {
1413                        throw new AssertionError("Stanza count messed up");
1414                    }
1415                }
1416
1417                ++stanzasSent;
1418                this.mStanzaQueue.append(stanzasSent, stanza);
1419                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1420                    if (Config.EXTENDED_SM_LOGGING) {
1421                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1422                    }
1423                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1424                }
1425            }
1426        }
1427    }
1428
1429    public void sendPing() {
1430        if (!r()) {
1431            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1432            iq.setFrom(account.getJid());
1433            iq.addChild("ping", Namespace.PING);
1434            this.sendIqPacket(iq, null);
1435        }
1436        this.lastPingSent = SystemClock.elapsedRealtime();
1437    }
1438
1439    public void setOnMessagePacketReceivedListener(
1440            final OnMessagePacketReceived listener) {
1441        this.messageListener = listener;
1442    }
1443
1444    public void setOnUnregisteredIqPacketReceivedListener(
1445            final OnIqPacketReceived listener) {
1446        this.unregisteredIqListener = listener;
1447    }
1448
1449    public void setOnPresencePacketReceivedListener(
1450            final OnPresencePacketReceived listener) {
1451        this.presenceListener = listener;
1452    }
1453
1454    public void setOnJinglePacketReceivedListener(
1455            final OnJinglePacketReceived listener) {
1456        this.jingleListener = listener;
1457    }
1458
1459    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1460        this.statusListener = listener;
1461    }
1462
1463    public void setOnBindListener(final OnBindListener listener) {
1464        this.bindListener = listener;
1465    }
1466
1467    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1468        this.acknowledgedListener = listener;
1469    }
1470
1471    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1472        this.advancedStreamFeaturesLoadedListeners.add(listener);
1473    }
1474
1475    private void forceCloseSocket() {
1476        FileBackend.close(this.socket);
1477        FileBackend.close(this.tagReader);
1478    }
1479
1480    public void interrupt() {
1481        if (this.mThread != null) {
1482            this.mThread.interrupt();
1483        }
1484    }
1485
1486    public void disconnect(final boolean force) {
1487        interrupt();
1488        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1489        if (force) {
1490            forceCloseSocket();
1491        } else {
1492            final TagWriter currentTagWriter = this.tagWriter;
1493            if (currentTagWriter.isActive()) {
1494                currentTagWriter.finish();
1495                final Socket currentSocket = this.socket;
1496                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1497                try {
1498                    currentTagWriter.await(1, TimeUnit.SECONDS);
1499                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1500                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1501                    if (streamCountDownLatch != null) {
1502                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1503                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1504                        } else {
1505                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1506                        }
1507                    }
1508                } catch (InterruptedException e) {
1509                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1510                } catch (final IOException e) {
1511                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1512                } finally {
1513                    FileBackend.close(currentSocket);
1514                }
1515            } else {
1516                forceCloseSocket();
1517            }
1518        }
1519    }
1520
1521    private void resetStreamId() {
1522        this.streamId = null;
1523    }
1524
1525    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1526        synchronized (this.disco) {
1527            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1528            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1529                if (cursor.getValue().getFeatures().contains(feature)) {
1530                    items.add(cursor);
1531                }
1532            }
1533            return items;
1534        }
1535    }
1536
1537    public Jid findDiscoItemByFeature(final String feature) {
1538        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1539        if (items.size() >= 1) {
1540            return items.get(0).getKey();
1541        }
1542        return null;
1543    }
1544
1545    public boolean r() {
1546        if (getFeatures().sm()) {
1547            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1548            return true;
1549        } else {
1550            return false;
1551        }
1552    }
1553
1554    public List<String> getMucServersWithholdAccount() {
1555        List<String> servers = getMucServers();
1556        servers.remove(account.getServer());
1557        return servers;
1558    }
1559
1560    public List<String> getMucServers() {
1561        List<String> servers = new ArrayList<>();
1562        synchronized (this.disco) {
1563            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1564                final ServiceDiscoveryResult value = cursor.getValue();
1565                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1566                        && value.hasIdentity("conference", "text")
1567                        && !value.getFeatures().contains("jabber:iq:gateway")
1568                        && !value.hasIdentity("conference", "irc")) {
1569                    servers.add(cursor.getKey().toString());
1570                }
1571            }
1572        }
1573        return servers;
1574    }
1575
1576    public String getMucServer() {
1577        List<String> servers = getMucServers();
1578        return servers.size() > 0 ? servers.get(0) : null;
1579    }
1580
1581    public int getTimeToNextAttempt() {
1582        final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1583        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1584        return interval - secondsSinceLast;
1585    }
1586
1587    public int getAttempt() {
1588        return this.attempt;
1589    }
1590
1591    public Features getFeatures() {
1592        return this.features;
1593    }
1594
1595    public long getLastSessionEstablished() {
1596        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1597        return System.currentTimeMillis() - diff;
1598    }
1599
1600    public long getLastConnect() {
1601        return this.lastConnect;
1602    }
1603
1604    public long getLastPingSent() {
1605        return this.lastPingSent;
1606    }
1607
1608    public long getLastDiscoStarted() {
1609        return this.lastDiscoStarted;
1610    }
1611
1612    public long getLastPacketReceived() {
1613        return this.lastPacketReceived;
1614    }
1615
1616    public void sendActive() {
1617        this.sendPacket(new ActivePacket());
1618    }
1619
1620    public void sendInactive() {
1621        this.sendPacket(new InactivePacket());
1622    }
1623
1624    public void resetAttemptCount(boolean resetConnectTime) {
1625        this.attempt = 0;
1626        if (resetConnectTime) {
1627            this.lastConnect = 0;
1628        }
1629    }
1630
1631    public void setInteractive(boolean interactive) {
1632        this.mInteractive = interactive;
1633    }
1634
1635    public Identity getServerIdentity() {
1636        synchronized (this.disco) {
1637            ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
1638            if (result == null) {
1639                return Identity.UNKNOWN;
1640            }
1641            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1642                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1643                    switch (id.getName()) {
1644                        case "Prosody":
1645                            return Identity.PROSODY;
1646                        case "ejabberd":
1647                            return Identity.EJABBERD;
1648                        case "Slack-XMPP":
1649                            return Identity.SLACK;
1650                    }
1651                }
1652            }
1653        }
1654        return Identity.UNKNOWN;
1655    }
1656
1657    private IqGenerator getIqGenerator() {
1658        return mXmppConnectionService.getIqGenerator();
1659    }
1660
1661    public enum Identity {
1662        FACEBOOK,
1663        SLACK,
1664        EJABBERD,
1665        PROSODY,
1666        NIMBUZZ,
1667        UNKNOWN
1668    }
1669
1670    private static class TlsFactoryVerifier {
1671        private final SSLSocketFactory factory;
1672        private final DomainHostnameVerifier verifier;
1673
1674        TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1675            this.factory = factory;
1676            this.verifier = verifier;
1677            if (factory == null || verifier == null) {
1678                throw new IOException("could not setup ssl");
1679            }
1680        }
1681    }
1682
1683    private class MyKeyManager implements X509KeyManager {
1684        @Override
1685        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1686            return account.getPrivateKeyAlias();
1687        }
1688
1689        @Override
1690        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1691            return null;
1692        }
1693
1694        @Override
1695        public X509Certificate[] getCertificateChain(String alias) {
1696            Log.d(Config.LOGTAG, "getting certificate chain");
1697            try {
1698                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1699            } catch (Exception e) {
1700                Log.d(Config.LOGTAG, e.getMessage());
1701                return new X509Certificate[0];
1702            }
1703        }
1704
1705        @Override
1706        public String[] getClientAliases(String s, Principal[] principals) {
1707            final String alias = account.getPrivateKeyAlias();
1708            return alias != null ? new String[]{alias} : new String[0];
1709        }
1710
1711        @Override
1712        public String[] getServerAliases(String s, Principal[] principals) {
1713            return new String[0];
1714        }
1715
1716        @Override
1717        public PrivateKey getPrivateKey(String alias) {
1718            try {
1719                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1720            } catch (Exception e) {
1721                return null;
1722            }
1723        }
1724    }
1725
1726    private class StateChangingError extends Error {
1727        private final Account.State state;
1728
1729        public StateChangingError(Account.State state) {
1730            this.state = state;
1731        }
1732    }
1733
1734    private class StateChangingException extends IOException {
1735        private final Account.State state;
1736
1737        public StateChangingException(Account.State state) {
1738            this.state = state;
1739        }
1740    }
1741
1742    public class Features {
1743        XmppConnection connection;
1744        private boolean carbonsEnabled = false;
1745        private boolean encryptionEnabled = false;
1746        private boolean blockListRequested = false;
1747
1748        public Features(final XmppConnection connection) {
1749            this.connection = connection;
1750        }
1751
1752        private boolean hasDiscoFeature(final Jid server, final String feature) {
1753            synchronized (XmppConnection.this.disco) {
1754                return connection.disco.containsKey(server) &&
1755                        connection.disco.get(server).getFeatures().contains(feature);
1756            }
1757        }
1758
1759        public boolean carbons() {
1760            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
1761        }
1762
1763        public boolean bookmarksConversion() {
1764            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1765        }
1766
1767        public boolean avatarConversion() {
1768            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1769        }
1770
1771        public boolean blocking() {
1772            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
1773        }
1774
1775        public boolean spamReporting() {
1776            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
1777        }
1778
1779        public boolean flexibleOfflineMessageRetrieval() {
1780            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1781        }
1782
1783        public boolean register() {
1784            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
1785        }
1786
1787        public boolean sm() {
1788            return streamId != null
1789                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1790        }
1791
1792        public boolean csi() {
1793            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1794        }
1795
1796        public boolean pep() {
1797            synchronized (XmppConnection.this.disco) {
1798                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1799                return info != null && info.hasIdentity("pubsub", "pep");
1800            }
1801        }
1802
1803        public boolean pepPersistent() {
1804            synchronized (XmppConnection.this.disco) {
1805                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1806                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1807            }
1808        }
1809
1810        public boolean pepPublishOptions() {
1811            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1812        }
1813
1814        public boolean pepOmemoWhitelisted() {
1815            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1816        }
1817
1818        public boolean mam() {
1819            return MessageArchiveService.Version.has(getAccountFeatures());
1820        }
1821
1822        public List<String> getAccountFeatures() {
1823            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1824            return result == null ? Collections.emptyList() : result.getFeatures();
1825        }
1826
1827        public boolean push() {
1828            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1829                    || hasDiscoFeature(Jid.of(account.getServer()), Namespace.PUSH);
1830        }
1831
1832        public boolean rosterVersioning() {
1833            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1834        }
1835
1836        public void setBlockListRequested(boolean value) {
1837            this.blockListRequested = value;
1838        }
1839
1840        public boolean p1S3FileTransfer() {
1841            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.P1_S3_FILE_TRANSFER);
1842        }
1843
1844        public boolean httpUpload(long filesize) {
1845            if (Config.DISABLE_HTTP_UPLOAD) {
1846                return false;
1847            } else {
1848                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1849                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1850                    if (items.size() > 0) {
1851                        try {
1852                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1853                            if (filesize <= maxsize) {
1854                                return true;
1855                            } else {
1856                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1857                                return false;
1858                            }
1859                        } catch (Exception e) {
1860                            return true;
1861                        }
1862                    }
1863                }
1864                return false;
1865            }
1866        }
1867
1868        public boolean useLegacyHttpUpload() {
1869            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1870        }
1871
1872        public long getMaxHttpUploadSize() {
1873            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1874                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1875                if (items.size() > 0) {
1876                    try {
1877                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1878                    } catch (Exception e) {
1879                        //ignored
1880                    }
1881                }
1882            }
1883            return -1;
1884        }
1885
1886        public boolean stanzaIds() {
1887            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1888        }
1889    }
1890}