1package eu.siacs.conversations.xmpp;
2
3import static eu.siacs.conversations.utils.Random.SECURE_RANDOM;
4
5import android.content.Context;
6import android.graphics.Bitmap;
7import android.graphics.BitmapFactory;
8import android.os.Build;
9import android.os.SystemClock;
10import android.security.KeyChain;
11import android.util.Base64;
12import android.util.Log;
13import android.util.Pair;
14import android.util.SparseArray;
15import androidx.annotation.NonNull;
16import androidx.annotation.Nullable;
17import com.google.common.base.MoreObjects;
18import com.google.common.base.Optional;
19import com.google.common.base.Preconditions;
20import com.google.common.base.Strings;
21import com.google.common.collect.ImmutableList;
22import com.google.common.collect.Iterables;
23import eu.siacs.conversations.AppSettings;
24import eu.siacs.conversations.BuildConfig;
25import eu.siacs.conversations.Config;
26import eu.siacs.conversations.R;
27import eu.siacs.conversations.crypto.XmppDomainVerifier;
28import eu.siacs.conversations.crypto.axolotl.AxolotlService;
29import eu.siacs.conversations.crypto.sasl.ChannelBinding;
30import eu.siacs.conversations.crypto.sasl.ChannelBindingMechanism;
31import eu.siacs.conversations.crypto.sasl.HashedToken;
32import eu.siacs.conversations.crypto.sasl.SaslMechanism;
33import eu.siacs.conversations.entities.Account;
34import eu.siacs.conversations.entities.Message;
35import eu.siacs.conversations.entities.ServiceDiscoveryResult;
36import eu.siacs.conversations.generator.IqGenerator;
37import eu.siacs.conversations.http.HttpConnectionManager;
38import eu.siacs.conversations.parser.IqParser;
39import eu.siacs.conversations.parser.MessageParser;
40import eu.siacs.conversations.parser.PresenceParser;
41import eu.siacs.conversations.persistance.FileBackend;
42import eu.siacs.conversations.services.MemorizingTrustManager;
43import eu.siacs.conversations.services.MessageArchiveService;
44import eu.siacs.conversations.services.NotificationService;
45import eu.siacs.conversations.services.XmppConnectionService;
46import eu.siacs.conversations.ui.util.PendingItem;
47import eu.siacs.conversations.utils.AccountUtils;
48import eu.siacs.conversations.utils.CryptoHelper;
49import eu.siacs.conversations.utils.Patterns;
50import eu.siacs.conversations.utils.PhoneHelper;
51import eu.siacs.conversations.utils.Resolver;
52import eu.siacs.conversations.utils.SSLSockets;
53import eu.siacs.conversations.utils.SocksSocketFactory;
54import eu.siacs.conversations.utils.XmlHelper;
55import eu.siacs.conversations.xml.Element;
56import eu.siacs.conversations.xml.LocalizedContent;
57import eu.siacs.conversations.xml.Namespace;
58import eu.siacs.conversations.xml.Tag;
59import eu.siacs.conversations.xml.TagWriter;
60import eu.siacs.conversations.xml.XmlReader;
61import eu.siacs.conversations.xmpp.bind.Bind2;
62import eu.siacs.conversations.xmpp.forms.Data;
63import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
64import im.conversations.android.xmpp.model.AuthenticationFailure;
65import im.conversations.android.xmpp.model.AuthenticationRequest;
66import im.conversations.android.xmpp.model.AuthenticationStreamFeature;
67import im.conversations.android.xmpp.model.StreamElement;
68import im.conversations.android.xmpp.model.bind2.Bind;
69import im.conversations.android.xmpp.model.bind2.Bound;
70import im.conversations.android.xmpp.model.csi.Active;
71import im.conversations.android.xmpp.model.csi.Inactive;
72import im.conversations.android.xmpp.model.error.Condition;
73import im.conversations.android.xmpp.model.fast.Fast;
74import im.conversations.android.xmpp.model.fast.RequestToken;
75import im.conversations.android.xmpp.model.jingle.Jingle;
76import im.conversations.android.xmpp.model.sasl.Auth;
77import im.conversations.android.xmpp.model.sasl.Failure;
78import im.conversations.android.xmpp.model.sasl.Mechanisms;
79import im.conversations.android.xmpp.model.sasl.Response;
80import im.conversations.android.xmpp.model.sasl.SaslError;
81import im.conversations.android.xmpp.model.sasl.Success;
82import im.conversations.android.xmpp.model.sasl2.Authenticate;
83import im.conversations.android.xmpp.model.sasl2.Authentication;
84import im.conversations.android.xmpp.model.sasl2.UserAgent;
85import im.conversations.android.xmpp.model.sm.Ack;
86import im.conversations.android.xmpp.model.sm.Enable;
87import im.conversations.android.xmpp.model.sm.Enabled;
88import im.conversations.android.xmpp.model.sm.Failed;
89import im.conversations.android.xmpp.model.sm.Request;
90import im.conversations.android.xmpp.model.sm.Resume;
91import im.conversations.android.xmpp.model.sm.Resumed;
92import im.conversations.android.xmpp.model.sm.StreamManagement;
93import im.conversations.android.xmpp.model.stanza.Iq;
94import im.conversations.android.xmpp.model.stanza.Presence;
95import im.conversations.android.xmpp.model.stanza.Stanza;
96import im.conversations.android.xmpp.model.streams.StreamError;
97import im.conversations.android.xmpp.model.tls.Proceed;
98import im.conversations.android.xmpp.model.tls.StartTls;
99import im.conversations.android.xmpp.processor.BindProcessor;
100import java.io.ByteArrayInputStream;
101import java.io.IOException;
102import java.io.InputStream;
103import java.net.ConnectException;
104import java.net.IDN;
105import java.net.InetAddress;
106import java.net.InetSocketAddress;
107import java.net.Socket;
108import java.net.UnknownHostException;
109import java.security.KeyManagementException;
110import java.security.NoSuchAlgorithmException;
111import java.security.Principal;
112import java.security.PrivateKey;
113import java.security.cert.X509Certificate;
114import java.util.ArrayList;
115import java.util.Arrays;
116import java.util.Collection;
117import java.util.Collections;
118import java.util.HashMap;
119import java.util.HashSet;
120import java.util.Hashtable;
121import java.util.Iterator;
122import java.util.List;
123import java.util.Map.Entry;
124import java.util.Set;
125import java.util.concurrent.CountDownLatch;
126import java.util.concurrent.TimeUnit;
127import java.util.concurrent.atomic.AtomicBoolean;
128import java.util.concurrent.atomic.AtomicInteger;
129import java.util.function.Consumer;
130import java.util.regex.Matcher;
131import javax.net.ssl.KeyManager;
132import javax.net.ssl.SSLContext;
133import javax.net.ssl.SSLPeerUnverifiedException;
134import javax.net.ssl.SSLSocket;
135import javax.net.ssl.SSLSocketFactory;
136import javax.net.ssl.X509KeyManager;
137import javax.net.ssl.X509TrustManager;
138import okhttp3.HttpUrl;
139import org.xmlpull.v1.XmlPullParserException;
140
141public class XmppConnection implements Runnable {
142
143 protected final Account account;
144 private final Features features = new Features(this);
145 private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
146 private final HashMap<String, Jid> commands = new HashMap<>();
147 private final SparseArray<Stanza> mStanzaQueue = new SparseArray<>();
148 private final Hashtable<String, Pair<Iq, Consumer<Iq>>> packetCallbacks = new Hashtable<>();
149 private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners =
150 new HashSet<>();
151 private final AppSettings appSettings;
152 private final XmppConnectionService mXmppConnectionService;
153 private Socket socket;
154 private XmlReader tagReader;
155 private TagWriter tagWriter = new TagWriter();
156 private boolean shouldAuthenticate = true;
157 private boolean inSmacksSession = false;
158 private boolean quickStartInProgress = false;
159 private boolean isBound = false;
160 private boolean offlineMessagesRetrieved = false;
161 private im.conversations.android.xmpp.model.streams.Features streamFeatures;
162 private im.conversations.android.xmpp.model.streams.Features boundStreamFeatures;
163 private StreamId streamId = null;
164 private int stanzasReceived = 0;
165 private int stanzasSent = 0;
166 private int stanzasSentBeforeAuthentication;
167 private long lastPacketReceived = 0;
168 private long lastPingSent = 0;
169 private long lastConnect = 0;
170 private long lastSessionStarted = 0;
171 private long lastDiscoStarted = 0;
172 private boolean isMamPreferenceAlways = false;
173 private final AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
174 private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
175 private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
176 private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
177 private boolean mInteractive = false;
178 private int attempt = 0;
179 private OnJinglePacketReceived jingleListener = null;
180
181 private final Consumer<Presence> presenceListener;
182 private final Consumer<Iq> unregisteredIqListener;
183 private final Consumer<im.conversations.android.xmpp.model.stanza.Message> messageListener;
184 private OnStatusChanged statusListener = null;
185 private final Runnable bindListener;
186 private OnMessageAcknowledged acknowledgedListener = null;
187 private final PendingItem<String> pendingResumeId = new PendingItem<>();
188 private LoginInfo loginInfo;
189 private HashedToken.Mechanism hashTokenRequest;
190 private HttpUrl redirectionUrl = null;
191 private String verifiedHostname = null;
192 private Resolver.Result currentResolverResult;
193 private Resolver.Result seeOtherHostResolverResult;
194 private volatile Thread mThread;
195 private CountDownLatch mStreamCountDownLatch;
196
197 public XmppConnection(final Account account, final XmppConnectionService service) {
198 this.account = account;
199 this.mXmppConnectionService = service;
200 this.appSettings = mXmppConnectionService.getAppSettings();
201 this.presenceListener = new PresenceParser(service, account);
202 this.unregisteredIqListener = new IqParser(service, account);
203 this.messageListener = new MessageParser(service, account);
204 this.bindListener = new BindProcessor(service, account);
205 }
206
207 private static void fixResource(final Context context, final Account account) {
208 String resource = account.getResource();
209 int fixedPartLength =
210 context.getString(R.string.app_name).length() + 1; // include the trailing dot
211 int randomPartLength = 4; // 3 bytes
212 if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
213 if (validBase64(
214 resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
215 account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
216 }
217 }
218 }
219
220 private static boolean validBase64(final String input) {
221 try {
222 return Base64.decode(input, Base64.URL_SAFE).length == 3;
223 } catch (final Throwable throwable) {
224 return false;
225 }
226 }
227
228 private void changeStatus(final Account.State nextStatus) {
229 synchronized (this) {
230 if (Thread.currentThread().isInterrupted()) {
231 Log.d(
232 Config.LOGTAG,
233 account.getJid().asBareJid()
234 + ": not changing status to "
235 + nextStatus
236 + " because thread was interrupted");
237 return;
238 }
239 if (account.getStatus() != nextStatus) {
240 if (nextStatus == Account.State.OFFLINE
241 && account.getStatus() != Account.State.CONNECTING
242 && account.getStatus() != Account.State.ONLINE
243 && account.getStatus() != Account.State.DISABLED
244 && account.getStatus() != Account.State.LOGGED_OUT) {
245 return;
246 }
247 if (nextStatus == Account.State.ONLINE) {
248 this.attempt = 0;
249 }
250 account.setStatus(nextStatus);
251 } else {
252 return;
253 }
254 }
255 if (statusListener != null) {
256 statusListener.onStatusChanged(account);
257 }
258 }
259
260 public Jid getJidForCommand(final String node) {
261 synchronized (this.commands) {
262 return this.commands.get(node);
263 }
264 }
265
266 public void prepareNewConnection() {
267 this.lastConnect = SystemClock.elapsedRealtime();
268 this.lastPingSent = SystemClock.elapsedRealtime();
269 this.lastDiscoStarted = Long.MAX_VALUE;
270 this.mWaitingForSmCatchup.set(false);
271 this.changeStatus(Account.State.CONNECTING);
272 }
273
274 public boolean isWaitingForSmCatchup() {
275 return mWaitingForSmCatchup.get();
276 }
277
278 public void incrementSmCatchupMessageCounter() {
279 this.mSmCatchupMessageCounter.incrementAndGet();
280 }
281
282 protected void connect() {
283 if (mXmppConnectionService.areMessagesInitialized()) {
284 mXmppConnectionService.resetSendingToWaiting(account);
285 }
286 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
287 this.pendingResumeId.clear();
288 this.loginInfo = null;
289 this.features.encryptionEnabled = false;
290 this.inSmacksSession = false;
291 this.quickStartInProgress = false;
292 this.isBound = false;
293 this.attempt++;
294 this.currentResolverResult = null;
295 // will be set if user entered hostname is being used or hostname was verified with dnssec
296 this.verifiedHostname = null;
297 try {
298 Socket localSocket;
299 shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
300 this.changeStatus(Account.State.CONNECTING);
301 final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
302 final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
303 // TODO collapse Tor usage into normal connection code path
304 if (useTor) {
305 final var seeOtherHost = this.seeOtherHostResolverResult;
306 final var hostname = account.getHostname();
307 final var port = account.getPort();
308 final Resolver.Result resume = streamId == null ? null : streamId.location;
309 final Resolver.Result viaTor;
310 if (resume != null) {
311 viaTor = resume;
312 } else if (seeOtherHost != null) {
313 viaTor = seeOtherHost;
314 } else if (hostname.isEmpty() || port < 0) {
315 viaTor =
316 Iterables.getOnlyElement(
317 Resolver.fromHardCoded(
318 account.getServer(), Resolver.XMPP_PORT_STARTTLS));
319 } else {
320 viaTor = Iterables.getOnlyElement(Resolver.fromHardCoded(hostname, port));
321 this.verifiedHostname = hostname;
322 }
323
324 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " via Tor: " + viaTor);
325
326 localSocket =
327 SocksSocketFactory.createSocketOverTor(
328 viaTor.asDestination(), viaTor.getPort());
329
330 if (viaTor.isDirectTls()) {
331 localSocket = upgradeSocketToTls(localSocket);
332 features.encryptionEnabled = true;
333 }
334
335 try {
336 if (startXmpp(localSocket)) {
337 this.currentResolverResult = viaTor;
338 this.seeOtherHostResolverResult = null;
339 }
340 } catch (final InterruptedException e) {
341 Log.d(
342 Config.LOGTAG,
343 account.getJid().asBareJid()
344 + ": thread was interrupted before beginning stream");
345 return;
346 } catch (final Exception e) {
347 throw new IOException("Could not start stream", e);
348 }
349 } else {
350 final var hostname = account.getHostname().trim();
351 final String domain = account.getServer();
352 final List<Resolver.Result> results = new ArrayList<>();
353 final boolean hardcoded = extended && !hostname.isEmpty();
354 if (hardcoded) {
355 results.addAll(Resolver.fromHardCoded(hostname, account.getPort()));
356 } else {
357 results.addAll(Resolver.resolve(domain));
358 }
359 if (Thread.currentThread().isInterrupted()) {
360 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
361 return;
362 }
363 if (results.isEmpty()) {
364 Log.e(
365 Config.LOGTAG,
366 account.getJid().asBareJid() + ": Resolver results were empty");
367 return;
368 }
369 final Resolver.Result storedBackupResult;
370 if (hardcoded) {
371 storedBackupResult = null;
372 } else {
373 storedBackupResult =
374 mXmppConnectionService.databaseBackend.findResolverResult(domain);
375 if (storedBackupResult != null && !results.contains(storedBackupResult)) {
376 results.add(storedBackupResult);
377 Log.d(
378 Config.LOGTAG,
379 account.getJid().asBareJid()
380 + ": loaded backup resolver result from db: "
381 + storedBackupResult);
382 }
383 }
384 final StreamId streamId = this.streamId;
385 final Resolver.Result resumeLocation = streamId == null ? null : streamId.location;
386 if (resumeLocation != null) {
387 Log.d(
388 Config.LOGTAG,
389 account.getJid().asBareJid()
390 + ": injected resume location on position 0");
391 results.add(0, resumeLocation);
392 }
393 final Resolver.Result seeOtherHost = this.seeOtherHostResolverResult;
394 if (seeOtherHost != null) {
395 Log.d(
396 Config.LOGTAG,
397 account.getJid().asBareJid()
398 + ": injected see-other-host on position 0");
399 results.add(0, seeOtherHost);
400 }
401 for (final Iterator<Resolver.Result> iterator = results.iterator();
402 iterator.hasNext(); ) {
403 final Resolver.Result result = iterator.next();
404 if (Thread.currentThread().isInterrupted()) {
405 Log.d(
406 Config.LOGTAG,
407 account.getJid().asBareJid() + ": Thread was interrupted");
408 return;
409 }
410 try {
411 // if tls is true, encryption is implied and must not be started
412 features.encryptionEnabled = result.isDirectTls();
413 verifiedHostname =
414 result.isAuthenticated() ? result.getHostname().toString() : null;
415 final InetSocketAddress addr;
416 if (result.getIp() != null) {
417 addr = new InetSocketAddress(result.getIp(), result.getPort());
418 Log.d(
419 Config.LOGTAG,
420 account.getJid().asBareJid().toString()
421 + ": using values from resolver "
422 + (result.getHostname() == null
423 ? ""
424 : result.getHostname().toString() + "/")
425 + result.getIp().getHostAddress()
426 + ":"
427 + result.getPort()
428 + " tls: "
429 + features.encryptionEnabled);
430 } else {
431 addr =
432 new InetSocketAddress(
433 IDN.toASCII(result.getHostname().toString()),
434 result.getPort());
435 Log.d(
436 Config.LOGTAG,
437 account.getJid().asBareJid().toString()
438 + ": using values from resolver "
439 + result.getHostname().toString()
440 + ":"
441 + result.getPort()
442 + " tls: "
443 + features.encryptionEnabled);
444 }
445
446 localSocket = new Socket();
447 localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
448
449 // TODO use result.isDirect() as condition and set encryptionEnabled after
450 if (features.encryptionEnabled) {
451 localSocket = upgradeSocketToTls(localSocket);
452 }
453
454 localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
455 if (startXmpp(localSocket)) {
456 // reset to 0; once the connection is established we don't want this
457 localSocket.setSoTimeout(0);
458 if (!hardcoded && !result.equals(storedBackupResult)) {
459 mXmppConnectionService.databaseBackend.saveResolverResult(
460 domain, result);
461 }
462 this.currentResolverResult = result;
463 this.seeOtherHostResolverResult = null;
464 break; // successfully connected to server that speaks xmpp
465 } else {
466 FileBackend.close(localSocket);
467 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
468 }
469 } catch (final StateChangingException e) {
470 if (!iterator.hasNext()) {
471 throw e;
472 }
473 } catch (InterruptedException e) {
474 Log.d(
475 Config.LOGTAG,
476 account.getJid().asBareJid()
477 + ": thread was interrupted before beginning stream");
478 return;
479 } catch (final Throwable e) {
480 Log.d(
481 Config.LOGTAG,
482 account.getJid().asBareJid().toString()
483 + ": "
484 + e.getMessage()
485 + "("
486 + e.getClass().getName()
487 + ")");
488 if (!iterator.hasNext()) {
489 throw new UnknownHostException();
490 }
491 }
492 }
493 }
494 processStream();
495 } catch (final SecurityException e) {
496 this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
497 } catch (final StateChangingException e) {
498 this.changeStatus(e.state);
499 } catch (final UnknownHostException
500 | ConnectException
501 | SocksSocketFactory.HostNotFoundException e) {
502 this.changeStatus(Account.State.SERVER_NOT_FOUND);
503 } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
504 this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
505 } catch (final IOException | XmlPullParserException e) {
506 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
507 this.changeStatus(Account.State.OFFLINE);
508 this.attempt = Math.max(0, this.attempt - 1);
509 } finally {
510 if (!Thread.currentThread().isInterrupted()) {
511 forceCloseSocket();
512 } else {
513 Log.d(
514 Config.LOGTAG,
515 account.getJid().asBareJid()
516 + ": not force closing socket because thread was interrupted");
517 }
518 }
519 }
520
521 /**
522 * Starts xmpp protocol, call after connecting to socket
523 *
524 * @return true if server returns with valid xmpp, false otherwise
525 */
526 private boolean startXmpp(final Socket socket) throws Exception {
527 if (Thread.currentThread().isInterrupted()) {
528 throw new InterruptedException();
529 }
530 this.socket = socket;
531 tagReader = new XmlReader();
532 if (tagWriter != null) {
533 tagWriter.forceClose();
534 }
535 tagWriter = new TagWriter();
536 tagWriter.setOutputStream(socket.getOutputStream());
537 tagReader.setInputStream(socket.getInputStream());
538 tagWriter.beginDocument();
539 final boolean quickStart;
540 if (socket instanceof SSLSocket sslSocket) {
541 SSLSockets.log(account, sslSocket);
542 quickStart = establishStream(SSLSockets.version(sslSocket));
543 } else {
544 quickStart = establishStream(SSLSockets.Version.NONE);
545 }
546 final Tag tag = tagReader.readTag();
547 if (Thread.currentThread().isInterrupted()) {
548 throw new InterruptedException();
549 }
550 if (tag == null) {
551 return false;
552 }
553 final boolean success = tag.isStart("stream", Namespace.STREAMS);
554 if (success) {
555 final var from = tag.getAttribute("from");
556 if (from == null || !from.equals(account.getServer())) {
557 throw new StateChangingException(Account.State.HOST_UNKNOWN);
558 }
559 }
560 if (success && quickStart) {
561 this.quickStartInProgress = true;
562 }
563 return success;
564 }
565
566 private SSLSocketFactory getSSLSocketFactory()
567 throws NoSuchAlgorithmException, KeyManagementException {
568 final SSLContext sc = SSLSockets.getSSLContext();
569 final MemorizingTrustManager trustManager =
570 this.mXmppConnectionService.getMemorizingTrustManager();
571 final KeyManager[] keyManager;
572 if (account.getPrivateKeyAlias() != null) {
573 keyManager = new KeyManager[] {new MyKeyManager()};
574 } else {
575 keyManager = null;
576 }
577 final String domain = account.getServer();
578 sc.init(
579 keyManager,
580 new X509TrustManager[] {
581 mInteractive
582 ? trustManager.getInteractive(domain)
583 : trustManager.getNonInteractive(domain)
584 },
585 SECURE_RANDOM);
586 return sc.getSocketFactory();
587 }
588
589 @Override
590 public void run() {
591 synchronized (this) {
592 this.mThread = Thread.currentThread();
593 if (this.mThread.isInterrupted()) {
594 Log.d(
595 Config.LOGTAG,
596 account.getJid().asBareJid()
597 + ": aborting connect because thread was interrupted");
598 return;
599 }
600 forceCloseSocket();
601 }
602 connect();
603 }
604
605 private void processStream() throws XmlPullParserException, IOException {
606 final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
607 this.mStreamCountDownLatch = streamCountDownLatch;
608 Tag nextTag = tagReader.readTag();
609 while (nextTag != null && !nextTag.isEnd("stream")) {
610 if (nextTag.isStart("error", Namespace.STREAMS)) {
611 processStreamError(tagReader.readElement(nextTag, StreamError.class));
612 } else if (nextTag.isStart("features", Namespace.STREAMS)) {
613 processStreamFeatures(nextTag);
614 } else if (nextTag.isStart("proceed", Namespace.TLS)) {
615 switchOverToTls(nextTag);
616 } else if (nextTag.isStart("failure", Namespace.TLS)) {
617 throw new StateChangingException(Account.State.TLS_ERROR);
618 } else if (!isSecure()) {
619 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
620 } else if (account.isOptionSet(Account.OPTION_REGISTER)
621 && nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
622 processIq(nextTag);
623 } else if (this.loginInfo == null) {
624 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
625 } else if (nextTag.isStart("success", Namespace.SASL)) {
626 processSuccess(tagReader.readElement(nextTag, Success.class));
627 break;
628 } else if (nextTag.isStart("success", Namespace.SASL_2)) {
629 processSuccess(
630 tagReader.readElement(
631 nextTag, im.conversations.android.xmpp.model.sasl2.Success.class));
632 } else if (nextTag.isStart("failure", Namespace.SASL)) {
633 final var failure = tagReader.readElement(nextTag, Failure.class);
634 processFailure(failure);
635 } else if (nextTag.isStart("failure", Namespace.SASL_2)) {
636 final var failure =
637 tagReader.readElement(
638 nextTag, im.conversations.android.xmpp.model.sasl2.Failure.class);
639 processFailure(failure);
640 } else if (nextTag.isStart("continue", Namespace.SASL_2)) {
641 // two step sasl2 - we don’t support this yet
642 throw new StateChangingException(Account.State.INCOMPATIBLE_CLIENT);
643 } else if (nextTag.isStart("challenge")) {
644 final Element challenge = tagReader.readElement(nextTag);
645 processChallenge(challenge);
646 } else if (!LoginInfo.isSuccess(this.loginInfo)) {
647 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
648 } else if (this.streamId != null
649 && nextTag.isStart("resumed", Namespace.STREAM_MANAGEMENT)) {
650 final Resumed resumed = tagReader.readElement(nextTag, Resumed.class);
651 processResumed(resumed);
652 } else if (nextTag.isStart("failed", Namespace.STREAM_MANAGEMENT)) {
653 final Failed failed = tagReader.readElement(nextTag, Failed.class);
654 processFailed(failed, true);
655 } else if (nextTag.isStart("iq", Namespace.JABBER_CLIENT)) {
656 processIq(nextTag);
657 } else if (!isBound) {
658 Log.d(
659 Config.LOGTAG,
660 account.getJid().asBareJid()
661 + ": server sent unexpected"
662 + nextTag.identifier());
663 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
664 } else if (nextTag.isStart("message", Namespace.JABBER_CLIENT)) {
665 processMessage(nextTag);
666 } else if (nextTag.isStart("presence", Namespace.JABBER_CLIENT)) {
667 processPresence(nextTag);
668 } else if (nextTag.isStart("enabled", Namespace.STREAM_MANAGEMENT)) {
669 final var enabled = tagReader.readElement(nextTag, Enabled.class);
670 processEnabled(enabled);
671 } else if (nextTag.isStart("r", Namespace.STREAM_MANAGEMENT)) {
672 tagReader.readElement(nextTag);
673 if (Config.EXTENDED_SM_LOGGING) {
674 Log.d(
675 Config.LOGTAG,
676 account.getJid().asBareJid()
677 + ": acknowledging stanza #"
678 + this.stanzasReceived);
679 }
680 final Ack ack = new Ack(this.stanzasReceived);
681 tagWriter.writeStanzaAsync(ack);
682 } else if (nextTag.isStart("a", Namespace.STREAM_MANAGEMENT)) {
683 boolean accountUiNeedsRefresh = false;
684 synchronized (NotificationService.CATCHUP_LOCK) {
685 if (mWaitingForSmCatchup.compareAndSet(true, false)) {
686 final int messageCount = mSmCatchupMessageCounter.get();
687 final int pendingIQs = packetCallbacks.size();
688 Log.d(
689 Config.LOGTAG,
690 account.getJid().asBareJid()
691 + ": SM catchup complete (messages="
692 + messageCount
693 + ", pending IQs="
694 + pendingIQs
695 + ")");
696 accountUiNeedsRefresh = true;
697 if (messageCount > 0) {
698 mXmppConnectionService
699 .getNotificationService()
700 .finishBacklog(true, account);
701 }
702 }
703 }
704 if (accountUiNeedsRefresh) {
705 mXmppConnectionService.updateAccountUi();
706 }
707 final var ack = tagReader.readElement(nextTag, Ack.class);
708 lastPacketReceived = SystemClock.elapsedRealtime();
709 final boolean acknowledgedMessages;
710 synchronized (this.mStanzaQueue) {
711 final Optional<Integer> serverSequence = ack.getHandled();
712 if (serverSequence.isPresent()) {
713 acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence.get());
714 } else {
715 acknowledgedMessages = false;
716 Log.d(
717 Config.LOGTAG,
718 account.getJid().asBareJid()
719 + ": server send ack without sequence number");
720 }
721 }
722 if (acknowledgedMessages) {
723 mXmppConnectionService.updateConversationUi();
724 }
725 } else {
726 Log.e(
727 Config.LOGTAG,
728 account.getJid().asBareJid()
729 + ": Encountered unknown stream element"
730 + nextTag.identifier());
731 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
732 }
733 nextTag = tagReader.readTag();
734 }
735 if (nextTag != null && nextTag.isEnd("stream")) {
736 streamCountDownLatch.countDown();
737 }
738 }
739
740 private void processChallenge(final Element challenge) throws IOException {
741 final SaslMechanism.Version version;
742 try {
743 version = SaslMechanism.Version.of(challenge);
744 } catch (final IllegalArgumentException e) {
745 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
746 }
747 final StreamElement response;
748 if (version == SaslMechanism.Version.SASL) {
749 response = new Response();
750 } else if (version == SaslMechanism.Version.SASL_2) {
751 response = new im.conversations.android.xmpp.model.sasl2.Response();
752 } else {
753 throw new AssertionError("Missing implementation for " + version);
754 }
755 final LoginInfo currentLoginInfo = this.loginInfo;
756 if (currentLoginInfo == null || LoginInfo.isSuccess(currentLoginInfo)) {
757 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
758 }
759 try {
760 response.setContent(
761 currentLoginInfo.saslMechanism.getResponse(
762 challenge.getContent(), sslSocketOrNull(socket)));
763 } catch (final SaslMechanism.AuthenticationException e) {
764 // TODO: Send auth abort tag.
765 Log.e(Config.LOGTAG, e.toString());
766 throw new StateChangingException(Account.State.UNAUTHORIZED);
767 }
768 tagWriter.writeElement(response);
769 }
770
771 private void processSuccess(final StreamElement element)
772 throws IOException, XmlPullParserException {
773 final LoginInfo currentLoginInfo = this.loginInfo;
774 final SaslMechanism currentSaslMechanism = LoginInfo.mechanism(currentLoginInfo);
775 if (currentLoginInfo == null || currentSaslMechanism == null) {
776 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
777 }
778 final SaslMechanism.Version version;
779 final String challenge;
780 if (element instanceof Success success) {
781 challenge = success.getContent();
782 version = SaslMechanism.Version.SASL;
783 } else if (element instanceof im.conversations.android.xmpp.model.sasl2.Success success) {
784 challenge = success.findChildContent("additional-data");
785 version = SaslMechanism.Version.SASL_2;
786 } else {
787 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
788 }
789 try {
790 currentLoginInfo.success(challenge, sslSocketOrNull(socket));
791 } catch (final SaslMechanism.AuthenticationException e) {
792 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": authentication failure ", e);
793 throw new StateChangingException(Account.State.UNAUTHORIZED);
794 }
795 Log.d(
796 Config.LOGTAG,
797 account.getJid().asBareJid().toString() + ": logged in (using " + version + ")");
798 if (SaslMechanism.pin(currentSaslMechanism)) {
799 account.setPinnedMechanism(currentSaslMechanism);
800 }
801 if (element instanceof im.conversations.android.xmpp.model.sasl2.Success success) {
802 final var authorizationJid = success.getAuthorizationIdentifier();
803 checkAssignedDomainOrThrow(authorizationJid);
804 Log.d(
805 Config.LOGTAG,
806 account.getJid().asBareJid()
807 + ": SASL 2.0 authorization identifier was "
808 + authorizationJid);
809 // TODO this should only happen when we used Bind 2
810 if (authorizationJid.isFullJid() && account.setJid(authorizationJid)) {
811 Log.d(
812 Config.LOGTAG,
813 account.getJid().asBareJid()
814 + ": jid changed during SASL 2.0. updating database");
815 }
816 final Bound bound = success.getExtension(Bound.class);
817 final Resumed resumed = success.getExtension(Resumed.class);
818 final Failed failed = success.getExtension(Failed.class);
819 final Element tokenWrapper = success.findChild("token", Namespace.FAST);
820 final String token = tokenWrapper == null ? null : tokenWrapper.getAttribute("token");
821 if (bound != null && resumed != null) {
822 Log.d(
823 Config.LOGTAG,
824 account.getJid().asBareJid()
825 + ": server sent bound and resumed in SASL2 success");
826 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
827 }
828 if (resumed != null && streamId != null) {
829 if (this.boundStreamFeatures != null) {
830 this.streamFeatures = this.boundStreamFeatures;
831 Log.d(
832 Config.LOGTAG,
833 "putting previous stream features back in place: "
834 + XmlHelper.printElementNames(this.boundStreamFeatures));
835 }
836 processResumed(resumed);
837 } else if (failed != null) {
838 processFailed(failed, false); // wait for new stream features
839 }
840 if (bound != null) {
841 clearIqCallbacks();
842 this.isBound = true;
843 processNopStreamFeatures();
844 this.boundStreamFeatures = this.streamFeatures;
845 final Enabled streamManagementEnabled = bound.getExtension(Enabled.class);
846 final Element carbonsEnabled = bound.findChild("enabled", Namespace.CARBONS);
847 final boolean waitForDisco;
848 if (streamManagementEnabled != null) {
849 resetOutboundStanzaQueue();
850 processEnabled(streamManagementEnabled);
851 waitForDisco = true;
852 } else {
853 // if we did not enable stream management in bind do it now
854 waitForDisco = enableStreamManagement();
855 }
856 final boolean negotiatedCarbons;
857 if (carbonsEnabled != null) {
858 negotiatedCarbons = true;
859 Log.d(
860 Config.LOGTAG,
861 account.getJid().asBareJid()
862 + ": successfully enabled carbons (via Bind 2.0)");
863 features.carbonsEnabled = true;
864 } else if (currentLoginInfo.inlineBindFeatures != null
865 && currentLoginInfo.inlineBindFeatures.contains(Namespace.CARBONS)) {
866 negotiatedCarbons = true;
867 Log.d(
868 Config.LOGTAG,
869 account.getJid().asBareJid()
870 + ": successfully enabled carbons (via Bind 2.0/implicit)");
871 features.carbonsEnabled = true;
872 } else {
873 negotiatedCarbons = false;
874 }
875 sendPostBindInitialization(waitForDisco, negotiatedCarbons);
876 }
877 final HashedToken.Mechanism tokenMechanism;
878 if (SaslMechanism.hashedToken(currentSaslMechanism)) {
879 tokenMechanism = ((HashedToken) currentSaslMechanism).getTokenMechanism();
880 } else if (this.hashTokenRequest != null) {
881 tokenMechanism = this.hashTokenRequest;
882 } else {
883 tokenMechanism = null;
884 }
885 if (tokenMechanism != null && !Strings.isNullOrEmpty(token)) {
886 if (ChannelBinding.priority(tokenMechanism.channelBinding)
887 >= ChannelBindingMechanism.getPriority(currentSaslMechanism)) {
888 this.account.setFastToken(tokenMechanism, token);
889 Log.d(
890 Config.LOGTAG,
891 account.getJid().asBareJid()
892 + ": storing hashed token "
893 + tokenMechanism);
894 } else {
895 Log.d(
896 Config.LOGTAG,
897 account.getJid().asBareJid()
898 + ": not accepting hashed token "
899 + tokenMechanism.name()
900 + " for log in mechanism "
901 + currentSaslMechanism.getMechanism());
902 this.account.resetFastToken();
903 }
904 } else if (this.hashTokenRequest != null) {
905 Log.w(
906 Config.LOGTAG,
907 account.getJid().asBareJid()
908 + ": no response to our hashed token request "
909 + this.hashTokenRequest);
910 }
911 }
912 mXmppConnectionService.databaseBackend.updateAccount(account);
913 this.quickStartInProgress = false;
914 if (version == SaslMechanism.Version.SASL) {
915 tagReader.reset();
916 sendStartStream(false, true);
917 final Tag tag = tagReader.readTag();
918 if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
919 processStream();
920 return;
921 } else {
922 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
923 }
924 }
925 }
926
927 private void resetOutboundStanzaQueue() {
928 synchronized (this.mStanzaQueue) {
929 final ImmutableList.Builder<Stanza> intermediateStanzasBuilder =
930 new ImmutableList.Builder<>();
931 if (Config.EXTENDED_SM_LOGGING) {
932 Log.d(
933 Config.LOGTAG,
934 account.getJid().asBareJid()
935 + ": stanzas sent before auth: "
936 + this.stanzasSentBeforeAuthentication);
937 }
938 for (int i = this.stanzasSentBeforeAuthentication + 1; i <= this.stanzasSent; ++i) {
939 final Stanza stanza = this.mStanzaQueue.get(i);
940 if (stanza != null) {
941 intermediateStanzasBuilder.add(stanza);
942 }
943 }
944 this.mStanzaQueue.clear();
945 final var intermediateStanzas = intermediateStanzasBuilder.build();
946 for (int i = 0; i < intermediateStanzas.size(); ++i) {
947 this.mStanzaQueue.append(i + 1, intermediateStanzas.get(i));
948 }
949 this.stanzasSent = intermediateStanzas.size();
950 if (Config.EXTENDED_SM_LOGGING) {
951 Log.d(
952 Config.LOGTAG,
953 account.getJid().asBareJid()
954 + ": resetting outbound stanza queue to "
955 + this.stanzasSent);
956 }
957 }
958 }
959
960 private void processNopStreamFeatures() throws IOException {
961 final Tag tag = tagReader.readTag();
962 if (tag != null && tag.isStart("features", Namespace.STREAMS)) {
963 this.streamFeatures =
964 tagReader.readElement(
965 tag, im.conversations.android.xmpp.model.streams.Features.class);
966 Log.d(
967 Config.LOGTAG,
968 account.getJid().asBareJid()
969 + ": processed NOP stream features after success: "
970 + XmlHelper.printElementNames(this.streamFeatures));
971 } else {
972 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received " + tag);
973 Log.d(
974 Config.LOGTAG,
975 account.getJid().asBareJid()
976 + ": server did not send stream features after SASL2 success");
977 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
978 }
979 }
980
981 private void processFailure(final AuthenticationFailure failure) throws IOException {
982 final SaslMechanism.Version version;
983 try {
984 version = SaslMechanism.Version.of(failure);
985 } catch (final IllegalArgumentException e) {
986 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
987 }
988 Log.d(Config.LOGTAG, failure.toString());
989 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
990 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
991 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resetting token");
992 account.resetFastToken();
993 mXmppConnectionService.databaseBackend.updateAccount(account);
994 }
995 final var errorCondition = failure.getErrorCondition();
996 if (errorCondition instanceof SaslError.InvalidMechanism
997 || errorCondition instanceof SaslError.MechanismTooWeak) {
998 Log.d(
999 Config.LOGTAG,
1000 account.getJid().asBareJid()
1001 + ": invalid or too weak mechanism. resetting quick start");
1002 if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false)) {
1003 mXmppConnectionService.databaseBackend.updateAccount(account);
1004 }
1005 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1006 } else if (errorCondition instanceof SaslError.TemporaryAuthFailure) {
1007 throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
1008 } else if (errorCondition instanceof SaslError.AccountDisabled) {
1009 final String text = failure.getText();
1010 if (Strings.isNullOrEmpty(text)) {
1011 throw new StateChangingException(Account.State.UNAUTHORIZED);
1012 }
1013 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
1014 if (matcher.find()) {
1015 final HttpUrl url;
1016 try {
1017 url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
1018 } catch (final IllegalArgumentException e) {
1019 throw new StateChangingException(Account.State.UNAUTHORIZED);
1020 }
1021 if (url.isHttps()) {
1022 this.redirectionUrl = url;
1023 throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
1024 }
1025 }
1026 }
1027 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1028 Log.d(
1029 Config.LOGTAG,
1030 account.getJid().asBareJid()
1031 + ": fast authentication failed. falling back to regular"
1032 + " authentication");
1033 authenticate();
1034 } else {
1035 throw new StateChangingException(Account.State.UNAUTHORIZED);
1036 }
1037 }
1038
1039 private static SSLSocket sslSocketOrNull(final Socket socket) {
1040 if (socket instanceof SSLSocket) {
1041 return (SSLSocket) socket;
1042 } else {
1043 return null;
1044 }
1045 }
1046
1047 private void processEnabled(final Enabled enabled) {
1048 final StreamId streamId = getStreamId(enabled);
1049 if (streamId == null) {
1050 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream management enabled");
1051 } else {
1052 Log.d(
1053 Config.LOGTAG,
1054 account.getJid().asBareJid()
1055 + ": stream management enabled. resume at: "
1056 + streamId.location);
1057 }
1058 this.streamId = streamId;
1059 this.stanzasReceived = 0;
1060 this.inSmacksSession = true;
1061 final var r = new Request();
1062 tagWriter.writeStanzaAsync(r);
1063 }
1064
1065 @Nullable
1066 private StreamId getStreamId(final Enabled enabled) {
1067 final Optional<String> id = enabled.getResumeId();
1068 final String locationAttribute = enabled.getLocation();
1069 final Resolver.Result currentResolverResult = this.currentResolverResult;
1070 final Resolver.Result location;
1071 if (Strings.isNullOrEmpty(locationAttribute) || currentResolverResult == null) {
1072 location = null;
1073 } else {
1074 location = currentResolverResult.seeOtherHost(locationAttribute);
1075 }
1076 return id.isPresent() ? new StreamId(id.get(), location) : null;
1077 }
1078
1079 private void processResumed(final Resumed resumed) throws StateChangingException {
1080 final var pendingResumeId = this.pendingResumeId.pop();
1081 final var prevId = resumed.getPrevId();
1082 if (prevId == null || !prevId.equals(pendingResumeId)) {
1083 Log.d(
1084 Config.LOGTAG,
1085 account.getJid().asBareJid()
1086 + ": server tried resume with unknown id "
1087 + prevId);
1088 resetStreamId();
1089 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1090 }
1091 this.inSmacksSession = true;
1092 this.isBound = true;
1093 this.tagWriter.writeStanzaAsync(new Request());
1094 lastPacketReceived = SystemClock.elapsedRealtime();
1095 final Optional<Integer> h = resumed.getHandled();
1096 final int serverCount;
1097 if (h.isPresent()) {
1098 serverCount = h.get();
1099 } else {
1100 resetStreamId();
1101 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1102 }
1103 final ArrayList<Stanza> failedStanzas = new ArrayList<>();
1104 final boolean acknowledgedMessages;
1105 synchronized (this.mStanzaQueue) {
1106 if (serverCount < stanzasSent) {
1107 Log.d(
1108 Config.LOGTAG,
1109 account.getJid().asBareJid() + ": session resumed with lost packages");
1110 stanzasSent = serverCount;
1111 } else {
1112 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": session resumed");
1113 }
1114 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
1115 for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
1116 failedStanzas.add(mStanzaQueue.valueAt(i));
1117 }
1118 mStanzaQueue.clear();
1119 }
1120 if (acknowledgedMessages) {
1121 mXmppConnectionService.updateConversationUi();
1122 }
1123 Log.d(
1124 Config.LOGTAG,
1125 account.getJid().asBareJid() + ": resending " + failedStanzas.size() + " stanzas");
1126 for (final Stanza packet : failedStanzas) {
1127 if (packet instanceof im.conversations.android.xmpp.model.stanza.Message message) {
1128 mXmppConnectionService.markMessage(
1129 account,
1130 message.getTo().asBareJid(),
1131 message.getId(),
1132 Message.STATUS_UNSEND);
1133 }
1134 sendPacket(packet);
1135 }
1136 if (mWaitForDisco.get()) {
1137 this.lastDiscoStarted = SystemClock.elapsedRealtime();
1138 Log.d(
1139 Config.LOGTAG,
1140 account.getJid().asBareJid() + ": awaiting disco results after resume");
1141 changeStatus(Account.State.CONNECTING);
1142 } else {
1143 changeStatusToOnline();
1144 }
1145 }
1146
1147 private void changeStatusToOnline() {
1148 Log.d(
1149 Config.LOGTAG,
1150 account.getJid().asBareJid() + ": online with resource " + account.getResource());
1151 changeStatus(Account.State.ONLINE);
1152 }
1153
1154 private void processFailed(final Failed failed, final boolean sendBindRequest) {
1155 final Optional<Integer> serverCount = failed.getHandled();
1156 if (serverCount.isPresent()) {
1157 Log.d(
1158 Config.LOGTAG,
1159 account.getJid().asBareJid()
1160 + ": resumption failed but server acknowledged stanza #"
1161 + serverCount.get());
1162 final boolean acknowledgedMessages;
1163 synchronized (this.mStanzaQueue) {
1164 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount.get());
1165 }
1166 if (acknowledgedMessages) {
1167 mXmppConnectionService.updateConversationUi();
1168 }
1169 } else {
1170 Log.d(
1171 Config.LOGTAG,
1172 account.getJid().asBareJid()
1173 + ": resumption failed ("
1174 + XmlHelper.print(failed.getChildren())
1175 + ")");
1176 }
1177 resetStreamId();
1178 if (sendBindRequest) {
1179 sendBindRequest();
1180 }
1181 }
1182
1183 private boolean acknowledgeStanzaUpTo(final int serverCount) {
1184 if (serverCount > stanzasSent) {
1185 Log.e(
1186 Config.LOGTAG,
1187 "server acknowledged more stanzas than we sent. serverCount="
1188 + serverCount
1189 + ", ourCount="
1190 + stanzasSent);
1191 }
1192 boolean acknowledgedMessages = false;
1193 for (int i = 0; i < mStanzaQueue.size(); ++i) {
1194 if (serverCount >= mStanzaQueue.keyAt(i)) {
1195 if (Config.EXTENDED_SM_LOGGING) {
1196 Log.d(
1197 Config.LOGTAG,
1198 account.getJid().asBareJid()
1199 + ": server acknowledged stanza #"
1200 + mStanzaQueue.keyAt(i));
1201 }
1202 final Stanza stanza = mStanzaQueue.valueAt(i);
1203 if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message packet
1204 && acknowledgedListener != null) {
1205 final String id = packet.getId();
1206 final Jid to = packet.getTo();
1207 if (id != null && to != null) {
1208 acknowledgedMessages |=
1209 acknowledgedListener.onMessageAcknowledged(account, to, id);
1210 }
1211 }
1212 mStanzaQueue.removeAt(i);
1213 i--;
1214 }
1215 }
1216 return acknowledgedMessages;
1217 }
1218
1219 private <S extends Stanza> @NonNull S processPacket(final Tag currentTag, final Class<S> clazz)
1220 throws IOException {
1221 final S stanza = tagReader.readElement(currentTag, clazz);
1222 if (stanzasReceived == Integer.MAX_VALUE) {
1223 resetStreamId();
1224 throw new IOException("time to restart the session. cant handle >2 billion pcks");
1225 }
1226 if (inSmacksSession) {
1227 ++stanzasReceived;
1228 } else if (features.sm()) {
1229 Log.d(
1230 Config.LOGTAG,
1231 account.getJid().asBareJid()
1232 + ": not counting stanza("
1233 + stanza.getClass().getSimpleName()
1234 + "). Not in smacks session.");
1235 }
1236 lastPacketReceived = SystemClock.elapsedRealtime();
1237 if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
1238 Log.d(Config.LOGTAG, "[background stanza] " + stanza);
1239 }
1240 return stanza;
1241 }
1242
1243 private void processIq(final Tag currentTag) throws IOException {
1244 final Iq packet = processPacket(currentTag, Iq.class);
1245 if (packet.isInvalid()) {
1246 Log.e(
1247 Config.LOGTAG,
1248 "encountered invalid iq from='"
1249 + packet.getFrom()
1250 + "' to='"
1251 + packet.getTo()
1252 + "'");
1253 return;
1254 }
1255 if (Thread.currentThread().isInterrupted()) {
1256 Log.d(
1257 Config.LOGTAG,
1258 account.getJid().asBareJid() + "Not processing iq. Thread was interrupted");
1259 return;
1260 }
1261 if (packet.hasExtension(Jingle.class) && packet.getType() == Iq.Type.SET && isBound) {
1262 if (this.jingleListener != null) {
1263 this.jingleListener.onJinglePacketReceived(account, packet);
1264 }
1265 } else {
1266 final var callback = getIqPacketReceivedCallback(packet);
1267 if (callback == null) {
1268 Log.d(
1269 Config.LOGTAG,
1270 account.getJid().asBareJid().toString()
1271 + ": no callback registered for IQ from "
1272 + packet.getFrom());
1273 return;
1274 }
1275 try {
1276 callback.accept(packet);
1277 } catch (final StateChangingError error) {
1278 throw new StateChangingException(error.state);
1279 }
1280 }
1281 }
1282
1283 private Consumer<Iq> getIqPacketReceivedCallback(final Iq stanza)
1284 throws StateChangingException {
1285 final boolean isRequest =
1286 stanza.getType() == Iq.Type.GET || stanza.getType() == Iq.Type.SET;
1287 if (isRequest) {
1288 if (isBound) {
1289 return this.unregisteredIqListener;
1290 } else {
1291 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1292 }
1293 } else {
1294 synchronized (this.packetCallbacks) {
1295 final var pair = packetCallbacks.get(stanza.getId());
1296 if (pair == null) {
1297 return null;
1298 }
1299 if (pair.first.toServer(account)) {
1300 if (stanza.fromServer(account)) {
1301 packetCallbacks.remove(stanza.getId());
1302 return pair.second;
1303 } else {
1304 Log.e(
1305 Config.LOGTAG,
1306 account.getJid().asBareJid().toString()
1307 + ": ignoring spoofed iq packet");
1308 }
1309 } else {
1310 if (stanza.getFrom() != null && stanza.getFrom().equals(pair.first.getTo())) {
1311 packetCallbacks.remove(stanza.getId());
1312 return pair.second;
1313 } else {
1314 Log.e(
1315 Config.LOGTAG,
1316 account.getJid().asBareJid().toString()
1317 + ": ignoring spoofed iq packet");
1318 }
1319 }
1320 }
1321 }
1322 return null;
1323 }
1324
1325 private void processMessage(final Tag currentTag) throws IOException {
1326 final var packet =
1327 processPacket(currentTag, im.conversations.android.xmpp.model.stanza.Message.class);
1328 if (packet.isInvalid()) {
1329 Log.e(
1330 Config.LOGTAG,
1331 "encountered invalid message from='"
1332 + packet.getFrom()
1333 + "' to='"
1334 + packet.getTo()
1335 + "'");
1336 return;
1337 }
1338 if (Thread.currentThread().isInterrupted()) {
1339 Log.d(
1340 Config.LOGTAG,
1341 account.getJid().asBareJid()
1342 + "Not processing message. Thread was interrupted");
1343 return;
1344 }
1345 this.messageListener.accept(packet);
1346 }
1347
1348 private void processPresence(final Tag currentTag) throws IOException {
1349 final var packet = processPacket(currentTag, Presence.class);
1350 if (packet.isInvalid()) {
1351 Log.e(
1352 Config.LOGTAG,
1353 "encountered invalid presence from='"
1354 + packet.getFrom()
1355 + "' to='"
1356 + packet.getTo()
1357 + "'");
1358 return;
1359 }
1360 if (Thread.currentThread().isInterrupted()) {
1361 Log.d(
1362 Config.LOGTAG,
1363 account.getJid().asBareJid()
1364 + "Not processing presence. Thread was interrupted");
1365 return;
1366 }
1367 this.presenceListener.accept(packet);
1368 }
1369
1370 private void sendStartTLS() throws IOException {
1371 tagWriter.writeElement(new StartTls());
1372 }
1373
1374 private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
1375 tagReader.readElement(currentTag, Proceed.class);
1376 final Socket socket = this.socket;
1377 final SSLSocket sslSocket = upgradeSocketToTls(socket);
1378 this.socket = sslSocket;
1379 this.tagReader.setInputStream(sslSocket.getInputStream());
1380 this.tagWriter.setOutputStream(sslSocket.getOutputStream());
1381 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1382 final boolean quickStart;
1383 try {
1384 quickStart = establishStream(SSLSockets.version(sslSocket));
1385 } catch (final InterruptedException e) {
1386 return;
1387 }
1388 if (quickStart) {
1389 this.quickStartInProgress = true;
1390 }
1391 features.encryptionEnabled = true;
1392 final Tag tag = tagReader.readTag();
1393 if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1394 SSLSockets.log(account, sslSocket);
1395 processStream();
1396 } else {
1397 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1398 }
1399 sslSocket.close();
1400 }
1401
1402 private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1403 final SSLSocketFactory sslSocketFactory;
1404 try {
1405 sslSocketFactory = getSSLSocketFactory();
1406 } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1407 throw new StateChangingException(Account.State.TLS_ERROR);
1408 }
1409 final InetAddress address = socket.getInetAddress();
1410 final SSLSocket sslSocket =
1411 (SSLSocket)
1412 sslSocketFactory.createSocket(
1413 socket, address.getHostAddress(), socket.getPort(), true);
1414 SSLSockets.setSecurity(sslSocket);
1415 SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1416 SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1417 final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1418 try {
1419 if (!xmppDomainVerifier.verify(
1420 account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1421 Log.d(
1422 Config.LOGTAG,
1423 account.getJid().asBareJid()
1424 + ": TLS certificate domain verification failed");
1425 FileBackend.close(sslSocket);
1426 throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1427 }
1428 } catch (final SSLPeerUnverifiedException e) {
1429 FileBackend.close(sslSocket);
1430 throw new StateChangingException(Account.State.TLS_ERROR);
1431 }
1432 return sslSocket;
1433 }
1434
1435 private void processStreamFeatures(final Tag currentTag) throws IOException {
1436 this.streamFeatures =
1437 tagReader.readElement(
1438 currentTag, im.conversations.android.xmpp.model.streams.Features.class);
1439 final boolean isSecure = isSecure();
1440 final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1441 if (this.quickStartInProgress) {
1442 if (this.streamFeatures.hasStreamFeature(Authentication.class)) {
1443 Log.d(
1444 Config.LOGTAG,
1445 account.getJid().asBareJid()
1446 + ": quick start in progress. ignoring features: "
1447 + XmlHelper.printElementNames(this.streamFeatures));
1448 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1449 return;
1450 }
1451 if (isFastTokenAvailable(this.streamFeatures.getExtension(Authentication.class))) {
1452 Log.d(
1453 Config.LOGTAG,
1454 account.getJid().asBareJid()
1455 + ": fast token available; resetting quick start");
1456 account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1457 mXmppConnectionService.databaseBackend.updateAccount(account);
1458 }
1459 return;
1460 }
1461 Log.d(
1462 Config.LOGTAG,
1463 account.getJid().asBareJid()
1464 + ": server lost support for SASL 2. quick start not possible");
1465 this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1466 mXmppConnectionService.databaseBackend.updateAccount(account);
1467 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1468 }
1469 if (this.streamFeatures.hasExtension(StartTls.class) && !features.encryptionEnabled) {
1470 sendStartTLS();
1471 } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1472 && account.isOptionSet(Account.OPTION_REGISTER)) {
1473 if (isSecure) {
1474 register();
1475 } else {
1476 Log.d(
1477 Config.LOGTAG,
1478 account.getJid().asBareJid()
1479 + ": unable to find STARTTLS for registration process "
1480 + XmlHelper.printElementNames(this.streamFeatures));
1481 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1482 }
1483 } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1484 && account.isOptionSet(Account.OPTION_REGISTER)) {
1485 throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1486 } else if (this.streamFeatures.hasStreamFeature(Authentication.class)
1487 && shouldAuthenticate
1488 && isSecure) {
1489 authenticate(SaslMechanism.Version.SASL_2);
1490 } else if (this.streamFeatures.hasStreamFeature(Mechanisms.class)
1491 && shouldAuthenticate
1492 && isSecure) {
1493 authenticate(SaslMechanism.Version.SASL);
1494 } else if (this.streamFeatures.streamManagement()
1495 && isSecure
1496 && LoginInfo.isSuccess(loginInfo)
1497 && streamId != null
1498 && !inSmacksSession) {
1499 if (Config.EXTENDED_SM_LOGGING) {
1500 Log.d(
1501 Config.LOGTAG,
1502 account.getJid().asBareJid()
1503 + ": resuming after stanza #"
1504 + stanzasReceived);
1505 }
1506 final var streamId = this.streamId.id;
1507 final var resume = new Resume(streamId, stanzasReceived);
1508 prepareForResume(streamId);
1509 this.tagWriter.writeStanzaAsync(resume);
1510 } else if (needsBinding) {
1511 if (this.streamFeatures.hasChild("bind", Namespace.BIND)
1512 && isSecure
1513 && LoginInfo.isSuccess(loginInfo)) {
1514 sendBindRequest();
1515 } else {
1516 Log.d(
1517 Config.LOGTAG,
1518 account.getJid().asBareJid()
1519 + ": unable to find bind feature "
1520 + XmlHelper.printElementNames(this.streamFeatures));
1521 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1522 }
1523 } else {
1524 Log.d(
1525 Config.LOGTAG,
1526 account.getJid().asBareJid()
1527 + ": received NOP stream features: "
1528 + XmlHelper.printElementNames(this.streamFeatures));
1529 }
1530 }
1531
1532 private void authenticate() throws IOException {
1533 final boolean isSecure = isSecure();
1534 if (isSecure && this.streamFeatures.hasStreamFeature(Authentication.class)) {
1535 authenticate(SaslMechanism.Version.SASL_2);
1536 } else if (isSecure && this.streamFeatures.hasStreamFeature(Mechanisms.class)) {
1537 authenticate(SaslMechanism.Version.SASL);
1538 } else {
1539 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1540 }
1541 }
1542
1543 private boolean isSecure() {
1544 return features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1545 }
1546
1547 private void authenticate(final SaslMechanism.Version version) throws IOException {
1548 final AuthenticationStreamFeature authElement;
1549 if (version == SaslMechanism.Version.SASL) {
1550 authElement = this.streamFeatures.getExtension(Mechanisms.class);
1551 } else {
1552 authElement = this.streamFeatures.getExtension(Authentication.class);
1553 }
1554 final Collection<String> mechanisms = authElement.getMechanismNames();
1555 final Element cbElement =
1556 this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1557 final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1558 final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1559 final SaslMechanism saslMechanism =
1560 factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1561 this.validate(saslMechanism, mechanisms);
1562 final boolean quickStartAvailable;
1563 final String firstMessage =
1564 saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1565 final boolean usingFast = SaslMechanism.hashedToken(saslMechanism);
1566 final AuthenticationRequest authenticate;
1567 final LoginInfo loginInfo;
1568 if (version == SaslMechanism.Version.SASL) {
1569 authenticate = new Auth();
1570 if (!Strings.isNullOrEmpty(firstMessage)) {
1571 authenticate.setContent(firstMessage);
1572 }
1573 quickStartAvailable = false;
1574 loginInfo = new LoginInfo(saslMechanism, version, Collections.emptyList());
1575 } else if (version == SaslMechanism.Version.SASL_2) {
1576 final Authentication authentication = (Authentication) authElement;
1577 final var inline = authentication.getInline();
1578 final boolean sm = inline != null && inline.hasExtension(StreamManagement.class);
1579 final HashedToken.Mechanism hashTokenRequest;
1580 if (usingFast) {
1581 hashTokenRequest = null;
1582 } else if (inline != null) {
1583 hashTokenRequest =
1584 HashedToken.Mechanism.best(
1585 inline.getFastMechanisms(), SSLSockets.version(this.socket));
1586 // TODO warn or fail early if channel binding priority isn’t high enough compared to
1587 // login mechanism
1588 // ChannelBinding.priority(hashTokenRequest.channelBinding)
1589 // <
1590 // ChannelBindingMechanism.getPriority(saslMechanism)
1591 } else {
1592 hashTokenRequest = null;
1593 }
1594 final Collection<String> bindFeatures = Bind2.features(inline);
1595 quickStartAvailable =
1596 sm
1597 && bindFeatures != null
1598 && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1599 if (bindFeatures != null) {
1600 try {
1601 mXmppConnectionService.restoredFromDatabaseLatch.await();
1602 } catch (final InterruptedException e) {
1603 Log.d(
1604 Config.LOGTAG,
1605 account.getJid().asBareJid()
1606 + ": interrupted while waiting for DB restore during SASL2"
1607 + " bind");
1608 return;
1609 }
1610 }
1611 loginInfo = new LoginInfo(saslMechanism, version, bindFeatures);
1612 this.hashTokenRequest = hashTokenRequest;
1613 authenticate =
1614 generateAuthenticationRequest(
1615 firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1616 } else {
1617 throw new AssertionError("Missing implementation for " + version);
1618 }
1619 this.loginInfo = loginInfo;
1620 if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1621 mXmppConnectionService.databaseBackend.updateAccount(account);
1622 }
1623
1624 Log.d(
1625 Config.LOGTAG,
1626 account.getJid().toString()
1627 + ": Authenticating with "
1628 + version
1629 + "/"
1630 + LoginInfo.mechanism(loginInfo).getMechanism());
1631 authenticate.setMechanism(LoginInfo.mechanism(loginInfo));
1632 synchronized (this.mStanzaQueue) {
1633 this.stanzasSentBeforeAuthentication = this.stanzasSent;
1634 tagWriter.writeElement(authenticate);
1635 }
1636 }
1637
1638 private static boolean isFastTokenAvailable(final Authentication authentication) {
1639 final var inline = authentication == null ? null : authentication.getInline();
1640 return inline != null && inline.hasExtension(Fast.class);
1641 }
1642
1643 private void validate(
1644 final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms)
1645 throws StateChangingException {
1646 if (saslMechanism == null) {
1647 Log.d(
1648 Config.LOGTAG,
1649 account.getJid().asBareJid()
1650 + ": unable to find supported SASL mechanism in "
1651 + mechanisms);
1652 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1653 }
1654 checkRequireChannelBinding(saslMechanism);
1655 if (SaslMechanism.hashedToken(saslMechanism)) {
1656 return;
1657 }
1658 final int pinnedMechanism = account.getPinnedMechanismPriority();
1659 if (pinnedMechanism > saslMechanism.getPriority()) {
1660 Log.e(
1661 Config.LOGTAG,
1662 "Auth failed. Authentication mechanism "
1663 + saslMechanism.getMechanism()
1664 + " has lower priority ("
1665 + saslMechanism.getPriority()
1666 + ") than pinned priority ("
1667 + pinnedMechanism
1668 + "). Possible downgrade attack?");
1669 throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1670 }
1671 }
1672
1673 private void checkRequireChannelBinding(@NonNull final SaslMechanism mechanism)
1674 throws StateChangingException {
1675 if (appSettings.isRequireChannelBinding()) {
1676 if (mechanism instanceof ChannelBindingMechanism) {
1677 return;
1678 }
1679 Log.d(Config.LOGTAG, account.getJid() + ": server did not offer channel binding");
1680 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1681 }
1682 }
1683
1684 private void checkAssignedDomainOrThrow(final Jid jid) throws StateChangingException {
1685 if (jid == null) {
1686 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": bind response is missing jid");
1687 throw new StateChangingException(Account.State.BIND_FAILURE);
1688 }
1689 final var current = this.account.getJid().getDomain();
1690 if (jid.getDomain().equals(current)) {
1691 return;
1692 }
1693 Log.d(
1694 Config.LOGTAG,
1695 account.getJid().asBareJid()
1696 + ": server tried to re-assign domain to "
1697 + jid.getDomain());
1698 throw new StateChangingException(Account.State.BIND_FAILURE);
1699 }
1700
1701 private void checkAssignedDomain(final Jid jid) {
1702 try {
1703 checkAssignedDomainOrThrow(jid);
1704 } catch (final StateChangingException e) {
1705 throw new StateChangingError(e.state);
1706 }
1707 }
1708
1709 private AuthenticationRequest generateAuthenticationRequest(
1710 final String firstMessage, final boolean usingFast) {
1711 return generateAuthenticationRequest(
1712 firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1713 }
1714
1715 private AuthenticationRequest generateAuthenticationRequest(
1716 final String firstMessage,
1717 final boolean usingFast,
1718 final HashedToken.Mechanism hashedTokenRequest,
1719 final Collection<String> bind,
1720 final boolean inlineStreamManagement) {
1721 final var authenticate = new Authenticate();
1722 if (!Strings.isNullOrEmpty(firstMessage)) {
1723 authenticate.addChild("initial-response").setContent(firstMessage);
1724 }
1725 final var userAgent =
1726 authenticate.addExtension(
1727 new UserAgent(
1728 AccountUtils.publicDeviceId(
1729 account, appSettings.getInstallationId())));
1730 userAgent.setSoftware(
1731 String.format("%s %s", BuildConfig.APP_NAME, BuildConfig.VERSION_NAME));
1732 if (!PhoneHelper.isEmulator()) {
1733 userAgent.setDevice(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1734 }
1735 // do not include bind if 'inlineStreamManagement' is missing and we have a streamId
1736 // (because we would rather just do a normal SM/resume)
1737 final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1738 if (bind != null && mayAttemptBind) {
1739 authenticate.addChild(generateBindRequest(bind));
1740 }
1741 if (inlineStreamManagement && streamId != null) {
1742 final var streamId = this.streamId.id;
1743 final var resume = new Resume(streamId, stanzasReceived);
1744 prepareForResume(streamId);
1745 authenticate.addExtension(resume);
1746 }
1747 if (hashedTokenRequest != null) {
1748 authenticate.addExtension(new RequestToken(hashedTokenRequest));
1749 }
1750 if (usingFast) {
1751 authenticate.addExtension(new Fast());
1752 }
1753 return authenticate;
1754 }
1755
1756 private void prepareForResume(final String streamId) {
1757 this.mSmCatchupMessageCounter.set(0);
1758 this.mWaitingForSmCatchup.set(true);
1759 this.pendingResumeId.push(streamId);
1760 }
1761
1762 private Bind generateBindRequest(final Collection<String> bindFeatures) {
1763 Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1764 final var bind = new Bind();
1765 bind.setTag(BuildConfig.APP_NAME);
1766 if (bindFeatures.contains(Namespace.CARBONS)) {
1767 bind.addExtension(new im.conversations.android.xmpp.model.carbons.Enable());
1768 }
1769 if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1770 bind.addExtension(new Enable());
1771 }
1772 return bind;
1773 }
1774
1775 private void register() {
1776 final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1777 if (preAuth != null && features.invite()) {
1778 final Iq preAuthRequest = new Iq(Iq.Type.SET);
1779 preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1780 sendUnmodifiedIqPacket(
1781 preAuthRequest,
1782 (response) -> {
1783 if (response.getType() == Iq.Type.RESULT) {
1784 sendRegistryRequest();
1785 } else {
1786 final String error = response.getErrorCondition();
1787 Log.d(
1788 Config.LOGTAG,
1789 account.getJid().asBareJid()
1790 + ": failed to pre auth. "
1791 + error);
1792 throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1793 }
1794 },
1795 true);
1796 } else {
1797 sendRegistryRequest();
1798 }
1799 }
1800
1801 private void sendRegistryRequest() {
1802 final Iq register = new Iq(Iq.Type.GET);
1803 register.query(Namespace.REGISTER);
1804 register.setTo(account.getDomain());
1805 sendUnmodifiedIqPacket(
1806 register,
1807 (packet) -> {
1808 if (packet.getType() == Iq.Type.TIMEOUT) {
1809 return;
1810 }
1811 if (packet.getType() == Iq.Type.ERROR) {
1812 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1813 }
1814 final Element query = packet.query(Namespace.REGISTER);
1815 if (query.hasChild("username") && (query.hasChild("password"))) {
1816 final Iq register1 = new Iq(Iq.Type.SET);
1817 final Element username =
1818 new Element("username").setContent(account.getUsername());
1819 final Element password =
1820 new Element("password").setContent(account.getPassword());
1821 register1.query(Namespace.REGISTER).addChild(username);
1822 register1.query().addChild(password);
1823 register1.setFrom(account.getJid().asBareJid());
1824 sendUnmodifiedIqPacket(register1, this::processRegistrationResponse, true);
1825 } else if (query.hasChild("x", Namespace.DATA)) {
1826 final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1827 final Element blob = query.findChild("data", "urn:xmpp:bob");
1828 final String id = packet.getId();
1829 InputStream is;
1830 if (blob != null) {
1831 try {
1832 final String base64Blob = blob.getContent();
1833 final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1834 is = new ByteArrayInputStream(strBlob);
1835 } catch (Exception e) {
1836 is = null;
1837 }
1838 } else {
1839 final boolean useTor =
1840 mXmppConnectionService.useTorToConnect() || account.isOnion();
1841 try {
1842 final String url = data.getValue("url");
1843 final String fallbackUrl = data.getValue("captcha-fallback-url");
1844 if (url != null) {
1845 is = HttpConnectionManager.open(url, useTor);
1846 } else if (fallbackUrl != null) {
1847 is = HttpConnectionManager.open(fallbackUrl, useTor);
1848 } else {
1849 is = null;
1850 }
1851 } catch (final IOException e) {
1852 Log.d(
1853 Config.LOGTAG,
1854 account.getJid().asBareJid() + ": unable to fetch captcha",
1855 e);
1856 is = null;
1857 }
1858 }
1859
1860 if (is != null) {
1861 Bitmap captcha = BitmapFactory.decodeStream(is);
1862 try {
1863 if (mXmppConnectionService.displayCaptchaRequest(
1864 account, id, data, captcha)) {
1865 return;
1866 }
1867 } catch (Exception e) {
1868 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1869 }
1870 }
1871 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1872 } else if (query.hasChild("instructions")
1873 || query.hasChild("x", Namespace.OOB)) {
1874 final String instructions = query.findChildContent("instructions");
1875 final Element oob = query.findChild("x", Namespace.OOB);
1876 final String url = oob == null ? null : oob.findChildContent("url");
1877 if (url != null) {
1878 setAccountCreationFailed(url);
1879 } else if (instructions != null) {
1880 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1881 if (matcher.find()) {
1882 setAccountCreationFailed(
1883 instructions.substring(matcher.start(), matcher.end()));
1884 }
1885 }
1886 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1887 }
1888 },
1889 true);
1890 }
1891
1892 public void sendCreateAccountWithCaptchaPacket(final String id, final Data data) {
1893 final Iq request = IqGenerator.generateCreateAccountWithCaptcha(account, id, data);
1894 this.sendUnmodifiedIqPacket(request, this::processRegistrationResponse, true);
1895 }
1896
1897 private void processRegistrationResponse(final Iq response) {
1898 if (response.getType() == Iq.Type.RESULT) {
1899 account.setOption(Account.OPTION_REGISTER, false);
1900 Log.d(
1901 Config.LOGTAG,
1902 account.getJid().asBareJid()
1903 + ": successfully registered new account on server");
1904 throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
1905 } else {
1906 final Account.State state = getRegistrationFailedState(response);
1907 throw new StateChangingError(state);
1908 }
1909 }
1910
1911 @NonNull
1912 private static Account.State getRegistrationFailedState(final Iq response) {
1913 final List<String> PASSWORD_TOO_WEAK_MESSAGES =
1914 Arrays.asList("The password is too weak", "Please use a longer password.");
1915 final var error = response.getError();
1916 final var condition = error == null ? null : error.getCondition();
1917 final Account.State state;
1918 if (condition instanceof Condition.Conflict) {
1919 state = Account.State.REGISTRATION_CONFLICT;
1920 } else if (condition instanceof Condition.ResourceConstraint) {
1921 state = Account.State.REGISTRATION_PLEASE_WAIT;
1922 } else if (condition instanceof Condition.NotAcceptable
1923 && PASSWORD_TOO_WEAK_MESSAGES.contains(error.getTextAsString())) {
1924 state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
1925 } else {
1926 state = Account.State.REGISTRATION_FAILED;
1927 }
1928 return state;
1929 }
1930
1931 private void setAccountCreationFailed(final String url) {
1932 final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1933 if (httpUrl != null && httpUrl.isHttps()) {
1934 this.redirectionUrl = httpUrl;
1935 throw new StateChangingError(Account.State.REGISTRATION_WEB);
1936 }
1937 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1938 }
1939
1940 public HttpUrl getRedirectionUrl() {
1941 return this.redirectionUrl;
1942 }
1943
1944 public void resetEverything() {
1945 resetAttemptCount(true);
1946 resetStreamId();
1947 clearIqCallbacks();
1948 synchronized (this.mStanzaQueue) {
1949 this.stanzasSent = 0;
1950 this.mStanzaQueue.clear();
1951 }
1952 this.redirectionUrl = null;
1953 synchronized (this.disco) {
1954 disco.clear();
1955 }
1956 synchronized (this.commands) {
1957 this.commands.clear();
1958 }
1959 this.loginInfo = null;
1960 }
1961
1962 private void sendBindRequest() {
1963 try {
1964 mXmppConnectionService.restoredFromDatabaseLatch.await();
1965 } catch (InterruptedException e) {
1966 Log.d(
1967 Config.LOGTAG,
1968 account.getJid().asBareJid()
1969 + ": interrupted while waiting for DB restore during bind");
1970 return;
1971 }
1972 clearIqCallbacks();
1973 if (account.getJid().isBareJid()) {
1974 account.setResource(createNewResource());
1975 } else {
1976 fixResource(mXmppConnectionService, account);
1977 }
1978 final Iq iq = new Iq(Iq.Type.SET);
1979 final String resource =
1980 Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND
1981 ? CryptoHelper.random(9)
1982 : account.getResource();
1983 iq.addExtension(new im.conversations.android.xmpp.model.bind.Bind()).setResource(resource);
1984 this.sendUnmodifiedIqPacket(
1985 iq,
1986 (packet) -> {
1987 if (packet.getType() == Iq.Type.TIMEOUT) {
1988 return;
1989 }
1990 final var bind =
1991 packet.getExtension(
1992 im.conversations.android.xmpp.model.bind.Bind.class);
1993 if (bind != null && packet.getType() == Iq.Type.RESULT) {
1994 isBound = true;
1995 final Jid assignedJid = bind.getJid();
1996 checkAssignedDomain(assignedJid);
1997 if (account.setJid(assignedJid)) {
1998 Log.d(
1999 Config.LOGTAG,
2000 account.getJid().asBareJid()
2001 + ": jid changed during bind. updating database");
2002 mXmppConnectionService.databaseBackend.updateAccount(account);
2003 }
2004 if (streamFeatures.hasChild("session")
2005 && !streamFeatures.findChild("session").hasChild("optional")) {
2006 sendStartSession();
2007 } else {
2008 final boolean waitForDisco = enableStreamManagement();
2009 sendPostBindInitialization(waitForDisco, false);
2010 }
2011 } else {
2012 Log.d(
2013 Config.LOGTAG,
2014 account.getJid()
2015 + ": disconnecting because of bind failure ("
2016 + packet);
2017 final var error = packet.getError();
2018 // TODO error.is(Condition)
2019 if (packet.getType() == Iq.Type.ERROR
2020 && error != null
2021 && error.hasChild("conflict")) {
2022 account.setResource(createNewResource());
2023 }
2024 throw new StateChangingError(Account.State.BIND_FAILURE);
2025 }
2026 },
2027 true);
2028 }
2029
2030 private void clearIqCallbacks() {
2031 final Iq failurePacket = new Iq(Iq.Type.TIMEOUT);
2032 final ArrayList<Consumer<Iq>> callbacks = new ArrayList<>();
2033 synchronized (this.packetCallbacks) {
2034 if (this.packetCallbacks.isEmpty()) {
2035 return;
2036 }
2037 Log.d(
2038 Config.LOGTAG,
2039 account.getJid().asBareJid()
2040 + ": clearing "
2041 + this.packetCallbacks.size()
2042 + " iq callbacks");
2043 final var iterator = this.packetCallbacks.values().iterator();
2044 while (iterator.hasNext()) {
2045 final var entry = iterator.next();
2046 callbacks.add(entry.second);
2047 iterator.remove();
2048 }
2049 }
2050 for (final var callback : callbacks) {
2051 try {
2052 callback.accept(failurePacket);
2053 } catch (StateChangingError error) {
2054 Log.d(
2055 Config.LOGTAG,
2056 account.getJid().asBareJid()
2057 + ": caught StateChangingError("
2058 + error.state.toString()
2059 + ") while clearing callbacks");
2060 // ignore
2061 }
2062 }
2063 Log.d(
2064 Config.LOGTAG,
2065 account.getJid().asBareJid()
2066 + ": done clearing iq callbacks. "
2067 + this.packetCallbacks.size()
2068 + " left");
2069 }
2070
2071 public void sendDiscoTimeout() {
2072 if (mWaitForDisco.compareAndSet(true, false)) {
2073 Log.d(
2074 Config.LOGTAG,
2075 account.getJid().asBareJid() + ": finalizing bind after disco timeout");
2076 finalizeBind();
2077 }
2078 }
2079
2080 private void sendStartSession() {
2081 Log.d(
2082 Config.LOGTAG,
2083 account.getJid().asBareJid() + ": sending legacy session to outdated server");
2084 final Iq startSession = new Iq(Iq.Type.SET);
2085 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
2086 this.sendUnmodifiedIqPacket(
2087 startSession,
2088 (packet) -> {
2089 if (packet.getType() == Iq.Type.RESULT) {
2090 final boolean waitForDisco = enableStreamManagement();
2091 sendPostBindInitialization(waitForDisco, false);
2092 } else if (packet.getType() != Iq.Type.TIMEOUT) {
2093 throw new StateChangingError(Account.State.SESSION_FAILURE);
2094 }
2095 },
2096 true);
2097 }
2098
2099 private boolean enableStreamManagement() {
2100 final boolean streamManagement = this.streamFeatures.streamManagement();
2101 if (streamManagement) {
2102 synchronized (this.mStanzaQueue) {
2103 final var enable = new Enable();
2104 tagWriter.writeStanzaAsync(enable);
2105 stanzasSent = 0;
2106 mStanzaQueue.clear();
2107 }
2108 return true;
2109 } else {
2110 return false;
2111 }
2112 }
2113
2114 private void sendPostBindInitialization(
2115 final boolean waitForDisco, final boolean carbonsEnabled) {
2116 features.carbonsEnabled = carbonsEnabled;
2117 features.blockListRequested = false;
2118 synchronized (this.disco) {
2119 this.disco.clear();
2120 }
2121 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
2122 mPendingServiceDiscoveries.set(0);
2123 mWaitForDisco.set(waitForDisco);
2124 this.lastDiscoStarted = SystemClock.elapsedRealtime();
2125 mXmppConnectionService.scheduleWakeUpCall(
2126 Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2127 final Element caps = streamFeatures.findChild("c");
2128 final String hash = caps == null ? null : caps.getAttribute("hash");
2129 final String ver = caps == null ? null : caps.getAttribute("ver");
2130 ServiceDiscoveryResult discoveryResult = null;
2131 if (hash != null && ver != null) {
2132 discoveryResult =
2133 mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2134 }
2135 final boolean requestDiscoItemsFirst =
2136 !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
2137 if (requestDiscoItemsFirst) {
2138 sendServiceDiscoveryItems(account.getDomain());
2139 }
2140 if (discoveryResult == null) {
2141 sendServiceDiscoveryInfo(account.getDomain());
2142 } else {
2143 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
2144 disco.put(account.getDomain(), discoveryResult);
2145 }
2146 final var features = getFeatures();
2147 if (!features.bind2()) {
2148 discoverMamPreferences();
2149 }
2150 sendServiceDiscoveryInfo(account.getJid().asBareJid());
2151 if (!requestDiscoItemsFirst) {
2152 sendServiceDiscoveryItems(account.getDomain());
2153 }
2154
2155 if (!mWaitForDisco.get()) {
2156 finalizeBind();
2157 }
2158 this.lastSessionStarted = SystemClock.elapsedRealtime();
2159 }
2160
2161 private void sendServiceDiscoveryInfo(final Jid jid) {
2162 mPendingServiceDiscoveries.incrementAndGet();
2163 final Iq iq = new Iq(Iq.Type.GET);
2164 iq.setTo(jid);
2165 iq.query("http://jabber.org/protocol/disco#info");
2166 this.sendIqPacket(
2167 iq,
2168 (packet) -> {
2169 if (packet.getType() == Iq.Type.RESULT) {
2170 boolean advancedStreamFeaturesLoaded;
2171 synchronized (XmppConnection.this.disco) {
2172 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2173 if (jid.equals(account.getDomain())) {
2174 mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2175 result);
2176 }
2177 disco.put(jid, result);
2178 advancedStreamFeaturesLoaded =
2179 disco.containsKey(account.getDomain())
2180 && disco.containsKey(account.getJid().asBareJid());
2181 }
2182 if (advancedStreamFeaturesLoaded
2183 && (jid.equals(account.getDomain())
2184 || jid.equals(account.getJid().asBareJid()))) {
2185 enableAdvancedStreamFeatures();
2186 }
2187 } else if (packet.getType() == Iq.Type.ERROR) {
2188 Log.d(
2189 Config.LOGTAG,
2190 account.getJid().asBareJid()
2191 + ": could not query disco info for "
2192 + jid.toString());
2193 final boolean serverOrAccount =
2194 jid.equals(account.getDomain())
2195 || jid.equals(account.getJid().asBareJid());
2196 final boolean advancedStreamFeaturesLoaded;
2197 if (serverOrAccount) {
2198 synchronized (XmppConnection.this.disco) {
2199 disco.put(jid, ServiceDiscoveryResult.empty());
2200 advancedStreamFeaturesLoaded =
2201 disco.containsKey(account.getDomain())
2202 && disco.containsKey(account.getJid().asBareJid());
2203 }
2204 } else {
2205 advancedStreamFeaturesLoaded = false;
2206 }
2207 if (advancedStreamFeaturesLoaded) {
2208 enableAdvancedStreamFeatures();
2209 }
2210 }
2211 if (packet.getType() != Iq.Type.TIMEOUT) {
2212 if (mPendingServiceDiscoveries.decrementAndGet() == 0
2213 && mWaitForDisco.compareAndSet(true, false)) {
2214 finalizeBind();
2215 }
2216 }
2217 });
2218 }
2219
2220 private void discoverMamPreferences() {
2221 final Iq request = new Iq(Iq.Type.GET);
2222 request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2223 sendIqPacket(
2224 request,
2225 (response) -> {
2226 if (response.getType() == Iq.Type.RESULT) {
2227 Element prefs =
2228 response.findChild(
2229 "prefs", MessageArchiveService.Version.MAM_2.namespace);
2230 isMamPreferenceAlways =
2231 "always"
2232 .equals(
2233 prefs == null
2234 ? null
2235 : prefs.getAttribute("default"));
2236 }
2237 });
2238 }
2239
2240 private void discoverCommands() {
2241 final Iq request = new Iq(Iq.Type.GET);
2242 request.setTo(account.getDomain());
2243 request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2244 sendIqPacket(
2245 request,
2246 (response) -> {
2247 if (response.getType() == Iq.Type.RESULT) {
2248 final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2249 if (query == null) {
2250 return;
2251 }
2252 final HashMap<String, Jid> commands = new HashMap<>();
2253 for (final Element child : query.getChildren()) {
2254 if ("item".equals(child.getName())) {
2255 final String node = child.getAttribute("node");
2256 final Jid jid = child.getAttributeAsJid("jid");
2257 if (node != null && jid != null) {
2258 commands.put(node, jid);
2259 }
2260 }
2261 }
2262 synchronized (this.commands) {
2263 this.commands.clear();
2264 this.commands.putAll(commands);
2265 }
2266 }
2267 });
2268 }
2269
2270 public boolean isMamPreferenceAlways() {
2271 return isMamPreferenceAlways;
2272 }
2273
2274 private void finalizeBind() {
2275 this.offlineMessagesRetrieved = false;
2276 this.bindListener.run();
2277 this.changeStatusToOnline();
2278 }
2279
2280 private void enableAdvancedStreamFeatures() {
2281 if (getFeatures().blocking() && !features.blockListRequested) {
2282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2283 this.sendIqPacket(getIqGenerator().generateGetBlockList(), unregisteredIqListener);
2284 }
2285 for (final OnAdvancedStreamFeaturesLoaded listener :
2286 advancedStreamFeaturesLoadedListeners) {
2287 listener.onAdvancedStreamFeaturesAvailable(account);
2288 }
2289 if (getFeatures().carbons() && !features.carbonsEnabled) {
2290 sendEnableCarbons();
2291 }
2292 if (getFeatures().commands()) {
2293 discoverCommands();
2294 }
2295 }
2296
2297 private void sendServiceDiscoveryItems(final Jid server) {
2298 mPendingServiceDiscoveries.incrementAndGet();
2299 final Iq iq = new Iq(Iq.Type.GET);
2300 iq.setTo(server.getDomain());
2301 iq.query("http://jabber.org/protocol/disco#items");
2302 this.sendIqPacket(
2303 iq,
2304 (packet) -> {
2305 if (packet.getType() == Iq.Type.RESULT) {
2306 final HashSet<Jid> items = new HashSet<>();
2307 final List<Element> elements = packet.query().getChildren();
2308 for (final Element element : elements) {
2309 if (element.getName().equals("item")) {
2310 final Jid jid =
2311 InvalidJid.getNullForInvalid(
2312 element.getAttributeAsJid("jid"));
2313 if (jid != null && !jid.equals(account.getDomain())) {
2314 items.add(jid);
2315 }
2316 }
2317 }
2318 for (Jid jid : items) {
2319 sendServiceDiscoveryInfo(jid);
2320 }
2321 } else {
2322 Log.d(
2323 Config.LOGTAG,
2324 account.getJid().asBareJid()
2325 + ": could not query disco items of "
2326 + server);
2327 }
2328 if (packet.getType() != Iq.Type.TIMEOUT) {
2329 if (mPendingServiceDiscoveries.decrementAndGet() == 0
2330 && mWaitForDisco.compareAndSet(true, false)) {
2331 finalizeBind();
2332 }
2333 }
2334 });
2335 }
2336
2337 private void sendEnableCarbons() {
2338 final Iq iq = new Iq(Iq.Type.SET);
2339 iq.addChild("enable", Namespace.CARBONS);
2340 this.sendIqPacket(
2341 iq,
2342 (packet) -> {
2343 if (packet.getType() == Iq.Type.RESULT) {
2344 Log.d(
2345 Config.LOGTAG,
2346 account.getJid().asBareJid() + ": successfully enabled carbons");
2347 features.carbonsEnabled = true;
2348 } else {
2349 Log.d(
2350 Config.LOGTAG,
2351 account.getJid().asBareJid()
2352 + ": could not enable carbons "
2353 + packet);
2354 }
2355 });
2356 }
2357
2358 private void processStreamError(final StreamError streamError) throws IOException {
2359 final var loginInfo = this.loginInfo;
2360 final var isSecureLoggedIn = isSecure() && LoginInfo.isSuccess(loginInfo);
2361 if (isSecureLoggedIn && streamError.hasChild("conflict")) {
2362 if (loginInfo.saslVersion == SaslMechanism.Version.SASL_2) {
2363 this.appSettings.resetInstallationId();
2364 }
2365 account.setResource(createNewResource());
2366 Log.d(
2367 Config.LOGTAG,
2368 account.getJid().asBareJid()
2369 + ": switching resource due to conflict ("
2370 + account.getResource()
2371 + ")");
2372 throw new IOException("Closed stream due to resource conflict");
2373 } else if (streamError.hasChild("host-unknown")) {
2374 throw new StateChangingException(Account.State.HOST_UNKNOWN);
2375 } else if (streamError.hasChild("policy-violation")) {
2376 this.lastConnect = SystemClock.elapsedRealtime();
2377 final String text = streamError.findChildContent("text");
2378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2379 if (isSecureLoggedIn) {
2380 failPendingMessages(text);
2381 }
2382 throw new StateChangingException(Account.State.POLICY_VIOLATION);
2383 } else if (streamError.hasChild("see-other-host")) {
2384 final String seeOtherHost = streamError.findChildContent("see-other-host");
2385 final Resolver.Result currentResolverResult = this.currentResolverResult;
2386 if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2387 Log.d(
2388 Config.LOGTAG,
2389 account.getJid().asBareJid() + ": stream error " + streamError);
2390 throw new StateChangingException(Account.State.STREAM_ERROR);
2391 }
2392 Log.d(
2393 Config.LOGTAG,
2394 account.getJid().asBareJid()
2395 + ": see other host: "
2396 + seeOtherHost
2397 + " "
2398 + currentResolverResult);
2399 final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2400 if (seeOtherResult != null) {
2401 this.seeOtherHostResolverResult = seeOtherResult;
2402 throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2403 } else {
2404 throw new StateChangingException(Account.State.STREAM_ERROR);
2405 }
2406 } else {
2407 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2408 throw new StateChangingException(Account.State.STREAM_ERROR);
2409 }
2410 }
2411
2412 private void failPendingMessages(final String error) {
2413 synchronized (this.mStanzaQueue) {
2414 for (int i = 0; i < mStanzaQueue.size(); ++i) {
2415 final Stanza stanza = mStanzaQueue.valueAt(i);
2416 if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message packet) {
2417 final String id = packet.getId();
2418 final Jid to = packet.getTo();
2419 mXmppConnectionService.markMessage(
2420 account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2421 }
2422 }
2423 }
2424 }
2425
2426 private boolean establishStream(final SSLSockets.Version sslVersion)
2427 throws IOException, InterruptedException {
2428 final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2429 final SaslMechanism quickStartMechanism;
2430 if (secureConnection) {
2431 quickStartMechanism =
2432 SaslMechanism.ensureAvailable(
2433 account.getQuickStartMechanism(),
2434 sslVersion,
2435 appSettings.isRequireChannelBinding());
2436 } else {
2437 quickStartMechanism = null;
2438 }
2439 if (secureConnection
2440 && Config.QUICKSTART_ENABLED
2441 && quickStartMechanism != null
2442 && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2443 mXmppConnectionService.restoredFromDatabaseLatch.await();
2444 this.loginInfo =
2445 new LoginInfo(
2446 quickStartMechanism,
2447 SaslMechanism.Version.SASL_2,
2448 Bind2.QUICKSTART_FEATURES);
2449 final boolean usingFast = quickStartMechanism instanceof HashedToken;
2450 final AuthenticationRequest authenticate =
2451 generateAuthenticationRequest(
2452 quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2453 usingFast);
2454 authenticate.setMechanism(quickStartMechanism);
2455 sendStartStream(true, false);
2456 synchronized (this.mStanzaQueue) {
2457 this.stanzasSentBeforeAuthentication = this.stanzasSent;
2458 tagWriter.writeElement(authenticate);
2459 }
2460 Log.d(
2461 Config.LOGTAG,
2462 account.getJid().toString()
2463 + ": quick start with "
2464 + quickStartMechanism.getMechanism());
2465 return true;
2466 } else {
2467 sendStartStream(secureConnection, true);
2468 return false;
2469 }
2470 }
2471
2472 private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2473 final Tag stream = Tag.start("stream:stream");
2474 stream.setAttribute("to", account.getServer());
2475 if (from) {
2476 stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2477 }
2478 stream.setAttribute("version", "1.0");
2479 stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2480 stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2481 stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2482 tagWriter.writeTag(stream, flush);
2483 }
2484
2485 private static String createNewResource() {
2486 return String.format("%s.%s", BuildConfig.APP_NAME, CryptoHelper.random(3));
2487 }
2488
2489 public String sendIqPacket(final Iq packet, final Consumer<Iq> callback) {
2490 packet.setFrom(account.getJid());
2491 return this.sendUnmodifiedIqPacket(packet, callback, false);
2492 }
2493
2494 public synchronized String sendUnmodifiedIqPacket(
2495 final Iq packet, final Consumer<Iq> callback, boolean force) {
2496 // TODO if callback != null verify that type is get or set
2497 if (packet.getId() == null) {
2498 packet.setId(CryptoHelper.random(9));
2499 }
2500 if (callback != null) {
2501 synchronized (this.packetCallbacks) {
2502 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2503 }
2504 }
2505 this.sendPacket(packet, force);
2506 return packet.getId();
2507 }
2508
2509 public void sendMessagePacket(final im.conversations.android.xmpp.model.stanza.Message packet) {
2510 this.sendPacket(packet);
2511 }
2512
2513 public void sendPresencePacket(final Presence packet) {
2514 this.sendPacket(packet);
2515 }
2516
2517 private synchronized void sendPacket(final StreamElement packet) {
2518 sendPacket(packet, false);
2519 }
2520
2521 private synchronized void sendPacket(final StreamElement packet, final boolean force) {
2522 if (stanzasSent == Integer.MAX_VALUE) {
2523 resetStreamId();
2524 disconnect(true);
2525 return;
2526 }
2527 synchronized (this.mStanzaQueue) {
2528 if (force || isBound) {
2529 tagWriter.writeStanzaAsync(packet);
2530 } else {
2531 Log.d(
2532 Config.LOGTAG,
2533 account.getJid().asBareJid()
2534 + " do not write stanza to unbound stream "
2535 + packet.toString());
2536 }
2537 if (packet instanceof Stanza stanza) {
2538 if (this.mStanzaQueue.size() != 0) {
2539 int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2540 if (currentHighestKey != stanzasSent) {
2541 throw new AssertionError("Stanza count messed up");
2542 }
2543 }
2544
2545 ++stanzasSent;
2546 if (Config.EXTENDED_SM_LOGGING) {
2547 Log.d(
2548 Config.LOGTAG,
2549 account.getJid().asBareJid()
2550 + ": counting outbound "
2551 + packet.getName()
2552 + " as #"
2553 + stanzasSent);
2554 }
2555 this.mStanzaQueue.append(stanzasSent, stanza);
2556 if (stanza instanceof im.conversations.android.xmpp.model.stanza.Message
2557 && stanza.getId() != null
2558 && inSmacksSession) {
2559 if (Config.EXTENDED_SM_LOGGING) {
2560 Log.d(
2561 Config.LOGTAG,
2562 account.getJid().asBareJid()
2563 + ": requesting ack for message stanza #"
2564 + stanzasSent);
2565 }
2566 tagWriter.writeStanzaAsync(new Request());
2567 }
2568 }
2569 }
2570 }
2571
2572 public void sendPing() {
2573 if (!r()) {
2574 final Iq iq = new Iq(Iq.Type.GET);
2575 iq.setFrom(account.getJid());
2576 iq.addChild("ping", Namespace.PING);
2577 this.sendIqPacket(iq, null);
2578 }
2579 this.lastPingSent = SystemClock.elapsedRealtime();
2580 }
2581
2582 public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2583 this.jingleListener = listener;
2584 }
2585
2586 public void setOnStatusChangedListener(final OnStatusChanged listener) {
2587 this.statusListener = listener;
2588 }
2589
2590 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2591 this.acknowledgedListener = listener;
2592 }
2593
2594 public void addOnAdvancedStreamFeaturesAvailableListener(
2595 final OnAdvancedStreamFeaturesLoaded listener) {
2596 this.advancedStreamFeaturesLoadedListeners.add(listener);
2597 }
2598
2599 private void forceCloseSocket() {
2600 FileBackend.close(this.socket);
2601 FileBackend.close(this.tagReader);
2602 }
2603
2604 public void interrupt() {
2605 if (this.mThread != null) {
2606 this.mThread.interrupt();
2607 }
2608 }
2609
2610 public void disconnect(final boolean force) {
2611 interrupt();
2612 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2613 if (force) {
2614 forceCloseSocket();
2615 } else {
2616 final TagWriter currentTagWriter = this.tagWriter;
2617 if (currentTagWriter.isActive()) {
2618 currentTagWriter.finish();
2619 final Socket currentSocket = this.socket;
2620 final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2621 try {
2622 currentTagWriter.await(1, TimeUnit.SECONDS);
2623 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2624 currentTagWriter.writeTag(Tag.end("stream:stream"));
2625 if (streamCountDownLatch != null) {
2626 if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2627 Log.d(
2628 Config.LOGTAG,
2629 account.getJid().asBareJid() + ": remote ended stream");
2630 } else {
2631 Log.d(
2632 Config.LOGTAG,
2633 account.getJid().asBareJid()
2634 + ": remote has not closed socket. force closing");
2635 }
2636 }
2637 } catch (InterruptedException e) {
2638 Log.d(
2639 Config.LOGTAG,
2640 account.getJid().asBareJid()
2641 + ": interrupted while gracefully closing stream");
2642 } catch (final IOException e) {
2643 Log.d(
2644 Config.LOGTAG,
2645 account.getJid().asBareJid()
2646 + ": io exception during disconnect ("
2647 + e.getMessage()
2648 + ")");
2649 } finally {
2650 FileBackend.close(currentSocket);
2651 }
2652 } else {
2653 forceCloseSocket();
2654 }
2655 }
2656 }
2657
2658 private void resetStreamId() {
2659 this.pendingResumeId.clear();
2660 this.streamId = null;
2661 this.boundStreamFeatures = null;
2662 }
2663
2664 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2665 synchronized (this.disco) {
2666 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2667 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2668 if (cursor.getValue().getFeatures().contains(feature)) {
2669 items.add(cursor);
2670 }
2671 }
2672 return items;
2673 }
2674 }
2675
2676 public Jid findDiscoItemByFeature(final String feature) {
2677 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2678 if (items.size() >= 1) {
2679 return items.get(0).getKey();
2680 }
2681 return null;
2682 }
2683
2684 public boolean r() {
2685 if (getFeatures().sm()) {
2686 this.tagWriter.writeStanzaAsync(new Request());
2687 return true;
2688 } else {
2689 return false;
2690 }
2691 }
2692
2693 public List<String> getMucServersWithholdAccount() {
2694 final List<String> servers = getMucServers();
2695 servers.remove(account.getDomain().toEscapedString());
2696 return servers;
2697 }
2698
2699 public List<String> getMucServers() {
2700 List<String> servers = new ArrayList<>();
2701 synchronized (this.disco) {
2702 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2703 final ServiceDiscoveryResult value = cursor.getValue();
2704 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2705 && value.hasIdentity("conference", "text")
2706 && !value.getFeatures().contains("jabber:iq:gateway")
2707 && !value.hasIdentity("conference", "irc")) {
2708 servers.add(cursor.getKey().toString());
2709 }
2710 }
2711 }
2712 return servers;
2713 }
2714
2715 public String getMucServer() {
2716 List<String> servers = getMucServers();
2717 return servers.size() > 0 ? servers.get(0) : null;
2718 }
2719
2720 public int getTimeToNextAttempt(final boolean aggressive) {
2721 final int interval;
2722 if (aggressive) {
2723 interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2724 } else {
2725 final int additionalTime =
2726 account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2727 interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2728 }
2729 final int secondsSinceLast =
2730 (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2731 return interval - secondsSinceLast;
2732 }
2733
2734 public int getAttempt() {
2735 return this.attempt;
2736 }
2737
2738 public Features getFeatures() {
2739 return this.features;
2740 }
2741
2742 public long getLastSessionEstablished() {
2743 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2744 return System.currentTimeMillis() - diff;
2745 }
2746
2747 public long getLastConnect() {
2748 return this.lastConnect;
2749 }
2750
2751 public long getLastPingSent() {
2752 return this.lastPingSent;
2753 }
2754
2755 public long getLastDiscoStarted() {
2756 return this.lastDiscoStarted;
2757 }
2758
2759 public long getLastPacketReceived() {
2760 return this.lastPacketReceived;
2761 }
2762
2763 public void sendActive() {
2764 this.sendPacket(new Active());
2765 }
2766
2767 public void sendInactive() {
2768 this.sendPacket(new Inactive());
2769 }
2770
2771 public void resetAttemptCount(boolean resetConnectTime) {
2772 this.attempt = 0;
2773 if (resetConnectTime) {
2774 this.lastConnect = 0;
2775 }
2776 }
2777
2778 public void setInteractive(boolean interactive) {
2779 this.mInteractive = interactive;
2780 }
2781
2782 private IqGenerator getIqGenerator() {
2783 return mXmppConnectionService.getIqGenerator();
2784 }
2785
2786 public void trackOfflineMessageRetrieval(boolean trackOfflineMessageRetrieval) {
2787 if (trackOfflineMessageRetrieval) {
2788 final Iq iqPing = new Iq(Iq.Type.GET);
2789 iqPing.addChild("ping", Namespace.PING);
2790 this.sendIqPacket(
2791 iqPing,
2792 (response) -> {
2793 Log.d(
2794 Config.LOGTAG,
2795 account.getJid().asBareJid()
2796 + ": got ping response after sending initial presence");
2797 XmppConnection.this.offlineMessagesRetrieved = true;
2798 });
2799 } else {
2800 this.offlineMessagesRetrieved = true;
2801 }
2802 }
2803
2804 public boolean isOfflineMessagesRetrieved() {
2805 return this.offlineMessagesRetrieved;
2806 }
2807
2808 public void fetchRoster() {
2809 final Iq iqPacket = new Iq(Iq.Type.GET);
2810 final var version = account.getRosterVersion();
2811 if (Strings.isNullOrEmpty(account.getRosterVersion())) {
2812 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching roster");
2813 } else {
2814 Log.d(
2815 Config.LOGTAG,
2816 account.getJid().asBareJid() + ": fetching roster version " + version);
2817 }
2818 iqPacket.query(Namespace.ROSTER).setAttribute("ver", version);
2819 sendIqPacket(iqPacket, unregisteredIqListener);
2820 }
2821
2822 private class MyKeyManager implements X509KeyManager {
2823 @Override
2824 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2825 return account.getPrivateKeyAlias();
2826 }
2827
2828 @Override
2829 public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2830 return null;
2831 }
2832
2833 @Override
2834 public X509Certificate[] getCertificateChain(String alias) {
2835 Log.d(Config.LOGTAG, "getting certificate chain");
2836 try {
2837 return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2838 } catch (final Exception e) {
2839 Log.d(Config.LOGTAG, "could not get certificate chain", e);
2840 return new X509Certificate[0];
2841 }
2842 }
2843
2844 @Override
2845 public String[] getClientAliases(String s, Principal[] principals) {
2846 final String alias = account.getPrivateKeyAlias();
2847 return alias != null ? new String[] {alias} : new String[0];
2848 }
2849
2850 @Override
2851 public String[] getServerAliases(String s, Principal[] principals) {
2852 return new String[0];
2853 }
2854
2855 @Override
2856 public PrivateKey getPrivateKey(String alias) {
2857 try {
2858 return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2859 } catch (Exception e) {
2860 return null;
2861 }
2862 }
2863 }
2864
2865 private static class LoginInfo {
2866 public final SaslMechanism saslMechanism;
2867 public final SaslMechanism.Version saslVersion;
2868 public final List<String> inlineBindFeatures;
2869 public final AtomicBoolean success = new AtomicBoolean(false);
2870
2871 private LoginInfo(
2872 final SaslMechanism saslMechanism,
2873 final SaslMechanism.Version saslVersion,
2874 final Collection<String> inlineBindFeatures) {
2875 Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2876 Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2877 this.saslMechanism = saslMechanism;
2878 this.saslVersion = saslVersion;
2879 this.inlineBindFeatures =
2880 inlineBindFeatures == null
2881 ? Collections.emptyList()
2882 : ImmutableList.copyOf(inlineBindFeatures);
2883 }
2884
2885 public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2886 return loginInfo == null ? null : loginInfo.saslMechanism;
2887 }
2888
2889 public void success(final String challenge, final SSLSocket sslSocket)
2890 throws SaslMechanism.AuthenticationException {
2891 final var response = this.saslMechanism.getResponse(challenge, sslSocket);
2892 if (!Strings.isNullOrEmpty(response)) {
2893 throw new SaslMechanism.AuthenticationException(
2894 "processing success yielded another response");
2895 }
2896 if (this.success.compareAndSet(false, true)) {
2897 return;
2898 }
2899 throw new SaslMechanism.AuthenticationException("Process 'success' twice");
2900 }
2901
2902 public static boolean isSuccess(final LoginInfo loginInfo) {
2903 return loginInfo != null && loginInfo.success.get();
2904 }
2905 }
2906
2907 private static class StreamId {
2908 public final String id;
2909 public final Resolver.Result location;
2910
2911 private StreamId(String id, Resolver.Result location) {
2912 this.id = id;
2913 this.location = location;
2914 }
2915
2916 @NonNull
2917 @Override
2918 public String toString() {
2919 return MoreObjects.toStringHelper(this)
2920 .add("id", id)
2921 .add("location", location)
2922 .toString();
2923 }
2924 }
2925
2926 private static class StateChangingError extends Error {
2927 private final Account.State state;
2928
2929 public StateChangingError(Account.State state) {
2930 this.state = state;
2931 }
2932 }
2933
2934 private static class StateChangingException extends IOException {
2935 private final Account.State state;
2936
2937 public StateChangingException(Account.State state) {
2938 this.state = state;
2939 }
2940 }
2941
2942 public class Features {
2943 XmppConnection connection;
2944 private boolean carbonsEnabled = false;
2945 private boolean encryptionEnabled = false;
2946 private boolean blockListRequested = false;
2947
2948 public Features(final XmppConnection connection) {
2949 this.connection = connection;
2950 }
2951
2952 private boolean hasDiscoFeature(final Jid server, final String feature) {
2953 synchronized (XmppConnection.this.disco) {
2954 final ServiceDiscoveryResult sdr = connection.disco.get(server);
2955 return sdr != null && sdr.getFeatures().contains(feature);
2956 }
2957 }
2958
2959 public boolean carbons() {
2960 return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2961 }
2962
2963 public boolean commands() {
2964 return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2965 }
2966
2967 public boolean easyOnboardingInvites() {
2968 synchronized (commands) {
2969 return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2970 }
2971 }
2972
2973 public boolean bookmarksConversion() {
2974 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2975 && pepPublishOptions();
2976 }
2977
2978 public boolean blocking() {
2979 return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2980 }
2981
2982 public boolean spamReporting() {
2983 return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
2984 }
2985
2986 public boolean flexibleOfflineMessageRetrieval() {
2987 return hasDiscoFeature(
2988 account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2989 }
2990
2991 public boolean register() {
2992 return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2993 }
2994
2995 public boolean invite() {
2996 return connection.streamFeatures != null
2997 && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2998 }
2999
3000 public boolean sm() {
3001 return streamId != null
3002 || (connection.streamFeatures != null
3003 && connection.streamFeatures.streamManagement());
3004 }
3005
3006 public boolean csi() {
3007 return connection.streamFeatures != null
3008 && connection.streamFeatures.clientStateIndication();
3009 }
3010
3011 public boolean pep() {
3012 synchronized (XmppConnection.this.disco) {
3013 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3014 return info != null && info.hasIdentity("pubsub", "pep");
3015 }
3016 }
3017
3018 public boolean pepPersistent() {
3019 synchronized (XmppConnection.this.disco) {
3020 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
3021 return info != null
3022 && info.getFeatures()
3023 .contains("http://jabber.org/protocol/pubsub#persistent-items");
3024 }
3025 }
3026
3027 public boolean bind2() {
3028 final var loginInfo = XmppConnection.this.loginInfo;
3029 return loginInfo != null && !loginInfo.inlineBindFeatures.isEmpty();
3030 }
3031
3032 public boolean sasl2() {
3033 final var loginInfo = XmppConnection.this.loginInfo;
3034 return loginInfo != null && loginInfo.saslVersion == SaslMechanism.Version.SASL_2;
3035 }
3036
3037 public String loginMechanism() {
3038 final var loginInfo = XmppConnection.this.loginInfo;
3039 return loginInfo == null ? null : loginInfo.saslMechanism.getMechanism();
3040 }
3041
3042 public boolean pepPublishOptions() {
3043 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
3044 }
3045
3046 public boolean pepConfigNodeMax() {
3047 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_CONFIG_NODE_MAX);
3048 }
3049
3050 public boolean pepOmemoWhitelisted() {
3051 return hasDiscoFeature(
3052 account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
3053 }
3054
3055 public boolean mam() {
3056 return MessageArchiveService.Version.has(getAccountFeatures());
3057 }
3058
3059 public List<String> getAccountFeatures() {
3060 ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
3061 return result == null ? Collections.emptyList() : result.getFeatures();
3062 }
3063
3064 public boolean push() {
3065 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
3066 || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
3067 }
3068
3069 public boolean rosterVersioning() {
3070 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
3071 }
3072
3073 public void setBlockListRequested(boolean value) {
3074 this.blockListRequested = value;
3075 }
3076
3077 public boolean httpUpload(long filesize) {
3078 if (Config.DISABLE_HTTP_UPLOAD) {
3079 return false;
3080 } else {
3081 for (String namespace :
3082 new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3083 List<Entry<Jid, ServiceDiscoveryResult>> items =
3084 findDiscoItemsByFeature(namespace);
3085 if (items.size() > 0) {
3086 try {
3087 long maxsize =
3088 Long.parseLong(
3089 items.get(0)
3090 .getValue()
3091 .getExtendedDiscoInformation(
3092 namespace, "max-file-size"));
3093 if (filesize <= maxsize) {
3094 return true;
3095 } else {
3096 Log.d(
3097 Config.LOGTAG,
3098 account.getJid().asBareJid()
3099 + ": http upload is not available for files with"
3100 + " size "
3101 + filesize
3102 + " (max is "
3103 + maxsize
3104 + ")");
3105 return false;
3106 }
3107 } catch (Exception e) {
3108 return true;
3109 }
3110 }
3111 }
3112 return false;
3113 }
3114 }
3115
3116 public boolean useLegacyHttpUpload() {
3117 return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
3118 && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
3119 }
3120
3121 public long getMaxHttpUploadSize() {
3122 for (String namespace :
3123 new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3124 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
3125 if (items.size() > 0) {
3126 try {
3127 return Long.parseLong(
3128 items.get(0)
3129 .getValue()
3130 .getExtendedDiscoInformation(namespace, "max-file-size"));
3131 } catch (Exception e) {
3132 // ignored
3133 }
3134 }
3135 }
3136 return -1;
3137 }
3138
3139 public boolean stanzaIds() {
3140 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3141 }
3142
3143 public boolean bookmarks2() {
3144 return pepPublishOptions()
3145 && pepConfigNodeMax()
3146 && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3147 }
3148
3149 public boolean externalServiceDiscovery() {
3150 return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3151 }
3152
3153 public boolean mds() {
3154 return pepPublishOptions()
3155 && pepConfigNodeMax()
3156 && Config.MESSAGE_DISPLAYED_SYNCHRONIZATION;
3157 }
3158
3159 public boolean mdsServerAssist() {
3160 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.MDS_DISPLAYED);
3161 }
3162 }
3163}