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