XmppConnection.java

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