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