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