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 ImmutableList.Builder<AbstractAcknowledgeableStanza> intermediateStanzasBuilder =
939 new ImmutableList.Builder<>();
940 if (Config.EXTENDED_SM_LOGGING) {
941 Log.d(
942 Config.LOGTAG,
943 account.getJid().asBareJid()
944 + ": stanzas sent before auth: "
945 + this.stanzasSentBeforeAuthentication);
946 }
947 for (int i = this.stanzasSentBeforeAuthentication + 1; i <= this.stanzasSent; ++i) {
948 final AbstractAcknowledgeableStanza stanza = this.mStanzaQueue.get(i);
949 if (stanza != null) {
950 intermediateStanzasBuilder.add(stanza);
951 }
952 }
953 this.mStanzaQueue.clear();
954 final var intermediateStanzas = intermediateStanzasBuilder.build();
955 for (int i = 0; i < intermediateStanzas.size(); ++i) {
956 this.mStanzaQueue.append(i + 1, intermediateStanzas.get(i));
957 }
958 this.stanzasSent = intermediateStanzas.size();
959 if (Config.EXTENDED_SM_LOGGING) {
960 Log.d(
961 Config.LOGTAG,
962 account.getJid().asBareJid()
963 + ": resetting outbound stanza queue to "
964 + this.stanzasSent);
965 }
966 }
967 }
968
969 private void processNopStreamFeatures() throws IOException {
970 final Tag tag = tagReader.readTag();
971 if (tag != null && tag.isStart("features", Namespace.STREAMS)) {
972 this.streamFeatures = tagReader.readElement(tag);
973 Log.d(
974 Config.LOGTAG,
975 account.getJid().asBareJid()
976 + ": processed NOP stream features after success: "
977 + XmlHelper.printElementNames(this.streamFeatures));
978 } else {
979 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": received " + tag);
980 Log.d(
981 Config.LOGTAG,
982 account.getJid().asBareJid()
983 + ": server did not send stream features after SASL2 success");
984 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
985 }
986 }
987
988 private void processFailure(final Element failure) throws IOException {
989 final SaslMechanism.Version version;
990 try {
991 version = SaslMechanism.Version.of(failure);
992 } catch (final IllegalArgumentException e) {
993 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
994 }
995 Log.d(Config.LOGTAG, failure.toString());
996 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
997 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
998 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resetting token");
999 account.resetFastToken();
1000 mXmppConnectionService.databaseBackend.updateAccount(account);
1001 }
1002 if (failure.hasChild("temporary-auth-failure")) {
1003 throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
1004 } else if (failure.hasChild("account-disabled")) {
1005 final String text = failure.findChildContent("text");
1006 if (Strings.isNullOrEmpty(text)) {
1007 throw new StateChangingException(Account.State.UNAUTHORIZED);
1008 }
1009 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
1010 if (matcher.find()) {
1011 final HttpUrl url;
1012 try {
1013 url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
1014 } catch (final IllegalArgumentException e) {
1015 throw new StateChangingException(Account.State.UNAUTHORIZED);
1016 }
1017 if (url.isHttps()) {
1018 this.redirectionUrl = url;
1019 throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
1020 }
1021 }
1022 }
1023 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1024 Log.d(
1025 Config.LOGTAG,
1026 account.getJid().asBareJid()
1027 + ": fast authentication failed. falling back to regular authentication");
1028 authenticate();
1029 } else {
1030 throw new StateChangingException(Account.State.UNAUTHORIZED);
1031 }
1032 }
1033
1034 private static SSLSocket sslSocketOrNull(final Socket socket) {
1035 if (socket instanceof SSLSocket) {
1036 return (SSLSocket) socket;
1037 } else {
1038 return null;
1039 }
1040 }
1041
1042 private void processEnabled(final Element enabled) {
1043 final String id;
1044 if (enabled.getAttributeAsBoolean("resume")) {
1045 id = enabled.getAttribute("id");
1046 } else {
1047 id = null;
1048 }
1049 final String locationAttribute = enabled.getAttribute("location");
1050 final Resolver.Result currentResolverResult = this.currentResolverResult;
1051 final Resolver.Result location;
1052 if (Strings.isNullOrEmpty(locationAttribute) || currentResolverResult == null) {
1053 location = null;
1054 } else {
1055 location = currentResolverResult.seeOtherHost(locationAttribute);
1056 }
1057 final StreamId streamId = id == null ? null : new StreamId(id, location);
1058 if (streamId == null) {
1059 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream management enabled");
1060 } else {
1061 Log.d(
1062 Config.LOGTAG,
1063 account.getJid().asBareJid()
1064 + ": stream management enabled. resume at: "
1065 + streamId.location);
1066 }
1067 this.streamId = streamId;
1068 this.stanzasReceived = 0;
1069 this.inSmacksSession = true;
1070 final RequestPacket r = new RequestPacket();
1071 tagWriter.writeStanzaAsync(r);
1072 }
1073
1074 private void processResumed(final Element resumed) throws StateChangingException {
1075 this.inSmacksSession = true;
1076 this.isBound = true;
1077 this.tagWriter.writeStanzaAsync(new RequestPacket());
1078 lastPacketReceived = SystemClock.elapsedRealtime();
1079 final Optional<Integer> h = resumed.getOptionalIntAttribute("h");
1080 final int serverCount;
1081 if (h.isPresent()) {
1082 serverCount = h.get();
1083 } else {
1084 resetStreamId();
1085 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1086 }
1087 final ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
1088 final boolean acknowledgedMessages;
1089 synchronized (this.mStanzaQueue) {
1090 if (serverCount < stanzasSent) {
1091 Log.d(
1092 Config.LOGTAG,
1093 account.getJid().asBareJid() + ": session resumed with lost packages");
1094 stanzasSent = serverCount;
1095 } else {
1096 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": session resumed");
1097 }
1098 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
1099 for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
1100 failedStanzas.add(mStanzaQueue.valueAt(i));
1101 }
1102 mStanzaQueue.clear();
1103 }
1104 if (acknowledgedMessages) {
1105 mXmppConnectionService.updateConversationUi();
1106 }
1107 Log.d(
1108 Config.LOGTAG,
1109 account.getJid().asBareJid() + ": resending " + failedStanzas.size() + " stanzas");
1110 for (final AbstractAcknowledgeableStanza packet : failedStanzas) {
1111 if (packet instanceof MessagePacket message) {
1112 mXmppConnectionService.markMessage(
1113 account,
1114 message.getTo().asBareJid(),
1115 message.getId(),
1116 Message.STATUS_UNSEND);
1117 }
1118 sendPacket(packet);
1119 }
1120 changeStatusToOnline();
1121 }
1122
1123 private void changeStatusToOnline() {
1124 Log.d(
1125 Config.LOGTAG,
1126 account.getJid().asBareJid() + ": online with resource " + account.getResource());
1127 changeStatus(Account.State.ONLINE);
1128 }
1129
1130 private void processFailed(final Element failed, final boolean sendBindRequest) {
1131 final Optional<Integer> serverCount = failed.getOptionalIntAttribute("h");
1132 if (serverCount.isPresent()) {
1133 Log.d(
1134 Config.LOGTAG,
1135 account.getJid().asBareJid()
1136 + ": resumption failed but server acknowledged stanza #"
1137 + serverCount.get());
1138 final boolean acknowledgedMessages;
1139 synchronized (this.mStanzaQueue) {
1140 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount.get());
1141 }
1142 if (acknowledgedMessages) {
1143 mXmppConnectionService.updateConversationUi();
1144 }
1145 } else {
1146 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
1147 }
1148 resetStreamId();
1149 if (sendBindRequest) {
1150 sendBindRequest();
1151 }
1152 }
1153
1154 private boolean acknowledgeStanzaUpTo(final int serverCount) {
1155 if (serverCount > stanzasSent) {
1156 Log.e(
1157 Config.LOGTAG,
1158 "server acknowledged more stanzas than we sent. serverCount="
1159 + serverCount
1160 + ", ourCount="
1161 + stanzasSent);
1162 }
1163 boolean acknowledgedMessages = false;
1164 for (int i = 0; i < mStanzaQueue.size(); ++i) {
1165 if (serverCount >= mStanzaQueue.keyAt(i)) {
1166 if (Config.EXTENDED_SM_LOGGING) {
1167 Log.d(
1168 Config.LOGTAG,
1169 account.getJid().asBareJid()
1170 + ": server acknowledged stanza #"
1171 + mStanzaQueue.keyAt(i));
1172 }
1173 final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1174 if (stanza instanceof MessagePacket packet && acknowledgedListener != null) {
1175 final String id = packet.getId();
1176 final Jid to = packet.getTo();
1177 if (id != null && to != null) {
1178 acknowledgedMessages |=
1179 acknowledgedListener.onMessageAcknowledged(account, to, id);
1180 }
1181 }
1182 mStanzaQueue.removeAt(i);
1183 i--;
1184 }
1185 }
1186 return acknowledgedMessages;
1187 }
1188
1189 private @NonNull Element processPacket(final Tag currentTag, final int packetType)
1190 throws IOException {
1191 final Element element =
1192 switch (packetType) {
1193 case PACKET_IQ -> new IqPacket();
1194 case PACKET_MESSAGE -> new MessagePacket();
1195 case PACKET_PRESENCE -> new PresencePacket();
1196 default -> throw new AssertionError("Should never encounter invalid type");
1197 };
1198 element.setAttributes(currentTag.getAttributes());
1199 Tag nextTag = tagReader.readTag();
1200 if (nextTag == null) {
1201 throw new IOException("interrupted mid tag");
1202 }
1203 while (!nextTag.isEnd(element.getName())) {
1204 if (!nextTag.isNo()) {
1205 element.addChild(tagReader.readElement(nextTag));
1206 }
1207 nextTag = tagReader.readTag();
1208 if (nextTag == null) {
1209 throw new IOException("interrupted mid tag");
1210 }
1211 }
1212 if (stanzasReceived == Integer.MAX_VALUE) {
1213 resetStreamId();
1214 throw new IOException("time to restart the session. cant handle >2 billion pcks");
1215 }
1216 if (inSmacksSession) {
1217 ++stanzasReceived;
1218 } else if (features.sm()) {
1219 Log.d(
1220 Config.LOGTAG,
1221 account.getJid().asBareJid()
1222 + ": not counting stanza("
1223 + element.getClass().getSimpleName()
1224 + "). Not in smacks session.");
1225 }
1226 lastPacketReceived = SystemClock.elapsedRealtime();
1227 if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
1228 Log.d(Config.LOGTAG, "[background stanza] " + element);
1229 }
1230 if (element instanceof IqPacket
1231 && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
1232 && element.hasChild("jingle", Namespace.JINGLE)) {
1233 return JinglePacket.upgrade((IqPacket) element);
1234 } else {
1235 return element;
1236 }
1237 }
1238
1239 private void processIq(final Tag currentTag) throws IOException {
1240 final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
1241 if (!packet.valid()) {
1242 Log.e(
1243 Config.LOGTAG,
1244 "encountered invalid iq from='"
1245 + packet.getFrom()
1246 + "' to='"
1247 + packet.getTo()
1248 + "'");
1249 return;
1250 }
1251 if (Thread.currentThread().isInterrupted()) {
1252 Log.d(
1253 Config.LOGTAG,
1254 account.getJid().asBareJid() + "Not processing iq. Thread was interrupted");
1255 return;
1256 }
1257 if (packet instanceof JinglePacket jinglePacket && isBound) {
1258 if (this.jingleListener != null) {
1259 this.jingleListener.onJinglePacketReceived(account, jinglePacket);
1260 }
1261 } else {
1262 final OnIqPacketReceived callback = getIqPacketReceivedCallback(packet);
1263 if (callback == null) {
1264 Log.d(
1265 Config.LOGTAG,
1266 account.getJid().asBareJid().toString()
1267 + ": no callback registered for IQ from "
1268 + packet.getFrom());
1269 return;
1270 }
1271 try {
1272 callback.onIqPacketReceived(account, packet);
1273 } catch (final StateChangingError error) {
1274 throw new StateChangingException(error.state);
1275 }
1276 }
1277 }
1278
1279 private OnIqPacketReceived getIqPacketReceivedCallback(final IqPacket stanza)
1280 throws StateChangingException {
1281 final boolean isRequest =
1282 stanza.getType() == IqPacket.TYPE.GET || stanza.getType() == IqPacket.TYPE.SET;
1283 if (isRequest) {
1284 if (isBound) {
1285 return this.unregisteredIqListener;
1286 } else {
1287 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1288 }
1289 } else {
1290 synchronized (this.packetCallbacks) {
1291 final var pair = packetCallbacks.get(stanza.getId());
1292 if (pair == null) {
1293 return null;
1294 }
1295 if (pair.first.toServer(account)) {
1296 if (stanza.fromServer(account)) {
1297 packetCallbacks.remove(stanza.getId());
1298 return pair.second;
1299 } else {
1300 Log.e(
1301 Config.LOGTAG,
1302 account.getJid().asBareJid().toString()
1303 + ": ignoring spoofed iq packet");
1304 }
1305 } else {
1306 if (stanza.getFrom() != null && stanza.getFrom().equals(pair.first.getTo())) {
1307 packetCallbacks.remove(stanza.getId());
1308 return pair.second;
1309 } else {
1310 Log.e(
1311 Config.LOGTAG,
1312 account.getJid().asBareJid().toString()
1313 + ": ignoring spoofed iq packet");
1314 }
1315 }
1316 }
1317 }
1318 return null;
1319 }
1320
1321 private void processMessage(final Tag currentTag) throws IOException {
1322 final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
1323 if (!packet.valid()) {
1324 Log.e(
1325 Config.LOGTAG,
1326 "encountered invalid message from='"
1327 + packet.getFrom()
1328 + "' to='"
1329 + packet.getTo()
1330 + "'");
1331 return;
1332 }
1333 if (Thread.currentThread().isInterrupted()) {
1334 Log.d(
1335 Config.LOGTAG,
1336 account.getJid().asBareJid()
1337 + "Not processing message. Thread was interrupted");
1338 return;
1339 }
1340 this.messageListener.onMessagePacketReceived(account, packet);
1341 }
1342
1343 private void processPresence(final Tag currentTag) throws IOException {
1344 final PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
1345 if (!packet.valid()) {
1346 Log.e(
1347 Config.LOGTAG,
1348 "encountered invalid presence from='"
1349 + packet.getFrom()
1350 + "' to='"
1351 + packet.getTo()
1352 + "'");
1353 return;
1354 }
1355 if (Thread.currentThread().isInterrupted()) {
1356 Log.d(
1357 Config.LOGTAG,
1358 account.getJid().asBareJid()
1359 + "Not processing presence. Thread was interrupted");
1360 return;
1361 }
1362 this.presenceListener.onPresencePacketReceived(account, packet);
1363 }
1364
1365 private void sendStartTLS() throws IOException {
1366 final Tag startTLS = Tag.empty("starttls");
1367 startTLS.setAttribute("xmlns", Namespace.TLS);
1368 tagWriter.writeTag(startTLS);
1369 }
1370
1371 private void switchOverToTls() throws XmlPullParserException, IOException {
1372 tagReader.readTag();
1373 final Socket socket = this.socket;
1374 final SSLSocket sslSocket = upgradeSocketToTls(socket);
1375 this.socket = sslSocket;
1376 this.tagReader.setInputStream(sslSocket.getInputStream());
1377 this.tagWriter.setOutputStream(sslSocket.getOutputStream());
1378 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
1379 final boolean quickStart;
1380 try {
1381 quickStart = establishStream(SSLSockets.version(sslSocket));
1382 } catch (final InterruptedException e) {
1383 return;
1384 }
1385 if (quickStart) {
1386 this.quickStartInProgress = true;
1387 }
1388 features.encryptionEnabled = true;
1389 final Tag tag = tagReader.readTag();
1390 if (tag != null && tag.isStart("stream", Namespace.STREAMS)) {
1391 SSLSockets.log(account, sslSocket);
1392 processStream();
1393 } else {
1394 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
1395 }
1396 sslSocket.close();
1397 }
1398
1399 private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
1400 final SSLSocketFactory sslSocketFactory;
1401 try {
1402 sslSocketFactory = getSSLSocketFactory();
1403 } catch (final NoSuchAlgorithmException | KeyManagementException e) {
1404 throw new StateChangingException(Account.State.TLS_ERROR);
1405 }
1406 final InetAddress address = socket.getInetAddress();
1407 final SSLSocket sslSocket =
1408 (SSLSocket)
1409 sslSocketFactory.createSocket(
1410 socket, address.getHostAddress(), socket.getPort(), true);
1411 SSLSockets.setSecurity(sslSocket);
1412 SSLSockets.setHostname(sslSocket, IDN.toASCII(account.getServer()));
1413 SSLSockets.setApplicationProtocol(sslSocket, "xmpp-client");
1414 final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
1415 try {
1416 if (!xmppDomainVerifier.verify(
1417 account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
1418 Log.d(
1419 Config.LOGTAG,
1420 account.getJid().asBareJid()
1421 + ": TLS certificate domain verification failed");
1422 FileBackend.close(sslSocket);
1423 throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
1424 }
1425 } catch (final SSLPeerUnverifiedException e) {
1426 FileBackend.close(sslSocket);
1427 throw new StateChangingException(Account.State.TLS_ERROR);
1428 }
1429 return sslSocket;
1430 }
1431
1432 private void processStreamFeatures(final Tag currentTag) throws IOException {
1433 this.streamFeatures = tagReader.readElement(currentTag);
1434 final boolean isSecure = isSecure();
1435 final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
1436 if (this.quickStartInProgress) {
1437 if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1438 Log.d(
1439 Config.LOGTAG,
1440 account.getJid().asBareJid()
1441 + ": quick start in progress. ignoring features: "
1442 + XmlHelper.printElementNames(this.streamFeatures));
1443 if (SaslMechanism.hashedToken(LoginInfo.mechanism(this.loginInfo))) {
1444 return;
1445 }
1446 if (isFastTokenAvailable(
1447 this.streamFeatures.findChild("authentication", Namespace.SASL_2))) {
1448 Log.d(
1449 Config.LOGTAG,
1450 account.getJid().asBareJid()
1451 + ": fast token available; resetting quick start");
1452 account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1453 mXmppConnectionService.databaseBackend.updateAccount(account);
1454 }
1455 return;
1456 }
1457 Log.d(
1458 Config.LOGTAG,
1459 account.getJid().asBareJid()
1460 + ": server lost support for SASL 2. quick start not possible");
1461 this.account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, false);
1462 mXmppConnectionService.databaseBackend.updateAccount(account);
1463 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1464 }
1465 if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
1466 && !features.encryptionEnabled) {
1467 sendStartTLS();
1468 } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1469 && account.isOptionSet(Account.OPTION_REGISTER)) {
1470 if (isSecure) {
1471 register();
1472 } else {
1473 Log.d(
1474 Config.LOGTAG,
1475 account.getJid().asBareJid()
1476 + ": unable to find STARTTLS for registration process "
1477 + XmlHelper.printElementNames(this.streamFeatures));
1478 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1479 }
1480 } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
1481 && account.isOptionSet(Account.OPTION_REGISTER)) {
1482 throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
1483 } else if (this.streamFeatures.hasChild("authentication", Namespace.SASL_2)
1484 && shouldAuthenticate
1485 && isSecure) {
1486 authenticate(SaslMechanism.Version.SASL_2);
1487 } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
1488 && shouldAuthenticate
1489 && isSecure) {
1490 authenticate(SaslMechanism.Version.SASL);
1491 } else if (this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT)
1492 && isSecure
1493 && LoginInfo.isSuccess(loginInfo)
1494 && streamId != null
1495 && !inSmacksSession) {
1496 if (Config.EXTENDED_SM_LOGGING) {
1497 Log.d(
1498 Config.LOGTAG,
1499 account.getJid().asBareJid()
1500 + ": resuming after stanza #"
1501 + stanzasReceived);
1502 }
1503 final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1504 this.mSmCatchupMessageCounter.set(0);
1505 this.mWaitingForSmCatchup.set(true);
1506 this.tagWriter.writeStanzaAsync(resume);
1507 } else if (needsBinding) {
1508 if (this.streamFeatures.hasChild("bind", Namespace.BIND)
1509 && isSecure
1510 && LoginInfo.isSuccess(loginInfo)) {
1511 sendBindRequest();
1512 } else {
1513 Log.d(
1514 Config.LOGTAG,
1515 account.getJid().asBareJid()
1516 + ": unable to find bind feature "
1517 + XmlHelper.printElementNames(this.streamFeatures));
1518 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1519 }
1520 } else {
1521 Log.d(
1522 Config.LOGTAG,
1523 account.getJid().asBareJid()
1524 + ": received NOP stream features: "
1525 + XmlHelper.printElementNames(this.streamFeatures));
1526 }
1527 }
1528
1529 private void authenticate() throws IOException {
1530 final boolean isSecure = isSecure();
1531 if (isSecure && this.streamFeatures.hasChild("authentication", Namespace.SASL_2)) {
1532 authenticate(SaslMechanism.Version.SASL_2);
1533 } else if (isSecure && this.streamFeatures.hasChild("mechanisms", Namespace.SASL)) {
1534 authenticate(SaslMechanism.Version.SASL);
1535 } else {
1536 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1537 }
1538 }
1539
1540 private boolean isSecure() {
1541 return features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
1542 }
1543
1544 private void authenticate(final SaslMechanism.Version version) throws IOException {
1545 final Element authElement;
1546 if (version == SaslMechanism.Version.SASL) {
1547 authElement = this.streamFeatures.findChild("mechanisms", Namespace.SASL);
1548 } else {
1549 authElement = this.streamFeatures.findChild("authentication", Namespace.SASL_2);
1550 }
1551 final Collection<String> mechanisms = SaslMechanism.mechanisms(authElement);
1552 final Element cbElement =
1553 this.streamFeatures.findChild("sasl-channel-binding", Namespace.CHANNEL_BINDING);
1554 final Collection<ChannelBinding> channelBindings = ChannelBinding.of(cbElement);
1555 final SaslMechanism.Factory factory = new SaslMechanism.Factory(account);
1556 final SaslMechanism saslMechanism =
1557 factory.of(mechanisms, channelBindings, version, SSLSockets.version(this.socket));
1558 this.validate(saslMechanism, mechanisms);
1559 final boolean quickStartAvailable;
1560 final String firstMessage =
1561 saslMechanism.getClientFirstMessage(sslSocketOrNull(this.socket));
1562 final boolean usingFast = SaslMechanism.hashedToken(saslMechanism);
1563 final Element authenticate;
1564 if (version == SaslMechanism.Version.SASL) {
1565 authenticate = new Element("auth", Namespace.SASL);
1566 if (!Strings.isNullOrEmpty(firstMessage)) {
1567 authenticate.setContent(firstMessage);
1568 }
1569 quickStartAvailable = false;
1570 this.loginInfo = new LoginInfo(saslMechanism, version, Collections.emptyList());
1571 } else if (version == SaslMechanism.Version.SASL_2) {
1572 final Element inline = authElement.findChild("inline", Namespace.SASL_2);
1573 final boolean sm = inline != null && inline.hasChild("sm", Namespace.STREAM_MANAGEMENT);
1574 final HashedToken.Mechanism hashTokenRequest;
1575 if (usingFast) {
1576 hashTokenRequest = null;
1577 } else {
1578 final Element fast =
1579 inline == null ? null : inline.findChild("fast", Namespace.FAST);
1580 final Collection<String> fastMechanisms = SaslMechanism.mechanisms(fast);
1581 hashTokenRequest =
1582 HashedToken.Mechanism.best(fastMechanisms, SSLSockets.version(this.socket));
1583 }
1584 final Collection<String> bindFeatures = Bind2.features(inline);
1585 quickStartAvailable =
1586 sm
1587 && bindFeatures != null
1588 && bindFeatures.containsAll(Bind2.QUICKSTART_FEATURES);
1589 if (bindFeatures != null) {
1590 try {
1591 mXmppConnectionService.restoredFromDatabaseLatch.await();
1592 } catch (final InterruptedException e) {
1593 Log.d(
1594 Config.LOGTAG,
1595 account.getJid().asBareJid()
1596 + ": interrupted while waiting for DB restore during SASL2 bind");
1597 return;
1598 }
1599 }
1600 this.loginInfo = new LoginInfo(saslMechanism, version, bindFeatures);
1601 this.hashTokenRequest = hashTokenRequest;
1602 authenticate =
1603 generateAuthenticationRequest(
1604 firstMessage, usingFast, hashTokenRequest, bindFeatures, sm);
1605 } else {
1606 throw new AssertionError("Missing implementation for " + version);
1607 }
1608
1609 if (account.setOption(Account.OPTION_QUICKSTART_AVAILABLE, quickStartAvailable)) {
1610 mXmppConnectionService.databaseBackend.updateAccount(account);
1611 }
1612
1613 Log.d(
1614 Config.LOGTAG,
1615 account.getJid().toString()
1616 + ": Authenticating with "
1617 + version
1618 + "/"
1619 + LoginInfo.mechanism(this.loginInfo).getMechanism());
1620 authenticate.setAttribute("mechanism", LoginInfo.mechanism(this.loginInfo).getMechanism());
1621 synchronized (this.mStanzaQueue) {
1622 this.stanzasSentBeforeAuthentication = this.stanzasSent;
1623 tagWriter.writeElement(authenticate);
1624 }
1625 }
1626
1627 private static boolean isFastTokenAvailable(final Element authentication) {
1628 final Element inline = authentication == null ? null : authentication.findChild("inline");
1629 return inline != null && inline.hasChild("fast", Namespace.FAST);
1630 }
1631
1632 private void validate(
1633 final @Nullable SaslMechanism saslMechanism, Collection<String> mechanisms)
1634 throws StateChangingException {
1635 if (saslMechanism == null) {
1636 Log.d(
1637 Config.LOGTAG,
1638 account.getJid().asBareJid()
1639 + ": unable to find supported SASL mechanism in "
1640 + mechanisms);
1641 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
1642 }
1643 if (SaslMechanism.hashedToken(saslMechanism)) {
1644 return;
1645 }
1646 final int pinnedMechanism = account.getPinnedMechanismPriority();
1647 if (pinnedMechanism > saslMechanism.getPriority()) {
1648 Log.e(
1649 Config.LOGTAG,
1650 "Auth failed. Authentication mechanism "
1651 + saslMechanism.getMechanism()
1652 + " has lower priority ("
1653 + saslMechanism.getPriority()
1654 + ") than pinned priority ("
1655 + pinnedMechanism
1656 + "). Possible downgrade attack?");
1657 throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
1658 }
1659 }
1660
1661 private Element generateAuthenticationRequest(
1662 final String firstMessage, final boolean usingFast) {
1663 return generateAuthenticationRequest(
1664 firstMessage, usingFast, null, Bind2.QUICKSTART_FEATURES, true);
1665 }
1666
1667 private Element generateAuthenticationRequest(
1668 final String firstMessage,
1669 final boolean usingFast,
1670 final HashedToken.Mechanism hashedTokenRequest,
1671 final Collection<String> bind,
1672 final boolean inlineStreamManagement) {
1673 final Element authenticate = new Element("authenticate", Namespace.SASL_2);
1674 if (!Strings.isNullOrEmpty(firstMessage)) {
1675 authenticate.addChild("initial-response").setContent(firstMessage);
1676 }
1677 final Element userAgent = authenticate.addChild("user-agent");
1678 userAgent.setAttribute("id", AccountUtils.publicDeviceId(account));
1679 userAgent
1680 .addChild("software")
1681 .setContent(mXmppConnectionService.getString(R.string.app_name));
1682 if (!PhoneHelper.isEmulator()) {
1683 userAgent
1684 .addChild("device")
1685 .setContent(String.format("%s %s", Build.MANUFACTURER, Build.MODEL));
1686 }
1687 // do not include bind if 'inlineStreamManagement' is missing and we have a streamId
1688 // (because we would rather just do a normal SM/resume)
1689 final boolean mayAttemptBind = streamId == null || inlineStreamManagement;
1690 if (bind != null && mayAttemptBind) {
1691 authenticate.addChild(generateBindRequest(bind));
1692 }
1693 if (inlineStreamManagement && streamId != null) {
1694 final ResumePacket resume = new ResumePacket(this.streamId.id, stanzasReceived);
1695 this.mSmCatchupMessageCounter.set(0);
1696 this.mWaitingForSmCatchup.set(true);
1697 authenticate.addChild(resume);
1698 }
1699 if (hashedTokenRequest != null) {
1700 authenticate
1701 .addChild("request-token", Namespace.FAST)
1702 .setAttribute("mechanism", hashedTokenRequest.name());
1703 }
1704 if (usingFast) {
1705 authenticate.addChild("fast", Namespace.FAST);
1706 }
1707 return authenticate;
1708 }
1709
1710 private Element generateBindRequest(final Collection<String> bindFeatures) {
1711 Log.d(Config.LOGTAG, "inline bind features: " + bindFeatures);
1712 final Element bind = new Element("bind", Namespace.BIND2);
1713 bind.addChild("tag").setContent(mXmppConnectionService.getString(R.string.app_name));
1714 if (bindFeatures.contains(Namespace.CARBONS)) {
1715 bind.addChild("enable", Namespace.CARBONS);
1716 }
1717 if (bindFeatures.contains(Namespace.STREAM_MANAGEMENT)) {
1718 bind.addChild(new EnablePacket());
1719 }
1720 return bind;
1721 }
1722
1723 private void register() {
1724 final String preAuth = account.getKey(Account.KEY_PRE_AUTH_REGISTRATION_TOKEN);
1725 if (preAuth != null && features.invite()) {
1726 final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1727 preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1728 sendUnmodifiedIqPacket(
1729 preAuthRequest,
1730 (account, response) -> {
1731 if (response.getType() == IqPacket.TYPE.RESULT) {
1732 sendRegistryRequest();
1733 } else {
1734 final String error = response.getErrorCondition();
1735 Log.d(
1736 Config.LOGTAG,
1737 account.getJid().asBareJid()
1738 + ": failed to pre auth. "
1739 + error);
1740 throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1741 }
1742 },
1743 true);
1744 } else {
1745 sendRegistryRequest();
1746 }
1747 }
1748
1749 private void sendRegistryRequest() {
1750 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1751 register.query(Namespace.REGISTER);
1752 register.setTo(account.getDomain());
1753 sendUnmodifiedIqPacket(
1754 register,
1755 (account, packet) -> {
1756 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1757 return;
1758 }
1759 if (packet.getType() == IqPacket.TYPE.ERROR) {
1760 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1761 }
1762 final Element query = packet.query(Namespace.REGISTER);
1763 if (query.hasChild("username") && (query.hasChild("password"))) {
1764 final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1765 final Element username =
1766 new Element("username").setContent(account.getUsername());
1767 final Element password =
1768 new Element("password").setContent(account.getPassword());
1769 register1.query(Namespace.REGISTER).addChild(username);
1770 register1.query().addChild(password);
1771 register1.setFrom(account.getJid().asBareJid());
1772 sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1773 } else if (query.hasChild("x", Namespace.DATA)) {
1774 final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1775 final Element blob = query.findChild("data", "urn:xmpp:bob");
1776 final String id = packet.getId();
1777 InputStream is;
1778 if (blob != null) {
1779 try {
1780 final String base64Blob = blob.getContent();
1781 final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1782 is = new ByteArrayInputStream(strBlob);
1783 } catch (Exception e) {
1784 is = null;
1785 }
1786 } else {
1787 final boolean useTor =
1788 mXmppConnectionService.useTorToConnect() || account.isOnion();
1789 try {
1790 final String url = data.getValue("url");
1791 final String fallbackUrl = data.getValue("captcha-fallback-url");
1792 if (url != null) {
1793 is = HttpConnectionManager.open(url, useTor);
1794 } else if (fallbackUrl != null) {
1795 is = HttpConnectionManager.open(fallbackUrl, useTor);
1796 } else {
1797 is = null;
1798 }
1799 } catch (final IOException e) {
1800 Log.d(
1801 Config.LOGTAG,
1802 account.getJid().asBareJid() + ": unable to fetch captcha",
1803 e);
1804 is = null;
1805 }
1806 }
1807
1808 if (is != null) {
1809 Bitmap captcha = BitmapFactory.decodeStream(is);
1810 try {
1811 if (mXmppConnectionService.displayCaptchaRequest(
1812 account, id, data, captcha)) {
1813 return;
1814 }
1815 } catch (Exception e) {
1816 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1817 }
1818 }
1819 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1820 } else if (query.hasChild("instructions")
1821 || query.hasChild("x", Namespace.OOB)) {
1822 final String instructions = query.findChildContent("instructions");
1823 final Element oob = query.findChild("x", Namespace.OOB);
1824 final String url = oob == null ? null : oob.findChildContent("url");
1825 if (url != null) {
1826 setAccountCreationFailed(url);
1827 } else if (instructions != null) {
1828 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1829 if (matcher.find()) {
1830 setAccountCreationFailed(
1831 instructions.substring(matcher.start(), matcher.end()));
1832 }
1833 }
1834 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1835 }
1836 },
1837 true);
1838 }
1839
1840 private void setAccountCreationFailed(final String url) {
1841 final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1842 if (httpUrl != null && httpUrl.isHttps()) {
1843 this.redirectionUrl = httpUrl;
1844 throw new StateChangingError(Account.State.REGISTRATION_WEB);
1845 }
1846 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1847 }
1848
1849 public HttpUrl getRedirectionUrl() {
1850 return this.redirectionUrl;
1851 }
1852
1853 public void resetEverything() {
1854 resetAttemptCount(true);
1855 resetStreamId();
1856 clearIqCallbacks();
1857 synchronized (this.mStanzaQueue) {
1858 this.stanzasSent = 0;
1859 this.mStanzaQueue.clear();
1860 }
1861 this.redirectionUrl = null;
1862 synchronized (this.disco) {
1863 disco.clear();
1864 }
1865 synchronized (this.commands) {
1866 this.commands.clear();
1867 }
1868 this.loginInfo = null;
1869 }
1870
1871 private void sendBindRequest() {
1872 try {
1873 mXmppConnectionService.restoredFromDatabaseLatch.await();
1874 } catch (InterruptedException e) {
1875 Log.d(
1876 Config.LOGTAG,
1877 account.getJid().asBareJid()
1878 + ": interrupted while waiting for DB restore during bind");
1879 return;
1880 }
1881 clearIqCallbacks();
1882 if (account.getJid().isBareJid()) {
1883 account.setResource(this.createNewResource());
1884 } else {
1885 fixResource(mXmppConnectionService, account);
1886 }
1887 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1888 final String resource =
1889 Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1890 iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1891 this.sendUnmodifiedIqPacket(
1892 iq,
1893 (account, packet) -> {
1894 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1895 return;
1896 }
1897 final Element bind = packet.findChild("bind");
1898 if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1899 isBound = true;
1900 final Element jid = bind.findChild("jid");
1901 if (jid != null && jid.getContent() != null) {
1902 try {
1903 Jid assignedJid = Jid.ofEscaped(jid.getContent());
1904 if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1905 Log.d(
1906 Config.LOGTAG,
1907 account.getJid().asBareJid()
1908 + ": server tried to re-assign domain to "
1909 + assignedJid.getDomain());
1910 throw new StateChangingError(Account.State.BIND_FAILURE);
1911 }
1912 if (account.setJid(assignedJid)) {
1913 Log.d(
1914 Config.LOGTAG,
1915 account.getJid().asBareJid()
1916 + ": jid changed during bind. updating database");
1917 mXmppConnectionService.databaseBackend.updateAccount(account);
1918 }
1919 if (streamFeatures.hasChild("session")
1920 && !streamFeatures
1921 .findChild("session")
1922 .hasChild("optional")) {
1923 sendStartSession();
1924 } else {
1925 final boolean waitForDisco = enableStreamManagement();
1926 sendPostBindInitialization(waitForDisco, false);
1927 }
1928 return;
1929 } catch (final IllegalArgumentException e) {
1930 Log.d(
1931 Config.LOGTAG,
1932 account.getJid().asBareJid()
1933 + ": server reported invalid jid ("
1934 + jid.getContent()
1935 + ") on bind");
1936 }
1937 } else {
1938 Log.d(
1939 Config.LOGTAG,
1940 account.getJid()
1941 + ": disconnecting because of bind failure. (no jid)");
1942 }
1943 } else {
1944 Log.d(
1945 Config.LOGTAG,
1946 account.getJid()
1947 + ": disconnecting because of bind failure ("
1948 + packet);
1949 }
1950 final Element error = packet.findChild("error");
1951 if (packet.getType() == IqPacket.TYPE.ERROR
1952 && error != null
1953 && error.hasChild("conflict")) {
1954 account.setResource(createNewResource());
1955 }
1956 throw new StateChangingError(Account.State.BIND_FAILURE);
1957 },
1958 true);
1959 }
1960
1961 private void clearIqCallbacks() {
1962 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1963 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1964 synchronized (this.packetCallbacks) {
1965 if (this.packetCallbacks.size() == 0) {
1966 return;
1967 }
1968 Log.d(
1969 Config.LOGTAG,
1970 account.getJid().asBareJid()
1971 + ": clearing "
1972 + this.packetCallbacks.size()
1973 + " iq callbacks");
1974 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator =
1975 this.packetCallbacks.values().iterator();
1976 while (iterator.hasNext()) {
1977 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1978 callbacks.add(entry.second);
1979 iterator.remove();
1980 }
1981 }
1982 for (OnIqPacketReceived callback : callbacks) {
1983 try {
1984 callback.onIqPacketReceived(account, failurePacket);
1985 } catch (StateChangingError error) {
1986 Log.d(
1987 Config.LOGTAG,
1988 account.getJid().asBareJid()
1989 + ": caught StateChangingError("
1990 + error.state.toString()
1991 + ") while clearing callbacks");
1992 // ignore
1993 }
1994 }
1995 Log.d(
1996 Config.LOGTAG,
1997 account.getJid().asBareJid()
1998 + ": done clearing iq callbacks. "
1999 + this.packetCallbacks.size()
2000 + " left");
2001 }
2002
2003 public void sendDiscoTimeout() {
2004 if (mWaitForDisco.compareAndSet(true, false)) {
2005 Log.d(
2006 Config.LOGTAG,
2007 account.getJid().asBareJid() + ": finalizing bind after disco timeout");
2008 finalizeBind();
2009 }
2010 }
2011
2012 private void sendStartSession() {
2013 Log.d(
2014 Config.LOGTAG,
2015 account.getJid().asBareJid() + ": sending legacy session to outdated server");
2016 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
2017 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
2018 this.sendUnmodifiedIqPacket(
2019 startSession,
2020 (account, packet) -> {
2021 if (packet.getType() == IqPacket.TYPE.RESULT) {
2022 final boolean waitForDisco = enableStreamManagement();
2023 sendPostBindInitialization(waitForDisco, false);
2024 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2025 throw new StateChangingError(Account.State.SESSION_FAILURE);
2026 }
2027 },
2028 true);
2029 }
2030
2031 private boolean enableStreamManagement() {
2032 final boolean streamManagement =
2033 this.streamFeatures.hasChild("sm", Namespace.STREAM_MANAGEMENT);
2034 if (streamManagement) {
2035 synchronized (this.mStanzaQueue) {
2036 final EnablePacket enable = new EnablePacket();
2037 tagWriter.writeStanzaAsync(enable);
2038 stanzasSent = 0;
2039 mStanzaQueue.clear();
2040 }
2041 return true;
2042 } else {
2043 return false;
2044 }
2045 }
2046
2047 private void sendPostBindInitialization(
2048 final boolean waitForDisco, final boolean carbonsEnabled) {
2049 features.carbonsEnabled = carbonsEnabled;
2050 features.blockListRequested = false;
2051 synchronized (this.disco) {
2052 this.disco.clear();
2053 }
2054 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
2055 mPendingServiceDiscoveries.set(0);
2056 mWaitForDisco.set(waitForDisco);
2057 lastDiscoStarted = SystemClock.elapsedRealtime();
2058 mXmppConnectionService.scheduleWakeUpCall(
2059 Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
2060 final Element caps = streamFeatures.findChild("c");
2061 final String hash = caps == null ? null : caps.getAttribute("hash");
2062 final String ver = caps == null ? null : caps.getAttribute("ver");
2063 ServiceDiscoveryResult discoveryResult = null;
2064 if (hash != null && ver != null) {
2065 discoveryResult =
2066 mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
2067 }
2068 final boolean requestDiscoItemsFirst =
2069 !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
2070 if (requestDiscoItemsFirst) {
2071 sendServiceDiscoveryItems(account.getDomain());
2072 }
2073 if (discoveryResult == null) {
2074 sendServiceDiscoveryInfo(account.getDomain());
2075 } else {
2076 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
2077 disco.put(account.getDomain(), discoveryResult);
2078 }
2079 discoverMamPreferences();
2080 sendServiceDiscoveryInfo(account.getJid().asBareJid());
2081 if (!requestDiscoItemsFirst) {
2082 sendServiceDiscoveryItems(account.getDomain());
2083 }
2084
2085 if (!mWaitForDisco.get()) {
2086 finalizeBind();
2087 }
2088 this.lastSessionStarted = SystemClock.elapsedRealtime();
2089 }
2090
2091 private void sendServiceDiscoveryInfo(final Jid jid) {
2092 mPendingServiceDiscoveries.incrementAndGet();
2093 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2094 iq.setTo(jid);
2095 iq.query("http://jabber.org/protocol/disco#info");
2096 this.sendIqPacket(
2097 iq,
2098 (account, packet) -> {
2099 if (packet.getType() == IqPacket.TYPE.RESULT) {
2100 boolean advancedStreamFeaturesLoaded;
2101 synchronized (XmppConnection.this.disco) {
2102 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
2103 if (jid.equals(account.getDomain())) {
2104 mXmppConnectionService.databaseBackend.insertDiscoveryResult(
2105 result);
2106 }
2107 disco.put(jid, result);
2108 advancedStreamFeaturesLoaded =
2109 disco.containsKey(account.getDomain())
2110 && disco.containsKey(account.getJid().asBareJid());
2111 }
2112 if (advancedStreamFeaturesLoaded
2113 && (jid.equals(account.getDomain())
2114 || jid.equals(account.getJid().asBareJid()))) {
2115 enableAdvancedStreamFeatures();
2116 }
2117 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
2118 Log.d(
2119 Config.LOGTAG,
2120 account.getJid().asBareJid()
2121 + ": could not query disco info for "
2122 + jid.toString());
2123 final boolean serverOrAccount =
2124 jid.equals(account.getDomain())
2125 || jid.equals(account.getJid().asBareJid());
2126 final boolean advancedStreamFeaturesLoaded;
2127 if (serverOrAccount) {
2128 synchronized (XmppConnection.this.disco) {
2129 disco.put(jid, ServiceDiscoveryResult.empty());
2130 advancedStreamFeaturesLoaded =
2131 disco.containsKey(account.getDomain())
2132 && disco.containsKey(account.getJid().asBareJid());
2133 }
2134 } else {
2135 advancedStreamFeaturesLoaded = false;
2136 }
2137 if (advancedStreamFeaturesLoaded) {
2138 enableAdvancedStreamFeatures();
2139 }
2140 }
2141 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2142 if (mPendingServiceDiscoveries.decrementAndGet() == 0
2143 && mWaitForDisco.compareAndSet(true, false)) {
2144 finalizeBind();
2145 }
2146 }
2147 });
2148 }
2149
2150 private void discoverMamPreferences() {
2151 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2152 request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
2153 sendIqPacket(
2154 request,
2155 (account, response) -> {
2156 if (response.getType() == IqPacket.TYPE.RESULT) {
2157 Element prefs =
2158 response.findChild(
2159 "prefs", MessageArchiveService.Version.MAM_2.namespace);
2160 isMamPreferenceAlways =
2161 "always"
2162 .equals(
2163 prefs == null
2164 ? null
2165 : prefs.getAttribute("default"));
2166 }
2167 });
2168 }
2169
2170 private void discoverCommands() {
2171 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
2172 request.setTo(account.getDomain());
2173 request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
2174 sendIqPacket(
2175 request,
2176 (account, response) -> {
2177 if (response.getType() == IqPacket.TYPE.RESULT) {
2178 final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
2179 if (query == null) {
2180 return;
2181 }
2182 final HashMap<String, Jid> commands = new HashMap<>();
2183 for (final Element child : query.getChildren()) {
2184 if ("item".equals(child.getName())) {
2185 final String node = child.getAttribute("node");
2186 final Jid jid = child.getAttributeAsJid("jid");
2187 if (node != null && jid != null) {
2188 commands.put(node, jid);
2189 }
2190 }
2191 }
2192 synchronized (this.commands) {
2193 this.commands.clear();
2194 this.commands.putAll(commands);
2195 }
2196 }
2197 });
2198 }
2199
2200 public boolean isMamPreferenceAlways() {
2201 return isMamPreferenceAlways;
2202 }
2203
2204 private void finalizeBind() {
2205 if (bindListener != null) {
2206 bindListener.onBind(account);
2207 }
2208 changeStatusToOnline();
2209 }
2210
2211 private void enableAdvancedStreamFeatures() {
2212 if (getFeatures().blocking() && !features.blockListRequested) {
2213 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
2214 this.sendIqPacket(
2215 getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
2216 }
2217 for (final OnAdvancedStreamFeaturesLoaded listener :
2218 advancedStreamFeaturesLoadedListeners) {
2219 listener.onAdvancedStreamFeaturesAvailable(account);
2220 }
2221 if (getFeatures().carbons() && !features.carbonsEnabled) {
2222 sendEnableCarbons();
2223 }
2224 if (getFeatures().commands()) {
2225 discoverCommands();
2226 }
2227 }
2228
2229 private void sendServiceDiscoveryItems(final Jid server) {
2230 mPendingServiceDiscoveries.incrementAndGet();
2231 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2232 iq.setTo(server.getDomain());
2233 iq.query("http://jabber.org/protocol/disco#items");
2234 this.sendIqPacket(
2235 iq,
2236 (account, packet) -> {
2237 if (packet.getType() == IqPacket.TYPE.RESULT) {
2238 final HashSet<Jid> items = new HashSet<>();
2239 final List<Element> elements = packet.query().getChildren();
2240 for (final Element element : elements) {
2241 if (element.getName().equals("item")) {
2242 final Jid jid =
2243 InvalidJid.getNullForInvalid(
2244 element.getAttributeAsJid("jid"));
2245 if (jid != null && !jid.equals(account.getDomain())) {
2246 items.add(jid);
2247 }
2248 }
2249 }
2250 for (Jid jid : items) {
2251 sendServiceDiscoveryInfo(jid);
2252 }
2253 } else {
2254 Log.d(
2255 Config.LOGTAG,
2256 account.getJid().asBareJid()
2257 + ": could not query disco items of "
2258 + server);
2259 }
2260 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
2261 if (mPendingServiceDiscoveries.decrementAndGet() == 0
2262 && mWaitForDisco.compareAndSet(true, false)) {
2263 finalizeBind();
2264 }
2265 }
2266 });
2267 }
2268
2269 private void sendEnableCarbons() {
2270 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2271 iq.addChild("enable", Namespace.CARBONS);
2272 this.sendIqPacket(
2273 iq,
2274 (account, packet) -> {
2275 if (packet.getType() == IqPacket.TYPE.RESULT) {
2276 Log.d(
2277 Config.LOGTAG,
2278 account.getJid().asBareJid() + ": successfully enabled carbons");
2279 features.carbonsEnabled = true;
2280 } else {
2281 Log.d(
2282 Config.LOGTAG,
2283 account.getJid().asBareJid()
2284 + ": could not enable carbons "
2285 + packet);
2286 }
2287 });
2288 }
2289
2290 private void processStreamError(final Tag currentTag) throws IOException {
2291 final Element streamError = tagReader.readElement(currentTag);
2292 if (streamError == null) {
2293 return;
2294 }
2295 if (streamError.hasChild("conflict")) {
2296 account.setResource(createNewResource());
2297 Log.d(
2298 Config.LOGTAG,
2299 account.getJid().asBareJid()
2300 + ": switching resource due to conflict ("
2301 + account.getResource()
2302 + ")");
2303 throw new IOException();
2304 } else if (streamError.hasChild("host-unknown")) {
2305 throw new StateChangingException(Account.State.HOST_UNKNOWN);
2306 } else if (streamError.hasChild("policy-violation")) {
2307 this.lastConnect = SystemClock.elapsedRealtime();
2308 final String text = streamError.findChildContent("text");
2309 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
2310 failPendingMessages(text);
2311 throw new StateChangingException(Account.State.POLICY_VIOLATION);
2312 } else if (streamError.hasChild("see-other-host")) {
2313 final String seeOtherHost = streamError.findChildContent("see-other-host");
2314 final Resolver.Result currentResolverResult = this.currentResolverResult;
2315 if (Strings.isNullOrEmpty(seeOtherHost) || currentResolverResult == null) {
2316 Log.d(
2317 Config.LOGTAG,
2318 account.getJid().asBareJid() + ": stream error " + streamError);
2319 throw new StateChangingException(Account.State.STREAM_ERROR);
2320 }
2321 Log.d(
2322 Config.LOGTAG,
2323 account.getJid().asBareJid()
2324 + ": see other host: "
2325 + seeOtherHost
2326 + " "
2327 + currentResolverResult);
2328 final Resolver.Result seeOtherResult = currentResolverResult.seeOtherHost(seeOtherHost);
2329 if (seeOtherResult != null) {
2330 this.seeOtherHostResolverResult = seeOtherResult;
2331 throw new StateChangingException(Account.State.SEE_OTHER_HOST);
2332 } else {
2333 throw new StateChangingException(Account.State.STREAM_ERROR);
2334 }
2335 } else {
2336 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError);
2337 throw new StateChangingException(Account.State.STREAM_ERROR);
2338 }
2339 }
2340
2341 private void failPendingMessages(final String error) {
2342 synchronized (this.mStanzaQueue) {
2343 for (int i = 0; i < mStanzaQueue.size(); ++i) {
2344 final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
2345 if (stanza instanceof MessagePacket packet) {
2346 final String id = packet.getId();
2347 final Jid to = packet.getTo();
2348 mXmppConnectionService.markMessage(
2349 account, to.asBareJid(), id, Message.STATUS_SEND_FAILED, error);
2350 }
2351 }
2352 }
2353 }
2354
2355 private boolean establishStream(final SSLSockets.Version sslVersion)
2356 throws IOException, InterruptedException {
2357 final boolean secureConnection = sslVersion != SSLSockets.Version.NONE;
2358 final SaslMechanism quickStartMechanism;
2359 if (secureConnection) {
2360 quickStartMechanism =
2361 SaslMechanism.ensureAvailable(account.getQuickStartMechanism(), sslVersion);
2362 } else {
2363 quickStartMechanism = null;
2364 }
2365 if (secureConnection
2366 && Config.QUICKSTART_ENABLED
2367 && quickStartMechanism != null
2368 && account.isOptionSet(Account.OPTION_QUICKSTART_AVAILABLE)) {
2369 mXmppConnectionService.restoredFromDatabaseLatch.await();
2370 this.loginInfo =
2371 new LoginInfo(
2372 quickStartMechanism,
2373 SaslMechanism.Version.SASL_2,
2374 Bind2.QUICKSTART_FEATURES);
2375 final boolean usingFast = quickStartMechanism instanceof HashedToken;
2376 final Element authenticate =
2377 generateAuthenticationRequest(
2378 quickStartMechanism.getClientFirstMessage(sslSocketOrNull(this.socket)),
2379 usingFast);
2380 authenticate.setAttribute("mechanism", quickStartMechanism.getMechanism());
2381 sendStartStream(true, false);
2382 synchronized (this.mStanzaQueue) {
2383 this.stanzasSentBeforeAuthentication = this.stanzasSent;
2384 tagWriter.writeElement(authenticate);
2385 }
2386 Log.d(
2387 Config.LOGTAG,
2388 account.getJid().toString()
2389 + ": quick start with "
2390 + quickStartMechanism.getMechanism());
2391 return true;
2392 } else {
2393 sendStartStream(secureConnection, true);
2394 return false;
2395 }
2396 }
2397
2398 private void sendStartStream(final boolean from, final boolean flush) throws IOException {
2399 final Tag stream = Tag.start("stream:stream");
2400 stream.setAttribute("to", account.getServer());
2401 if (from) {
2402 stream.setAttribute("from", account.getJid().asBareJid().toEscapedString());
2403 }
2404 stream.setAttribute("version", "1.0");
2405 stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
2406 stream.setAttribute("xmlns", Namespace.JABBER_CLIENT);
2407 stream.setAttribute("xmlns:stream", Namespace.STREAMS);
2408 tagWriter.writeTag(stream, flush);
2409 }
2410
2411 private String createNewResource() {
2412 return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
2413 }
2414
2415 private String nextRandomId() {
2416 return nextRandomId(false);
2417 }
2418
2419 private String nextRandomId(final boolean s) {
2420 return CryptoHelper.random(s ? 3 : 9);
2421 }
2422
2423 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2424 packet.setFrom(account.getJid());
2425 return this.sendUnmodifiedIqPacket(packet, callback, false);
2426 }
2427
2428 public synchronized String sendUnmodifiedIqPacket(
2429 final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
2430 if (packet.getId() == null) {
2431 packet.setAttribute("id", nextRandomId());
2432 }
2433 if (callback != null) {
2434 synchronized (this.packetCallbacks) {
2435 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
2436 }
2437 }
2438 this.sendPacket(packet, force);
2439 return packet.getId();
2440 }
2441
2442 public void sendMessagePacket(final MessagePacket packet) {
2443 this.sendPacket(packet);
2444 }
2445
2446 public void sendPresencePacket(final PresencePacket packet) {
2447 this.sendPacket(packet);
2448 }
2449
2450 private synchronized void sendPacket(final AbstractStanza packet) {
2451 sendPacket(packet, false);
2452 }
2453
2454 private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
2455 if (stanzasSent == Integer.MAX_VALUE) {
2456 resetStreamId();
2457 disconnect(true);
2458 return;
2459 }
2460 synchronized (this.mStanzaQueue) {
2461 if (force || isBound) {
2462 tagWriter.writeStanzaAsync(packet);
2463 } else {
2464 Log.d(
2465 Config.LOGTAG,
2466 account.getJid().asBareJid()
2467 + " do not write stanza to unbound stream "
2468 + packet.toString());
2469 }
2470 if (packet instanceof AbstractAcknowledgeableStanza stanza) {
2471 if (this.mStanzaQueue.size() != 0) {
2472 int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
2473 if (currentHighestKey != stanzasSent) {
2474 throw new AssertionError("Stanza count messed up");
2475 }
2476 }
2477
2478 ++stanzasSent;
2479 if (Config.EXTENDED_SM_LOGGING) {
2480 Log.d(
2481 Config.LOGTAG,
2482 account.getJid().asBareJid()
2483 + ": counting outbound "
2484 + packet.getName()
2485 + " as #"
2486 + stanzasSent);
2487 }
2488 this.mStanzaQueue.append(stanzasSent, stanza);
2489 if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
2490 if (Config.EXTENDED_SM_LOGGING) {
2491 Log.d(
2492 Config.LOGTAG,
2493 account.getJid().asBareJid()
2494 + ": requesting ack for message stanza #"
2495 + stanzasSent);
2496 }
2497 tagWriter.writeStanzaAsync(new RequestPacket());
2498 }
2499 }
2500 }
2501 }
2502
2503 public void sendPing() {
2504 if (!r()) {
2505 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
2506 iq.setFrom(account.getJid());
2507 iq.addChild("ping", Namespace.PING);
2508 this.sendIqPacket(iq, null);
2509 }
2510 this.lastPingSent = SystemClock.elapsedRealtime();
2511 }
2512
2513 public void setOnMessagePacketReceivedListener(final OnMessagePacketReceived listener) {
2514 this.messageListener = listener;
2515 }
2516
2517 public void setOnUnregisteredIqPacketReceivedListener(final OnIqPacketReceived listener) {
2518 this.unregisteredIqListener = listener;
2519 }
2520
2521 public void setOnPresencePacketReceivedListener(final OnPresencePacketReceived listener) {
2522 this.presenceListener = listener;
2523 }
2524
2525 public void setOnJinglePacketReceivedListener(final OnJinglePacketReceived listener) {
2526 this.jingleListener = listener;
2527 }
2528
2529 public void setOnStatusChangedListener(final OnStatusChanged listener) {
2530 this.statusListener = listener;
2531 }
2532
2533 public void setOnBindListener(final OnBindListener listener) {
2534 this.bindListener = listener;
2535 }
2536
2537 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2538 this.acknowledgedListener = listener;
2539 }
2540
2541 public void addOnAdvancedStreamFeaturesAvailableListener(
2542 final OnAdvancedStreamFeaturesLoaded listener) {
2543 this.advancedStreamFeaturesLoadedListeners.add(listener);
2544 }
2545
2546 private void forceCloseSocket() {
2547 FileBackend.close(this.socket);
2548 FileBackend.close(this.tagReader);
2549 }
2550
2551 public void interrupt() {
2552 if (this.mThread != null) {
2553 this.mThread.interrupt();
2554 }
2555 }
2556
2557 public void disconnect(final boolean force) {
2558 interrupt();
2559 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
2560 if (force) {
2561 forceCloseSocket();
2562 } else {
2563 final TagWriter currentTagWriter = this.tagWriter;
2564 if (currentTagWriter.isActive()) {
2565 currentTagWriter.finish();
2566 final Socket currentSocket = this.socket;
2567 final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
2568 try {
2569 currentTagWriter.await(1, TimeUnit.SECONDS);
2570 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
2571 currentTagWriter.writeTag(Tag.end("stream:stream"));
2572 if (streamCountDownLatch != null) {
2573 if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
2574 Log.d(
2575 Config.LOGTAG,
2576 account.getJid().asBareJid() + ": remote ended stream");
2577 } else {
2578 Log.d(
2579 Config.LOGTAG,
2580 account.getJid().asBareJid()
2581 + ": remote has not closed socket. force closing");
2582 }
2583 }
2584 } catch (InterruptedException e) {
2585 Log.d(
2586 Config.LOGTAG,
2587 account.getJid().asBareJid()
2588 + ": interrupted while gracefully closing stream");
2589 } catch (final IOException e) {
2590 Log.d(
2591 Config.LOGTAG,
2592 account.getJid().asBareJid()
2593 + ": io exception during disconnect ("
2594 + e.getMessage()
2595 + ")");
2596 } finally {
2597 FileBackend.close(currentSocket);
2598 }
2599 } else {
2600 forceCloseSocket();
2601 }
2602 }
2603 }
2604
2605 private void resetStreamId() {
2606 this.streamId = null;
2607 this.boundStreamFeatures = null;
2608 }
2609
2610 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
2611 synchronized (this.disco) {
2612 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
2613 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
2614 if (cursor.getValue().getFeatures().contains(feature)) {
2615 items.add(cursor);
2616 }
2617 }
2618 return items;
2619 }
2620 }
2621
2622 public Jid findDiscoItemByFeature(final String feature) {
2623 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
2624 if (items.size() >= 1) {
2625 return items.get(0).getKey();
2626 }
2627 return null;
2628 }
2629
2630 public boolean r() {
2631 if (getFeatures().sm()) {
2632 this.tagWriter.writeStanzaAsync(new RequestPacket());
2633 return true;
2634 } else {
2635 return false;
2636 }
2637 }
2638
2639 public List<String> getMucServersWithholdAccount() {
2640 final List<String> servers = getMucServers();
2641 servers.remove(account.getDomain().toEscapedString());
2642 return servers;
2643 }
2644
2645 public List<String> getMucServers() {
2646 List<String> servers = new ArrayList<>();
2647 synchronized (this.disco) {
2648 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
2649 final ServiceDiscoveryResult value = cursor.getValue();
2650 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
2651 && value.hasIdentity("conference", "text")
2652 && !value.getFeatures().contains("jabber:iq:gateway")
2653 && !value.hasIdentity("conference", "irc")) {
2654 servers.add(cursor.getKey().toString());
2655 }
2656 }
2657 }
2658 return servers;
2659 }
2660
2661 public String getMucServer() {
2662 List<String> servers = getMucServers();
2663 return servers.size() > 0 ? servers.get(0) : null;
2664 }
2665
2666 public int getTimeToNextAttempt(final boolean aggressive) {
2667 final int interval;
2668 if (aggressive) {
2669 interval = Math.min((int) (3 * Math.pow(1.3, attempt)), 60);
2670 } else {
2671 final int additionalTime =
2672 account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
2673 interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
2674 }
2675 final int secondsSinceLast =
2676 (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2677 return interval - secondsSinceLast;
2678 }
2679
2680 public int getAttempt() {
2681 return this.attempt;
2682 }
2683
2684 public Features getFeatures() {
2685 return this.features;
2686 }
2687
2688 public long getLastSessionEstablished() {
2689 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
2690 return System.currentTimeMillis() - diff;
2691 }
2692
2693 public long getLastConnect() {
2694 return this.lastConnect;
2695 }
2696
2697 public long getLastPingSent() {
2698 return this.lastPingSent;
2699 }
2700
2701 public long getLastDiscoStarted() {
2702 return this.lastDiscoStarted;
2703 }
2704
2705 public long getLastPacketReceived() {
2706 return this.lastPacketReceived;
2707 }
2708
2709 public void sendActive() {
2710 this.sendPacket(new ActivePacket());
2711 }
2712
2713 public void sendInactive() {
2714 this.sendPacket(new InactivePacket());
2715 }
2716
2717 public void resetAttemptCount(boolean resetConnectTime) {
2718 this.attempt = 0;
2719 if (resetConnectTime) {
2720 this.lastConnect = 0;
2721 }
2722 }
2723
2724 public void setInteractive(boolean interactive) {
2725 this.mInteractive = interactive;
2726 }
2727
2728 private IqGenerator getIqGenerator() {
2729 return mXmppConnectionService.getIqGenerator();
2730 }
2731
2732 private class MyKeyManager implements X509KeyManager {
2733 @Override
2734 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
2735 return account.getPrivateKeyAlias();
2736 }
2737
2738 @Override
2739 public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
2740 return null;
2741 }
2742
2743 @Override
2744 public X509Certificate[] getCertificateChain(String alias) {
2745 Log.d(Config.LOGTAG, "getting certificate chain");
2746 try {
2747 return KeyChain.getCertificateChain(mXmppConnectionService, alias);
2748 } catch (final Exception e) {
2749 Log.d(Config.LOGTAG, "could not get certificate chain", e);
2750 return new X509Certificate[0];
2751 }
2752 }
2753
2754 @Override
2755 public String[] getClientAliases(String s, Principal[] principals) {
2756 final String alias = account.getPrivateKeyAlias();
2757 return alias != null ? new String[] {alias} : new String[0];
2758 }
2759
2760 @Override
2761 public String[] getServerAliases(String s, Principal[] principals) {
2762 return new String[0];
2763 }
2764
2765 @Override
2766 public PrivateKey getPrivateKey(String alias) {
2767 try {
2768 return KeyChain.getPrivateKey(mXmppConnectionService, alias);
2769 } catch (Exception e) {
2770 return null;
2771 }
2772 }
2773 }
2774
2775 private static class LoginInfo {
2776 public final SaslMechanism saslMechanism;
2777 public final SaslMechanism.Version saslVersion;
2778 public final List<String> inlineBindFeatures;
2779 public final AtomicBoolean success = new AtomicBoolean(false);
2780
2781 private LoginInfo(
2782 final SaslMechanism saslMechanism,
2783 final SaslMechanism.Version saslVersion,
2784 final Collection<String> inlineBindFeatures) {
2785 Preconditions.checkNotNull(saslMechanism, "SASL Mechanism must not be null");
2786 Preconditions.checkNotNull(saslVersion, "SASL version must not be null");
2787 this.saslMechanism = saslMechanism;
2788 this.saslVersion = saslVersion;
2789 this.inlineBindFeatures =
2790 inlineBindFeatures == null
2791 ? Collections.emptyList()
2792 : ImmutableList.copyOf(inlineBindFeatures);
2793 }
2794
2795 public static SaslMechanism mechanism(final LoginInfo loginInfo) {
2796 return loginInfo == null ? null : loginInfo.saslMechanism;
2797 }
2798
2799 public void success(final String challenge, final SSLSocket sslSocket)
2800 throws SaslMechanism.AuthenticationException {
2801 final var response = this.saslMechanism.getResponse(challenge, sslSocket);
2802 if (!Strings.isNullOrEmpty(response)) {
2803 throw new SaslMechanism.AuthenticationException(
2804 "processing success yielded another response");
2805 }
2806 if (this.success.compareAndSet(false, true)) {
2807 return;
2808 }
2809 throw new SaslMechanism.AuthenticationException("Process 'success' twice");
2810 }
2811
2812 public static boolean isSuccess(final LoginInfo loginInfo) {
2813 return loginInfo != null && loginInfo.success.get();
2814 }
2815 }
2816
2817 private static class StreamId {
2818 public final String id;
2819 public final Resolver.Result location;
2820
2821 private StreamId(String id, Resolver.Result location) {
2822 this.id = id;
2823 this.location = location;
2824 }
2825
2826 @NonNull
2827 @Override
2828 public String toString() {
2829 return MoreObjects.toStringHelper(this)
2830 .add("id", id)
2831 .add("location", location)
2832 .toString();
2833 }
2834 }
2835
2836 private static class StateChangingError extends Error {
2837 private final Account.State state;
2838
2839 public StateChangingError(Account.State state) {
2840 this.state = state;
2841 }
2842 }
2843
2844 private static class StateChangingException extends IOException {
2845 private final Account.State state;
2846
2847 public StateChangingException(Account.State state) {
2848 this.state = state;
2849 }
2850 }
2851
2852 public class Features {
2853 XmppConnection connection;
2854 private boolean carbonsEnabled = false;
2855 private boolean encryptionEnabled = false;
2856 private boolean blockListRequested = false;
2857
2858 public Features(final XmppConnection connection) {
2859 this.connection = connection;
2860 }
2861
2862 private boolean hasDiscoFeature(final Jid server, final String feature) {
2863 synchronized (XmppConnection.this.disco) {
2864 final ServiceDiscoveryResult sdr = connection.disco.get(server);
2865 return sdr != null && sdr.getFeatures().contains(feature);
2866 }
2867 }
2868
2869 public boolean carbons() {
2870 return hasDiscoFeature(account.getDomain(), Namespace.CARBONS);
2871 }
2872
2873 public boolean commands() {
2874 return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
2875 }
2876
2877 public boolean easyOnboardingInvites() {
2878 synchronized (commands) {
2879 return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
2880 }
2881 }
2882
2883 public boolean bookmarksConversion() {
2884 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION)
2885 && pepPublishOptions();
2886 }
2887
2888 public boolean blocking() {
2889 return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
2890 }
2891
2892 public boolean spamReporting() {
2893 return hasDiscoFeature(account.getDomain(), Namespace.REPORTING);
2894 }
2895
2896 public boolean flexibleOfflineMessageRetrieval() {
2897 return hasDiscoFeature(
2898 account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
2899 }
2900
2901 public boolean register() {
2902 return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
2903 }
2904
2905 public boolean invite() {
2906 return connection.streamFeatures != null
2907 && connection.streamFeatures.hasChild("register", Namespace.INVITE);
2908 }
2909
2910 public boolean sm() {
2911 return streamId != null
2912 || (connection.streamFeatures != null
2913 && connection.streamFeatures.hasChild(
2914 "sm", Namespace.STREAM_MANAGEMENT));
2915 }
2916
2917 public boolean csi() {
2918 return connection.streamFeatures != null
2919 && connection.streamFeatures.hasChild("csi", Namespace.CSI);
2920 }
2921
2922 public boolean pep() {
2923 synchronized (XmppConnection.this.disco) {
2924 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2925 return info != null && info.hasIdentity("pubsub", "pep");
2926 }
2927 }
2928
2929 public boolean pepPersistent() {
2930 synchronized (XmppConnection.this.disco) {
2931 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
2932 return info != null
2933 && info.getFeatures()
2934 .contains("http://jabber.org/protocol/pubsub#persistent-items");
2935 }
2936 }
2937
2938 public boolean pepPublishOptions() {
2939 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
2940 }
2941
2942 public boolean pepOmemoWhitelisted() {
2943 return hasDiscoFeature(
2944 account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
2945 }
2946
2947 public boolean mam() {
2948 return MessageArchiveService.Version.has(getAccountFeatures());
2949 }
2950
2951 public List<String> getAccountFeatures() {
2952 ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
2953 return result == null ? Collections.emptyList() : result.getFeatures();
2954 }
2955
2956 public boolean push() {
2957 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
2958 || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
2959 }
2960
2961 public boolean rosterVersioning() {
2962 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
2963 }
2964
2965 public void setBlockListRequested(boolean value) {
2966 this.blockListRequested = value;
2967 }
2968
2969 public boolean httpUpload(long filesize) {
2970 if (Config.DISABLE_HTTP_UPLOAD) {
2971 return false;
2972 } else {
2973 for (String namespace :
2974 new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2975 List<Entry<Jid, ServiceDiscoveryResult>> items =
2976 findDiscoItemsByFeature(namespace);
2977 if (items.size() > 0) {
2978 try {
2979 long maxsize =
2980 Long.parseLong(
2981 items.get(0)
2982 .getValue()
2983 .getExtendedDiscoInformation(
2984 namespace, "max-file-size"));
2985 if (filesize <= maxsize) {
2986 return true;
2987 } else {
2988 Log.d(
2989 Config.LOGTAG,
2990 account.getJid().asBareJid()
2991 + ": http upload is not available for files with size "
2992 + filesize
2993 + " (max is "
2994 + maxsize
2995 + ")");
2996 return false;
2997 }
2998 } catch (Exception e) {
2999 return true;
3000 }
3001 }
3002 }
3003 return false;
3004 }
3005 }
3006
3007 public boolean useLegacyHttpUpload() {
3008 return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null
3009 && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
3010 }
3011
3012 public long getMaxHttpUploadSize() {
3013 for (String namespace :
3014 new String[] {Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
3015 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
3016 if (items.size() > 0) {
3017 try {
3018 return Long.parseLong(
3019 items.get(0)
3020 .getValue()
3021 .getExtendedDiscoInformation(namespace, "max-file-size"));
3022 } catch (Exception e) {
3023 // ignored
3024 }
3025 }
3026 }
3027 return -1;
3028 }
3029
3030 public boolean stanzaIds() {
3031 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
3032 }
3033
3034 public boolean bookmarks2() {
3035 return pepPublishOptions()
3036 && hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT);
3037 }
3038
3039 public boolean externalServiceDiscovery() {
3040 return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
3041 }
3042 }
3043}