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 IOException {
 673        final 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                element.addChild(tagReader.readElement(nextTag));
 695            }
 696            nextTag = tagReader.readTag();
 697            if (nextTag == null) {
 698                throw new IOException("interrupted mid tag");
 699            }
 700        }
 701        if (stanzasReceived == Integer.MAX_VALUE) {
 702            resetStreamId();
 703            throw new IOException("time to restart the session. cant handle >2 billion pcks");
 704        }
 705        if (inSmacksSession) {
 706            ++stanzasReceived;
 707        } else if (features.sm()) {
 708            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
 709        }
 710        lastPacketReceived = SystemClock.elapsedRealtime();
 711        if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
 712            Log.d(Config.LOGTAG, "[background stanza] " + element);
 713        }
 714        if (element instanceof IqPacket && element.hasChild("jingle", Namespace.JINGLE)) {
 715            return JinglePacket.upgrade((IqPacket) element);
 716        } else {
 717            return element;
 718        }
 719    }
 720
 721    private void processIq(final Tag currentTag) throws IOException {
 722        final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
 723        if (!packet.valid()) {
 724            Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 725            return;
 726        }
 727        if (packet instanceof JinglePacket) {
 728            if (this.jingleListener != null) {
 729                this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
 730            }
 731        } else {
 732            OnIqPacketReceived callback = null;
 733            synchronized (this.packetCallbacks) {
 734                final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
 735                if (packetCallbackDuple != null) {
 736                    // Packets to the server should have responses from the server
 737                    if (packetCallbackDuple.first.toServer(account)) {
 738                        if (packet.fromServer(account)) {
 739                            callback = packetCallbackDuple.second;
 740                            packetCallbacks.remove(packet.getId());
 741                        } else {
 742                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 743                        }
 744                    } else {
 745                        if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
 746                            callback = packetCallbackDuple.second;
 747                            packetCallbacks.remove(packet.getId());
 748                        } else {
 749                            Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
 750                        }
 751                    }
 752                } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
 753                    callback = this.unregisteredIqListener;
 754                }
 755            }
 756            if (callback != null) {
 757                try {
 758                    callback.onIqPacketReceived(account, packet);
 759                } catch (StateChangingError error) {
 760                    throw new StateChangingException(error.state);
 761                }
 762            }
 763        }
 764    }
 765
 766    private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
 767        final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
 768        if (!packet.valid()) {
 769            Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 770            return;
 771        }
 772        this.messageListener.onMessagePacketReceived(account, packet);
 773    }
 774
 775    private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
 776        PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
 777        if (!packet.valid()) {
 778            Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
 779            return;
 780        }
 781        this.presenceListener.onPresencePacketReceived(account, packet);
 782    }
 783
 784    private void sendStartTLS() throws IOException {
 785        final Tag startTLS = Tag.empty("starttls");
 786        startTLS.setAttribute("xmlns", Namespace.TLS);
 787        tagWriter.writeTag(startTLS);
 788    }
 789
 790    private void switchOverToTls() throws XmlPullParserException, IOException {
 791        tagReader.readTag();
 792        final Socket socket = this.socket;
 793        final SSLSocket sslSocket = upgradeSocketToTls(socket);
 794        tagReader.setInputStream(sslSocket.getInputStream());
 795        tagWriter.setOutputStream(sslSocket.getOutputStream());
 796        sendStartStream();
 797        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
 798        features.encryptionEnabled = true;
 799        final Tag tag = tagReader.readTag();
 800        if (tag != null && tag.isStart("stream")) {
 801            SSLSocketHelper.log(account, sslSocket);
 802            processStream();
 803        } else {
 804            throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
 805        }
 806        sslSocket.close();
 807    }
 808
 809    private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
 810        final TlsFactoryVerifier tlsFactoryVerifier;
 811        try {
 812            tlsFactoryVerifier = getTlsFactoryVerifier();
 813        } catch (final NoSuchAlgorithmException | KeyManagementException e) {
 814            throw new StateChangingException(Account.State.TLS_ERROR);
 815        }
 816        final InetAddress address = socket.getInetAddress();
 817        final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
 818        SSLSocketHelper.setSecurity(sslSocket);
 819        SSLSocketHelper.setHostname(sslSocket, account.getServer());
 820        SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
 821        if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
 822            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
 823            FileBackend.close(sslSocket);
 824            throw new StateChangingException(Account.State.TLS_ERROR);
 825        }
 826        return sslSocket;
 827    }
 828
 829    private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
 830        this.streamFeatures = tagReader.readElement(currentTag);
 831        final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
 832        final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
 833        if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
 834            sendStartTLS();
 835        } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 836            if (isSecure) {
 837                register();
 838            } else {
 839                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find STARTTLS for registration process "+ XmlHelper.printElementNames(this.streamFeatures));
 840                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 841            }
 842        } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
 843            throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
 844        } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
 845            authenticate();
 846        } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
 847            if (Config.EXTENDED_SM_LOGGING) {
 848                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
 849            }
 850            final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
 851            this.mSmCatchupMessageCounter.set(0);
 852            this.mWaitingForSmCatchup.set(true);
 853            this.tagWriter.writeStanzaAsync(resume);
 854        } else if (needsBinding) {
 855            if (this.streamFeatures.hasChild("bind") && isSecure) {
 856                sendBindRequest();
 857            } else {
 858                Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find bind feature "+ XmlHelper.printElementNames(this.streamFeatures));
 859                throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 860            }
 861        }
 862    }
 863
 864    private void authenticate() throws IOException {
 865        final List<String> mechanisms = extractMechanisms(streamFeatures
 866                .findChild("mechanisms"));
 867        final Element auth = new Element("auth", Namespace.SASL);
 868        if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
 869            saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
 870        } else if (mechanisms.contains("SCRAM-SHA-256")) {
 871            saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
 872        } else if (mechanisms.contains("SCRAM-SHA-1")) {
 873            saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
 874        } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
 875            saslMechanism = new Plain(tagWriter, account);
 876        } else if (mechanisms.contains("DIGEST-MD5")) {
 877            saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
 878        } else if (mechanisms.contains("ANONYMOUS")) {
 879            saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
 880        }
 881        if (saslMechanism != null) {
 882            final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
 883            if (pinnedMechanism > saslMechanism.getPriority()) {
 884                Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
 885                        " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
 886                        ") than pinned priority (" + pinnedMechanism +
 887                        "). Possible downgrade attack?");
 888                throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
 889            }
 890            Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
 891            auth.setAttribute("mechanism", saslMechanism.getMechanism());
 892            if (!saslMechanism.getClientFirstMessage().isEmpty()) {
 893                auth.setContent(saslMechanism.getClientFirstMessage());
 894            }
 895            tagWriter.writeElement(auth);
 896        } else {
 897            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to find SASL mechanism "+ saslMechanism.toString());
 898            throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
 899        }
 900    }
 901
 902    private List<String> extractMechanisms(final Element stream) {
 903        final ArrayList<String> mechanisms = new ArrayList<>(stream
 904                .getChildren().size());
 905        for (final Element child : stream.getChildren()) {
 906            mechanisms.add(child.getContent());
 907        }
 908        return mechanisms;
 909    }
 910
 911
 912    private void register() {
 913        final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
 914        if (preAuth != null && features.invite()) {
 915            final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
 916            preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
 917            sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
 918                if (response.getType() == IqPacket.TYPE.RESULT) {
 919                    sendRegistryRequest();
 920                } else {
 921                    final Element error = response.getError();
 922                    Log.d(Config.LOGTAG,account.getJid().asBareJid()+": failed to pre auth. "+error);
 923                    throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
 924                }
 925            }, true);
 926        } else {
 927            sendRegistryRequest();
 928        }
 929    }
 930
 931    private void sendRegistryRequest() {
 932        final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
 933        register.query(Namespace.REGISTER);
 934        register.setTo(Jid.of(account.getServer()));
 935        sendUnmodifiedIqPacket(register, (account, packet) -> {
 936            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 937                return;
 938            }
 939            if (packet.getType() == IqPacket.TYPE.ERROR) {
 940                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 941            }
 942            final Element query = packet.query(Namespace.REGISTER);
 943            if (query.hasChild("username") && (query.hasChild("password"))) {
 944                final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
 945                final Element username = new Element("username").setContent(account.getUsername());
 946                final Element password = new Element("password").setContent(account.getPassword());
 947                register1.query(Namespace.REGISTER).addChild(username);
 948                register1.query().addChild(password);
 949                register1.setFrom(account.getJid().asBareJid());
 950                sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
 951            } else if (query.hasChild("x", Namespace.DATA)) {
 952                final Data data = Data.parse(query.findChild("x", Namespace.DATA));
 953                final Element blob = query.findChild("data", "urn:xmpp:bob");
 954                final String id = packet.getId();
 955                InputStream is;
 956                if (blob != null) {
 957                    try {
 958                        final String base64Blob = blob.getContent();
 959                        final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
 960                        is = new ByteArrayInputStream(strBlob);
 961                    } catch (Exception e) {
 962                        is = null;
 963                    }
 964                } else {
 965                    try {
 966                        Field field = data.getFieldByName("url");
 967                        URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
 968                        is = url != null ? url.openStream() : null;
 969                    } catch (IOException e) {
 970                        is = null;
 971                    }
 972                }
 973
 974                if (is != null) {
 975                    Bitmap captcha = BitmapFactory.decodeStream(is);
 976                    try {
 977                        if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
 978                            return;
 979                        }
 980                    } catch (Exception e) {
 981                        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 982                    }
 983                }
 984                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 985            } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
 986                final String instructions = query.findChildContent("instructions");
 987                final Element oob = query.findChild("x", Namespace.OOB);
 988                final String url = oob == null ? null : oob.findChildContent("url");
 989                if (url != null) {
 990                    setAccountCreationFailed(url);
 991                } else if (instructions != null) {
 992                    Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
 993                    if (matcher.find()) {
 994                        setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
 995                    }
 996                }
 997                throw new StateChangingError(Account.State.REGISTRATION_FAILED);
 998            }
 999        }, true);
