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