XmppConnection.java

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