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