XmppConnection.java

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