1000    }
1001
1002    private void setAccountCreationFailed(String url) {
1003        if (url != null) {
1004            try {
1005                this.redirectionUrl = new URL(url);
1006                if (this.redirectionUrl.getProtocol().equals("https")) {
1007                    throw new StateChangingError(Account.State.REGISTRATION_WEB);
1008                }
1009            } catch (MalformedURLException e) {
1010                //fall through
1011            }
1012        }
1013        throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1014    }
1015
1016    public URL getRedirectionUrl() {
1017        return this.redirectionUrl;
1018    }
1019
1020    public void resetEverything() {
1021        resetAttemptCount(true);
1022        resetStreamId();
1023        clearIqCallbacks();
1024        this.stanzasSent = 0;
1025        mStanzaQueue.clear();
1026        this.redirectionUrl = null;
1027        synchronized (this.disco) {
1028            disco.clear();
1029        }
1030    }
1031
1032    private void sendBindRequest() {
1033        try {
1034            mXmppConnectionService.restoredFromDatabaseLatch.await();
1035        } catch (InterruptedException e) {
1036            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1037            return;
1038        }
1039        clearIqCallbacks();
1040        if (account.getJid().isBareJid()) {
1041            account.setResource(this.createNewResource());
1042        } else {
1043            fixResource(mXmppConnectionService, account);
1044        }
1045        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1046        final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1047        iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1048        this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1049            if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1050                return;
1051            }
1052            final Element bind = packet.findChild("bind");
1053            if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1054                isBound = true;
1055                final Element jid = bind.findChild("jid");
1056                if (jid != null && jid.getContent() != null) {
1057                    try {
1058                        Jid assignedJid = Jid.ofEscaped(jid.getContent());
1059                        if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1060                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1061                            throw new StateChangingError(Account.State.BIND_FAILURE);
1062                        }
1063                        if (account.setJid(assignedJid)) {
1064                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1065                            mXmppConnectionService.databaseBackend.updateAccount(account);
1066                        }
1067                        if (streamFeatures.hasChild("session")
1068                                && !streamFeatures.findChild("session").hasChild("optional")) {
1069                            sendStartSession();
1070                        } else {
1071                            sendPostBindInitialization();
1072                        }
1073                        return;
1074                    } catch (final IllegalArgumentException e) {
1075                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1076                    }
1077                } else {
1078                    Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1079                }
1080            } else {
1081                Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1082            }
1083            final Element error = packet.findChild("error");
1084            if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1085                account.setResource(createNewResource());
1086            }
1087            throw new StateChangingError(Account.State.BIND_FAILURE);
1088        }, true);
1089    }
1090
1091    private void clearIqCallbacks() {
1092        final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1093        final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1094        synchronized (this.packetCallbacks) {
1095            if (this.packetCallbacks.size() == 0) {
1096                return;
1097            }
1098            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1099            final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1100            while (iterator.hasNext()) {
1101                Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1102                callbacks.add(entry.second);
1103                iterator.remove();
1104            }
1105        }
1106        for (OnIqPacketReceived callback : callbacks) {
1107            try {
1108                callback.onIqPacketReceived(account, failurePacket);
1109            } catch (StateChangingError error) {
1110                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1111                //ignore
1112            }
1113        }
1114        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1115    }
1116
1117    public void sendDiscoTimeout() {
1118        if (mWaitForDisco.compareAndSet(true, false)) {
1119            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1120            finalizeBind();
1121        }
1122    }
1123
1124    private void sendStartSession() {
1125        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1126        final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1127        startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1128        this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1129            if (packet.getType() == IqPacket.TYPE.RESULT) {
1130                sendPostBindInitialization();
1131            } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1132                throw new StateChangingError(Account.State.SESSION_FAILURE);
1133            }
1134        }, true);
1135    }
1136
1137    private void sendPostBindInitialization() {
1138        smVersion = 0;
1139        if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1140            smVersion = 3;
1141        } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1142            smVersion = 2;
1143        }
1144        if (smVersion != 0) {
1145            synchronized (this.mStanzaQueue) {
1146                final EnablePacket enable = new EnablePacket(smVersion);
1147                tagWriter.writeStanzaAsync(enable);
1148                stanzasSent = 0;
1149                mStanzaQueue.clear();
1150            }
1151        }
1152        features.carbonsEnabled = false;
1153        features.blockListRequested = false;
1154        synchronized (this.disco) {
1155            this.disco.clear();
1156        }
1157        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1158        mPendingServiceDiscoveries.set(0);
1159        if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
1160            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1161            mWaitForDisco.set(false);
1162        } else {
1163            mWaitForDisco.set(true);
1164        }
1165        lastDiscoStarted = SystemClock.elapsedRealtime();
1166        mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1167        Element caps = streamFeatures.findChild("c");
1168        final String hash = caps == null ? null : caps.getAttribute("hash");
1169        final String ver = caps == null ? null : caps.getAttribute("ver");
1170        ServiceDiscoveryResult discoveryResult = null;
1171        if (hash != null && ver != null) {
1172            discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1173        }
1174        final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1175        if (requestDiscoItemsFirst) {
1176            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1177        }
1178        if (discoveryResult == null) {
1179            sendServiceDiscoveryInfo(Jid.of(account.getServer()));
1180        } else {
1181            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1182            disco.put(Jid.of(account.getServer()), discoveryResult);
1183        }
1184        discoverMamPreferences();
1185        sendServiceDiscoveryInfo(account.getJid().asBareJid());
1186        if (!requestDiscoItemsFirst) {
1187            sendServiceDiscoveryItems(Jid.of(account.getServer()));
1188        }
1189
1190        if (!mWaitForDisco.get()) {
1191            finalizeBind();
1192        }
1193        this.lastSessionStarted = SystemClock.elapsedRealtime();
1194    }
1195
1196    private void sendServiceDiscoveryInfo(final Jid jid) {
1197        mPendingServiceDiscoveries.incrementAndGet();
1198        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1199        iq.setTo(jid);
1200        iq.query("http://jabber.org/protocol/disco#info");
1201        this.sendIqPacket(iq, (account, packet) -> {
1202            if (packet.getType() == IqPacket.TYPE.RESULT) {
1203                boolean advancedStreamFeaturesLoaded;
1204                synchronized (XmppConnection.this.disco) {
1205                    ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1206                    if (jid.equals(Jid.of(account.getServer()))) {
1207                        mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1208                    }
1209                    disco.put(jid, result);
1210                    advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
1211                            && disco.containsKey(account.getJid().asBareJid());
1212                }
1213                if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
1214                    enableAdvancedStreamFeatures();
1215                }
1216            } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1217                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1218                final boolean serverOrAccount = jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid());
1219                final boolean advancedStreamFeaturesLoaded;
1220                if (serverOrAccount) {
1221                    synchronized (XmppConnection.this.disco) {
1222                        disco.put(jid, ServiceDiscoveryResult.empty());
1223                        advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer())) && disco.containsKey(account.getJid().asBareJid());
1224                    }
1225                } else {
1226                    advancedStreamFeaturesLoaded = false;
1227                }
1228                if (advancedStreamFeaturesLoaded) {
1229                    enableAdvancedStreamFeatures();
1230                }
1231            }
1232            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1233                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1234                        && mWaitForDisco.compareAndSet(true, false)) {
1235                    finalizeBind();
1236                }
1237            }
1238        });
1239    }
1240
1241    private void discoverMamPreferences() {
1242        IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1243        request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1244        sendIqPacket(request, (account, response) -> {
1245           if (response.getType() == IqPacket.TYPE.RESULT) {
1246               Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1247               isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1248           }
1249        });
1250    }
1251
1252    public boolean isMamPreferenceAlways() {
1253        return isMamPreferenceAlways;
1254    }
1255
1256    private void finalizeBind() {
1257        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1258        if (bindListener != null) {
1259            bindListener.onBind(account);
1260        }
1261        changeStatus(Account.State.ONLINE);
1262    }
1263
1264    private void enableAdvancedStreamFeatures() {
1265        if (getFeatures().blocking() && !features.blockListRequested) {
1266            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1267            this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1268        }
1269        for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1270            listener.onAdvancedStreamFeaturesAvailable(account);
1271        }
1272        if (getFeatures().carbons() && !features.carbonsEnabled) {
1273            sendEnableCarbons();
1274        }
1275    }
1276
1277    private void sendServiceDiscoveryItems(final Jid server) {
1278        mPendingServiceDiscoveries.incrementAndGet();
1279        final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1280        iq.setTo(Jid.ofDomain(server.getDomain()));
1281        iq.query("http://jabber.org/protocol/disco#items");
1282        this.sendIqPacket(iq, (account, packet) -> {
1283            if (packet.getType() == IqPacket.TYPE.RESULT) {
1284                HashSet<Jid> items = new HashSet<Jid>();
1285                final List<Element> elements = packet.query().getChildren();
1286                for (final Element element : elements) {
1287                    if (element.getName().equals("item")) {
1288                        final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1289                        if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
1290                            items.add(jid);
1291                        }
1292                    }
1293                }
1294                for (Jid jid : items) {
1295                    sendServiceDiscoveryInfo(jid);
1296                }
1297            } else {
1298                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1299            }
1300            if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1301                if (mPendingServiceDiscoveries.decrementAndGet() == 0
1302                        && mWaitForDisco.compareAndSet(true, false)) {
1303                    finalizeBind();
1304                }
1305            }
1306        });
1307    }
1308
1309    private void sendEnableCarbons() {
1310        final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1311        iq.addChild("enable", "urn:xmpp:carbons:2");
1312        this.sendIqPacket(iq, new OnIqPacketReceived() {
1313
1314            @Override
1315            public void onIqPacketReceived(final Account account, final IqPacket packet) {
1316                if (!packet.hasChild("error")) {
1317                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1318                            + ": successfully enabled carbons");
1319                    features.carbonsEnabled = true;
1320                } else {
1321                    Log.d(Config.LOGTAG, account.getJid().asBareJid()
1322                            + ": error enableing carbons " + packet.toString());
1323                }
1324            }
1325        });
1326    }
1327
1328    private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1329        final Element streamError = tagReader.readElement(currentTag);
1330        if (streamError == null) {
1331            return;
1332        }
1333        if (streamError.hasChild("conflict")) {
1334            account.setResource(createNewResource());
1335            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1336            throw new IOException();
1337        } else if (streamError.hasChild("host-unknown")) {
1338            throw new StateChangingException(Account.State.HOST_UNKNOWN);
1339        } else if (streamError.hasChild("policy-violation")) {
1340            this.lastConnect = SystemClock.elapsedRealtime();
1341            final String text = streamError.findChildContent("text");
1342            Log.d(Config.LOGTAG,account.getJid().asBareJid()+": policy violation. "+text);
1343            throw new StateChangingException(Account.State.POLICY_VIOLATION);
1344        } else {
1345            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1346            throw new StateChangingException(Account.State.STREAM_ERROR);
1347        }
1348    }
1349
1350    private void sendStartStream() throws IOException {
1351        final Tag stream = Tag.start("stream:stream");
1352        stream.setAttribute("to", account.getServer());
1353        stream.setAttribute("version", "1.0");
1354        stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1355        stream.setAttribute("xmlns", "jabber:client");
1356        stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1357        tagWriter.writeTag(stream);
1358    }
1359
1360    private String createNewResource() {
1361        return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1362    }
1363
1364    private String nextRandomId() {
1365        return nextRandomId(false);
1366    }
1367
1368    private String nextRandomId(boolean s) {
1369        return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1370    }
1371
1372    public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1373        packet.setFrom(account.getJid());
1374        return this.sendUnmodifiedIqPacket(packet, callback, false);
1375    }
1376
1377    public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1378        if (packet.getId() == null) {
1379            packet.setAttribute("id", nextRandomId());
1380        }
1381        if (callback != null) {
1382            synchronized (this.packetCallbacks) {
1383                packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1384            }
1385        }
1386        this.sendPacket(packet, force);
1387        return packet.getId();
1388    }
1389
1390    public void sendMessagePacket(final MessagePacket packet) {
1391        this.sendPacket(packet);
1392    }
1393
1394    public void sendPresencePacket(final PresencePacket packet) {
1395        this.sendPacket(packet);
1396    }
1397
1398    private synchronized void sendPacket(final AbstractStanza packet) {
1399        sendPacket(packet, false);
1400    }
1401
1402    private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1403        if (stanzasSent == Integer.MAX_VALUE) {
1404            resetStreamId();
1405            disconnect(true);
1406            return;
1407        }
1408        synchronized (this.mStanzaQueue) {
1409            if (force || isBound) {
1410                tagWriter.writeStanzaAsync(packet);
1411            } else {
1412                Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1413            }
1414            if (packet instanceof AbstractAcknowledgeableStanza) {
1415                AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1416
1417                if (this.mStanzaQueue.size() != 0) {
1418                    int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1419                    if (currentHighestKey != stanzasSent) {
1420                        throw new AssertionError("Stanza count messed up");
1421                    }
1422                }
1423
1424                ++stanzasSent;
1425                this.mStanzaQueue.append(stanzasSent, stanza);
1426                if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1427                    if (Config.EXTENDED_SM_LOGGING) {
1428                        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1429                    }
1430                    tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1431                }
1432            }
1433        }
1434    }
1435
1436    public void sendPing() {
1437        if (!r()) {
1438            final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1439            iq.setFrom(account.getJid());
1440            iq.addChild("ping", Namespace.PING);
1441            this.sendIqPacket(iq, null);
1442        }
1443        this.lastPingSent = SystemClock.elapsedRealtime();
1444    }
1445
1446    public void setOnMessagePacketReceivedListener(
1447            final OnMessagePacketReceived listener) {
1448        this.messageListener = listener;
1449    }
1450
1451    public void setOnUnregisteredIqPacketReceivedListener(
1452            final OnIqPacketReceived listener) {
1453        this.unregisteredIqListener = listener;
1454    }
1455
1456    public void setOnPresencePacketReceivedListener(
1457            final OnPresencePacketReceived listener) {
1458        this.presenceListener = listener;
1459    }
1460
1461    public void setOnJinglePacketReceivedListener(
1462            final OnJinglePacketReceived listener) {
1463        this.jingleListener = listener;
1464    }
1465
1466    public void setOnStatusChangedListener(final OnStatusChanged listener) {
1467        this.statusListener = listener;
1468    }
1469
1470    public void setOnBindListener(final OnBindListener listener) {
1471        this.bindListener = listener;
1472    }
1473
1474    public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1475        this.acknowledgedListener = listener;
1476    }
1477
1478    public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1479        this.advancedStreamFeaturesLoadedListeners.add(listener);
1480    }
1481
1482    private void forceCloseSocket() {
1483        FileBackend.close(this.socket);
1484        FileBackend.close(this.tagReader);
1485    }
1486
1487    public void interrupt() {
1488        if (this.mThread != null) {
1489            this.mThread.interrupt();
1490        }
1491    }
1492
1493    public void disconnect(final boolean force) {
1494        interrupt();
1495        Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1496        if (force) {
1497            forceCloseSocket();
1498        } else {
1499            final TagWriter currentTagWriter = this.tagWriter;
1500            if (currentTagWriter.isActive()) {
1501                currentTagWriter.finish();
1502                final Socket currentSocket = this.socket;
1503                final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1504                try {
1505                    currentTagWriter.await(1, TimeUnit.SECONDS);
1506                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1507                    currentTagWriter.writeTag(Tag.end("stream:stream"));
1508                    if (streamCountDownLatch != null) {
1509                        if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1510                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1511                        } else {
1512                            Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1513                        }
1514                    }
1515                } catch (InterruptedException e) {
1516                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1517                } catch (final IOException e) {
1518                    Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1519                } finally {
1520                    FileBackend.close(currentSocket);
1521                }
1522            } else {
1523                forceCloseSocket();
1524            }
1525        }
1526    }
1527
1528    private void resetStreamId() {
1529        this.streamId = null;
1530    }
1531
1532    private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1533        synchronized (this.disco) {
1534            final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1535            for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1536                if (cursor.getValue().getFeatures().contains(feature)) {
1537                    items.add(cursor);
1538                }
1539            }
1540            return items;
1541        }
1542    }
1543
1544    public Jid findDiscoItemByFeature(final String feature) {
1545        final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1546        if (items.size() >= 1) {
1547            return items.get(0).getKey();
1548        }
1549        return null;
1550    }
1551
1552    public boolean r() {
1553        if (getFeatures().sm()) {
1554            this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1555            return true;
1556        } else {
1557            return false;
1558        }
1559    }
1560
1561    public List<String> getMucServersWithholdAccount() {
1562        List<String> servers = getMucServers();
1563        servers.remove(account.getServer());
1564        return servers;
1565    }
1566
1567    public List<String> getMucServers() {
1568        List<String> servers = new ArrayList<>();
1569        synchronized (this.disco) {
1570            for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1571                final ServiceDiscoveryResult value = cursor.getValue();
1572                if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1573                        && value.hasIdentity("conference", "text")
1574                        && !value.getFeatures().contains("jabber:iq:gateway")
1575                        && !value.hasIdentity("conference", "irc")) {
1576                    servers.add(cursor.getKey().toString());
1577                }
1578            }
1579        }
1580        return servers;
1581    }
1582
1583    public String getMucServer() {
1584        List<String> servers = getMucServers();
1585        return servers.size() > 0 ? servers.get(0) : null;
1586    }
1587
1588    public int getTimeToNextAttempt() {
1589        final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1590        final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1591        final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1592        return interval - secondsSinceLast;
1593    }
1594
1595    public int getAttempt() {
1596        return this.attempt;
1597    }
1598
1599    public Features getFeatures() {
1600        return this.features;
1601    }
1602
1603    public long getLastSessionEstablished() {
1604        final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1605        return System.currentTimeMillis() - diff;
1606    }
1607
1608    public long getLastConnect() {
1609        return this.lastConnect;
1610    }
1611
1612    public long getLastPingSent() {
1613        return this.lastPingSent;
1614    }
1615
1616    public long getLastDiscoStarted() {
1617        return this.lastDiscoStarted;
1618    }
1619
1620    public long getLastPacketReceived() {
1621        return this.lastPacketReceived;
1622    }
1623
1624    public void sendActive() {
1625        this.sendPacket(new ActivePacket());
1626    }
1627
1628    public void sendInactive() {
1629        this.sendPacket(new InactivePacket());
1630    }
1631
1632    public void resetAttemptCount(boolean resetConnectTime) {
1633        this.attempt = 0;
1634        if (resetConnectTime) {
1635            this.lastConnect = 0;
1636        }
1637    }
1638
1639    public void setInteractive(boolean interactive) {
1640        this.mInteractive = interactive;
1641    }
1642
1643    public Identity getServerIdentity() {
1644        synchronized (this.disco) {
1645            ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
1646            if (result == null) {
1647                return Identity.UNKNOWN;
1648            }
1649            for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1650                if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1651                    switch (id.getName()) {
1652                        case "Prosody":
1653                            return Identity.PROSODY;
1654                        case "ejabberd":
1655                            return Identity.EJABBERD;
1656                        case "Slack-XMPP":
1657                            return Identity.SLACK;
1658                    }
1659                }
1660            }
1661        }
1662        return Identity.UNKNOWN;
1663    }
1664
1665    private IqGenerator getIqGenerator() {
1666        return mXmppConnectionService.getIqGenerator();
1667    }
1668
1669    public enum Identity {
1670        FACEBOOK,
1671        SLACK,
1672        EJABBERD,
1673        PROSODY,
1674        NIMBUZZ,
1675        UNKNOWN
1676    }
1677
1678    private static class TlsFactoryVerifier {
1679        private final SSLSocketFactory factory;
1680        private final DomainHostnameVerifier verifier;
1681
1682        TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1683            this.factory = factory;
1684            this.verifier = verifier;
1685            if (factory == null || verifier == null) {
1686                throw new IOException("could not setup ssl");
1687            }
1688        }
1689    }
1690
1691    private class MyKeyManager implements X509KeyManager {
1692        @Override
1693        public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1694            return account.getPrivateKeyAlias();
1695        }
1696
1697        @Override
1698        public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1699            return null;
1700        }
1701
1702        @Override
1703        public X509Certificate[] getCertificateChain(String alias) {
1704            Log.d(Config.LOGTAG, "getting certificate chain");
1705            try {
1706                return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1707            } catch (Exception e) {
1708                Log.d(Config.LOGTAG, e.getMessage());
1709                return new X509Certificate[0];
1710            }
1711        }
1712
1713        @Override
1714        public String[] getClientAliases(String s, Principal[] principals) {
1715            final String alias = account.getPrivateKeyAlias();
1716            return alias != null ? new String[]{alias} : new String[0];
1717        }
1718
1719        @Override
1720        public String[] getServerAliases(String s, Principal[] principals) {
1721            return new String[0];
1722        }
1723
1724        @Override
1725        public PrivateKey getPrivateKey(String alias) {
1726            try {
1727                return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1728            } catch (Exception e) {
1729                return null;
1730            }
1731        }
1732    }
1733
1734    private class StateChangingError extends Error {
1735        private final Account.State state;
1736
1737        public StateChangingError(Account.State state) {
1738            this.state = state;
1739        }
1740    }
1741
1742    private class StateChangingException extends IOException {
1743        private final Account.State state;
1744
1745        public StateChangingException(Account.State state) {
1746            this.state = state;
1747        }
1748    }
1749
1750    public class Features {
1751        XmppConnection connection;
1752        private boolean carbonsEnabled = false;
1753        private boolean encryptionEnabled = false;
1754        private boolean blockListRequested = false;
1755
1756        public Features(final XmppConnection connection) {
1757            this.connection = connection;
1758        }
1759
1760        private boolean hasDiscoFeature(final Jid server, final String feature) {
1761            synchronized (XmppConnection.this.disco) {
1762                return connection.disco.containsKey(server) &&
1763                        connection.disco.get(server).getFeatures().contains(feature);
1764            }
1765        }
1766
1767        public boolean carbons() {
1768            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
1769        }
1770
1771        public boolean bookmarksConversion() {
1772            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1773        }
1774
1775        public boolean avatarConversion() {
1776            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1777        }
1778
1779        public boolean blocking() {
1780            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
1781        }
1782
1783        public boolean spamReporting() {
1784            return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
1785        }
1786
1787        public boolean flexibleOfflineMessageRetrieval() {
1788            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1789        }
1790
1791        public boolean register() {
1792            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
1793        }
1794
1795        public boolean invite() {
1796            return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1797        }
1798
1799        public boolean sm() {
1800            return streamId != null
1801                    || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1802        }
1803
1804        public boolean csi() {
1805            return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1806        }
1807
1808        public boolean pep() {
1809            synchronized (XmppConnection.this.disco) {
1810                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1811                return info != null && info.hasIdentity("pubsub", "pep");
1812            }
1813        }
1814
1815        public boolean pepPersistent() {
1816            synchronized (XmppConnection.this.disco) {
1817                ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1818                return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1819            }
1820        }
1821
1822        public boolean pepPublishOptions() {
1823            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1824        }
1825
1826        public boolean pepOmemoWhitelisted() {
1827            return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1828        }
1829
1830        public boolean mam() {
1831            return MessageArchiveService.Version.has(getAccountFeatures());
1832        }
1833
1834        public List<String> getAccountFeatures() {
1835            ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1836            return result == null ? Collections.emptyList() : result.getFeatures();
1837        }
1838
1839        public boolean push() {
1840            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1841                    || hasDiscoFeature(Jid.of(account.getServer()), Namespace.PUSH);
1842        }
1843
1844        public boolean rosterVersioning() {
1845            return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1846        }
1847
1848        public void setBlockListRequested(boolean value) {
1849            this.blockListRequested = value;
1850        }
1851
1852        public boolean p1S3FileTransfer() {
1853            return hasDiscoFeature(Jid.of(account.getServer()), Namespace.P1_S3_FILE_TRANSFER);
1854        }
1855
1856        public boolean httpUpload(long filesize) {
1857            if (Config.DISABLE_HTTP_UPLOAD) {
1858                return false;
1859            } else {
1860                for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1861                    List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1862                    if (items.size() > 0) {
1863                        try {
1864                            long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1865                            if (filesize <= maxsize) {
1866                                return true;
1867                            } else {
1868                                Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1869                                return false;
1870                            }
1871                        } catch (Exception e) {
1872                            return true;
1873                        }
1874                    }
1875                }
1876                return false;
1877            }
1878        }
1879
1880        public boolean useLegacyHttpUpload() {
1881            return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1882        }
1883
1884        public long getMaxHttpUploadSize() {
1885            for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1886                List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1887                if (items.size() > 0) {
1888                    try {
1889                        return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1890                    } catch (Exception e) {
1891                        //ignored
1892                    }
1893                }
1894            }
1895            return -1;
1896        }
1897
1898        public boolean stanzaIds() {
1899            return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1900        }
1901
1902        public boolean bookmarks2() {
1903            return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
1904        }
1905    }
1906}