1package eu.siacs.conversations.xmpp;
2
3import android.content.Context;
4import android.graphics.Bitmap;
5import android.graphics.BitmapFactory;
6import android.os.SystemClock;
7import android.security.KeyChain;
8import android.util.Base64;
9import android.util.Log;
10import android.util.Pair;
11import android.util.SparseArray;
12
13import androidx.annotation.NonNull;
14
15import com.google.common.base.Strings;
16
17import org.xmlpull.v1.XmlPullParserException;
18
19import java.io.ByteArrayInputStream;
20import java.io.IOException;
21import java.io.InputStream;
22import java.net.ConnectException;
23import java.net.IDN;
24import java.net.InetAddress;
25import java.net.InetSocketAddress;
26import java.net.Socket;
27import java.net.UnknownHostException;
28import java.security.KeyManagementException;
29import java.security.NoSuchAlgorithmException;
30import java.security.Principal;
31import java.security.PrivateKey;
32import java.security.cert.X509Certificate;
33import java.util.ArrayList;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.HashMap;
37import java.util.HashSet;
38import java.util.Hashtable;
39import java.util.Iterator;
40import java.util.List;
41import java.util.Map.Entry;
42import java.util.Set;
43import java.util.concurrent.CountDownLatch;
44import java.util.concurrent.TimeUnit;
45import java.util.concurrent.atomic.AtomicBoolean;
46import java.util.concurrent.atomic.AtomicInteger;
47import java.util.regex.Matcher;
48
49import javax.net.ssl.KeyManager;
50import javax.net.ssl.SSLContext;
51import javax.net.ssl.SSLPeerUnverifiedException;
52import javax.net.ssl.SSLSocket;
53import javax.net.ssl.SSLSocketFactory;
54import javax.net.ssl.X509KeyManager;
55import javax.net.ssl.X509TrustManager;
56
57import eu.siacs.conversations.Config;
58import eu.siacs.conversations.R;
59import eu.siacs.conversations.crypto.XmppDomainVerifier;
60import eu.siacs.conversations.crypto.axolotl.AxolotlService;
61import eu.siacs.conversations.crypto.sasl.Anonymous;
62import eu.siacs.conversations.crypto.sasl.DigestMd5;
63import eu.siacs.conversations.crypto.sasl.External;
64import eu.siacs.conversations.crypto.sasl.Plain;
65import eu.siacs.conversations.crypto.sasl.SaslMechanism;
66import eu.siacs.conversations.crypto.sasl.ScramSha1;
67import eu.siacs.conversations.crypto.sasl.ScramSha256;
68import eu.siacs.conversations.crypto.sasl.ScramSha512;
69import eu.siacs.conversations.entities.Account;
70import eu.siacs.conversations.entities.Message;
71import eu.siacs.conversations.entities.ServiceDiscoveryResult;
72import eu.siacs.conversations.generator.IqGenerator;
73import eu.siacs.conversations.http.HttpConnectionManager;
74import eu.siacs.conversations.persistance.FileBackend;
75import eu.siacs.conversations.services.MemorizingTrustManager;
76import eu.siacs.conversations.services.MessageArchiveService;
77import eu.siacs.conversations.services.NotificationService;
78import eu.siacs.conversations.services.XmppConnectionService;
79import eu.siacs.conversations.utils.CryptoHelper;
80import eu.siacs.conversations.utils.Patterns;
81import eu.siacs.conversations.utils.Resolver;
82import eu.siacs.conversations.utils.SSLSocketHelper;
83import eu.siacs.conversations.utils.SocksSocketFactory;
84import eu.siacs.conversations.utils.XmlHelper;
85import eu.siacs.conversations.xml.Element;
86import eu.siacs.conversations.xml.LocalizedContent;
87import eu.siacs.conversations.xml.Namespace;
88import eu.siacs.conversations.xml.Tag;
89import eu.siacs.conversations.xml.TagWriter;
90import eu.siacs.conversations.xml.XmlReader;
91import eu.siacs.conversations.xmpp.forms.Data;
92import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
93import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
94import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
95import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
96import eu.siacs.conversations.xmpp.stanzas.IqPacket;
97import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
98import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
99import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
100import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
101import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
102import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
103import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
104import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
105import okhttp3.HttpUrl;
106
107public class XmppConnection implements Runnable {
108
109 private static final int PACKET_IQ = 0;
110 private static final int PACKET_MESSAGE = 1;
111 private static final int PACKET_PRESENCE = 2;
112 public final OnIqPacketReceived registrationResponseListener = (account, packet) -> {
113 if (packet.getType() == IqPacket.TYPE.RESULT) {
114 account.setOption(Account.OPTION_REGISTER, false);
115 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": successfully registered new account on server");
116 throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
117 } else {
118 final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
119 "The password is too weak",
120 "Please use a longer password.");
121 Element error = packet.findChild("error");
122 Account.State state = Account.State.REGISTRATION_FAILED;
123 if (error != null) {
124 if (error.hasChild("conflict")) {
125 state = Account.State.REGISTRATION_CONFLICT;
126 } else if (error.hasChild("resource-constraint")
127 && "wait".equals(error.getAttribute("type"))) {
128 state = Account.State.REGISTRATION_PLEASE_WAIT;
129 } else if (error.hasChild("not-acceptable")
130 && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
131 state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
132 }
133 }
134 throw new StateChangingError(state);
135 }
136 };
137 protected final Account account;
138 private final Features features = new Features(this);
139 private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
140 private final HashMap<String, Jid> commands = new HashMap<>();
141 private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
142 private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
143 private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
144 private final XmppConnectionService mXmppConnectionService;
145 private Socket socket;
146 private XmlReader tagReader;
147 private TagWriter tagWriter = new TagWriter();
148 private boolean shouldAuthenticate = true;
149 private boolean inSmacksSession = false;
150 private boolean isBound = false;
151 private Element streamFeatures;
152 private String streamId = null;
153 private int smVersion = 3;
154 private int stanzasReceived = 0;
155 private int stanzasSent = 0;
156 private long lastPacketReceived = 0;
157 private long lastPingSent = 0;
158 private long lastConnect = 0;
159 private long lastSessionStarted = 0;
160 private long lastDiscoStarted = 0;
161 private boolean isMamPreferenceAlways = false;
162 private final AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
163 private final AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
164 private final AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
165 private final AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
166 private boolean mInteractive = false;
167 private int attempt = 0;
168 private OnPresencePacketReceived presenceListener = null;
169 private OnJinglePacketReceived jingleListener = null;
170 private OnIqPacketReceived unregisteredIqListener = null;
171 private OnMessagePacketReceived messageListener = null;
172 private OnStatusChanged statusListener = null;
173 private OnBindListener bindListener = null;
174 private OnMessageAcknowledged acknowledgedListener = null;
175 private SaslMechanism saslMechanism;
176 private HttpUrl redirectionUrl = null;
177 private String verifiedHostname = null;
178 private volatile Thread mThread;
179 private CountDownLatch mStreamCountDownLatch;
180
181
182 public XmppConnection(final Account account, final XmppConnectionService service) {
183 this.account = account;
184 this.mXmppConnectionService = service;
185 }
186
187 private static void fixResource(Context context, Account account) {
188 String resource = account.getResource();
189 int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
190 int randomPartLength = 4; // 3 bytes
191 if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
192 if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
193 account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
194 }
195 }
196 }
197
198 private static boolean validBase64(String input) {
199 try {
200 return Base64.decode(input, Base64.URL_SAFE).length == 3;
201 } catch (Throwable throwable) {
202 return false;
203 }
204 }
205
206 private void changeStatus(final Account.State nextStatus) {
207 synchronized (this) {
208 if (Thread.currentThread().isInterrupted()) {
209 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
210 return;
211 }
212 if (account.getStatus() != nextStatus) {
213 if ((nextStatus == Account.State.OFFLINE)
214 && (account.getStatus() != Account.State.CONNECTING)
215 && (account.getStatus() != Account.State.ONLINE)
216 && (account.getStatus() != Account.State.DISABLED)) {
217 return;
218 }
219 if (nextStatus == Account.State.ONLINE) {
220 this.attempt = 0;
221 }
222 account.setStatus(nextStatus);
223 } else {
224 return;
225 }
226 }
227 if (statusListener != null) {
228 statusListener.onStatusChanged(account);
229 }
230 }
231
232 public Jid getJidForCommand(final String node) {
233 synchronized (this.commands) {
234 return this.commands.get(node);
235 }
236 }
237
238 public void prepareNewConnection() {
239 this.lastConnect = SystemClock.elapsedRealtime();
240 this.lastPingSent = SystemClock.elapsedRealtime();
241 this.lastDiscoStarted = Long.MAX_VALUE;
242 this.mWaitingForSmCatchup.set(false);
243 this.changeStatus(Account.State.CONNECTING);
244 }
245
246 public boolean isWaitingForSmCatchup() {
247 return mWaitingForSmCatchup.get();
248 }
249
250 public void incrementSmCatchupMessageCounter() {
251 this.mSmCatchupMessageCounter.incrementAndGet();
252 }
253
254 protected void connect() {
255 if (mXmppConnectionService.areMessagesInitialized()) {
256 mXmppConnectionService.resetSendingToWaiting(account);
257 }
258 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
259 features.encryptionEnabled = false;
260 inSmacksSession = false;
261 isBound = false;
262 this.attempt++;
263 this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
264 try {
265 Socket localSocket;
266 shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
267 this.changeStatus(Account.State.CONNECTING);
268 final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
269 final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
270 if (useTor) {
271 String destination;
272 if (account.getHostname().isEmpty() || account.isOnion()) {
273 destination = account.getServer();
274 } else {
275 destination = account.getHostname();
276 this.verifiedHostname = destination;
277 }
278
279 final int port = account.getPort();
280 final boolean directTls = Resolver.useDirectTls(port);
281
282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor. directTls=" + directTls);
283 localSocket = SocksSocketFactory.createSocketOverTor(destination, port);
284
285 if (directTls) {
286 localSocket = upgradeSocketToTls(localSocket);
287 features.encryptionEnabled = true;
288 }
289
290 try {
291 startXmpp(localSocket);
292 } catch (InterruptedException e) {
293 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
294 return;
295 } catch (Exception e) {
296 throw new IOException(e.getMessage());
297 }
298 } else {
299 final String domain = account.getServer();
300 final List<Resolver.Result> results;
301 final boolean hardcoded = extended && !account.getHostname().isEmpty();
302 if (hardcoded) {
303 results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
304 } else {
305 results = Resolver.resolve(domain);
306 }
307 if (Thread.currentThread().isInterrupted()) {
308 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
309 return;
310 }
311 if (results.size() == 0) {
312 Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": Resolver results were empty");
313 return;
314 }
315 final Resolver.Result storedBackupResult;
316 if (hardcoded) {
317 storedBackupResult = null;
318 } else {
319 storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
320 if (storedBackupResult != null && !results.contains(storedBackupResult)) {
321 results.add(storedBackupResult);
322 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
323 }
324 }
325 for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
326 final Resolver.Result result = iterator.next();
327 if (Thread.currentThread().isInterrupted()) {
328 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
329 return;
330 }
331 try {
332 // if tls is true, encryption is implied and must not be started
333 features.encryptionEnabled = result.isDirectTls();
334 verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
335 Log.d(Config.LOGTAG, "verified hostname " + verifiedHostname);
336 final InetSocketAddress addr;
337 if (result.getIp() != null) {
338 addr = new InetSocketAddress(result.getIp(), result.getPort());
339 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
340 + ": using values from resolver " + (result.getHostname() == null ? "" : result.getHostname().toString()
341 + "/") + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
342 } else {
343 addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
344 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
345 + ": using values from resolver "
346 + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
347 }
348
349 localSocket = new Socket();
350 localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
351
352 if (features.encryptionEnabled) {
353 localSocket = upgradeSocketToTls(localSocket);
354 }
355
356 localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
357 if (startXmpp(localSocket)) {
358 localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
359 if (!hardcoded && !result.equals(storedBackupResult)) {
360 mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
361 }
362 break; // successfully connected to server that speaks xmpp
363 } else {
364 FileBackend.close(localSocket);
365 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
366 }
367 } catch (final StateChangingException e) {
368 if (!iterator.hasNext()) {
369 throw e;
370 }
371 } catch (InterruptedException e) {
372 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
373 return;
374 } catch (final Throwable e) {
375 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
376 if (!iterator.hasNext()) {
377 throw new UnknownHostException();
378 }
379 }
380 }
381 }
382 processStream();
383 } catch (final SecurityException e) {
384 this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
385 } catch (final StateChangingException e) {
386 this.changeStatus(e.state);
387 } catch (final UnknownHostException | ConnectException | SocksSocketFactory.HostNotFoundException e) {
388 this.changeStatus(Account.State.SERVER_NOT_FOUND);
389 } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
390 this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
391 } catch (final IOException | XmlPullParserException e) {
392 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
393 this.changeStatus(Account.State.OFFLINE);
394 this.attempt = Math.max(0, this.attempt - 1);
395 } finally {
396 if (!Thread.currentThread().isInterrupted()) {
397 forceCloseSocket();
398 } else {
399 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
400 }
401 }
402 }
403
404 /**
405 * Starts xmpp protocol, call after connecting to socket
406 *
407 * @return true if server returns with valid xmpp, false otherwise
408 */
409 private boolean startXmpp(Socket socket) throws Exception {
410 if (Thread.currentThread().isInterrupted()) {
411 throw new InterruptedException();
412 }
413 this.socket = socket;
414 tagReader = new XmlReader();
415 if (tagWriter != null) {
416 tagWriter.forceClose();
417 }
418 tagWriter = new TagWriter();
419 tagWriter.setOutputStream(socket.getOutputStream());
420 tagReader.setInputStream(socket.getInputStream());
421 tagWriter.beginDocument();
422 sendStartStream();
423 final Tag tag = tagReader.readTag();
424 if (Thread.currentThread().isInterrupted()) {
425 throw new InterruptedException();
426 }
427 if (socket instanceof SSLSocket) {
428 SSLSocketHelper.log(account, (SSLSocket) socket);
429 }
430 return tag != null && tag.isStart("stream");
431 }
432
433 private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
434 final SSLContext sc = SSLSocketHelper.getSSLContext();
435 final MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
436 final KeyManager[] keyManager;
437 if (account.getPrivateKeyAlias() != null) {
438 keyManager = new KeyManager[]{new MyKeyManager()};
439 } else {
440 keyManager = null;
441 }
442 final String domain = account.getServer();
443 sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
444 return sc.getSocketFactory();
445 }
446
447 @Override
448 public void run() {
449 synchronized (this) {
450 this.mThread = Thread.currentThread();
451 if (this.mThread.isInterrupted()) {
452 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
453 return;
454 }
455 forceCloseSocket();
456 }
457 connect();
458 }
459
460 private void processStream() throws XmlPullParserException, IOException {
461 final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
462 this.mStreamCountDownLatch = streamCountDownLatch;
463 Tag nextTag = tagReader.readTag();
464 while (nextTag != null && !nextTag.isEnd("stream")) {
465 if (nextTag.isStart("error")) {
466 processStreamError(nextTag);
467 } else if (nextTag.isStart("features")) {
468 processStreamFeatures(nextTag);
469 } else if (nextTag.isStart("proceed")) {
470 switchOverToTls();
471 } else if (nextTag.isStart("success")) {
472 final Element success = tagReader.readElement(nextTag);
473 final SaslMechanism.Version version;
474 try {
475 version = SaslMechanism.Version.of(success);
476 } catch (final IllegalArgumentException e) {
477 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
478 }
479 final String challenge;
480 if (version == SaslMechanism.Version.SASL) {
481 challenge = success.getContent();
482 } else if (version == SaslMechanism.Version.SASL_2) {
483 challenge = success.findChildContent("additional-data");
484 } else {
485 throw new AssertionError("Missing implementation for " + version);
486 }
487 try {
488 saslMechanism.getResponse(challenge);
489 } catch (final SaslMechanism.AuthenticationException e) {
490 Log.e(Config.LOGTAG, String.valueOf(e));
491 throw new StateChangingException(Account.State.UNAUTHORIZED);
492 }
493 Log.d(
494 Config.LOGTAG,
495 account.getJid().asBareJid().toString()
496 + ": logged in (using "
497 + version
498 + ")");
499 account.setKey(
500 Account.PINNED_MECHANISM_KEY, String.valueOf(saslMechanism.getPriority()));
501 if (version == SaslMechanism.Version.SASL) {
502 tagReader.reset();
503 sendStartStream();
504 final Tag tag = tagReader.readTag();
505 if (tag != null && tag.isStart("stream")) {
506 processStream();
507 } else {
508 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
509 }
510 break;
511 }
512 } else if (nextTag.isStart("failure")) {
513 final Element failure = tagReader.readElement(nextTag);
514 if (Namespace.TLS.equals(failure.getNamespace())) {
515 throw new StateChangingException(Account.State.TLS_ERROR);
516 }
517 final SaslMechanism.Version version;
518 try {
519 version = SaslMechanism.Version.of(failure);
520 } catch (final IllegalArgumentException e) {
521 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
522 }
523 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": login failure " + version);
524 if (failure.hasChild("temporary-auth-failure")) {
525 throw new StateChangingException(Account.State.TEMPORARY_AUTH_FAILURE);
526 } else if (failure.hasChild("account-disabled")) {
527 final String text = failure.findChildContent("text");
528 if (Strings.isNullOrEmpty(text)) {
529 throw new StateChangingException(Account.State.UNAUTHORIZED);
530 }
531 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
532 if (matcher.find()) {
533 final HttpUrl url;
534 try {
535 url = HttpUrl.get(text.substring(matcher.start(), matcher.end()));
536 } catch (final IllegalArgumentException e) {
537 throw new StateChangingException(Account.State.UNAUTHORIZED);
538 }
539 if (url.isHttps()) {
540 this.redirectionUrl = url;
541 throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
542 }
543 }
544 }
545 throw new StateChangingException(Account.State.UNAUTHORIZED);
546 } else if (nextTag.isStart("challenge")) {
547 final Element challenge = tagReader.readElement(nextTag);
548 final SaslMechanism.Version version;
549 try {
550 version = SaslMechanism.Version.of(challenge);
551 } catch (final IllegalArgumentException e) {
552 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
553 }
554 final Element response;
555 if (version == SaslMechanism.Version.SASL) {
556 response = new Element("response", Namespace.SASL);
557 } else if (version == SaslMechanism.Version.SASL_2) {
558 response = new Element("response", Namespace.SASL_2);
559 } else {
560 throw new AssertionError("Missing implementation for " + version);
561 }
562 try {
563 response.setContent(saslMechanism.getResponse(challenge.getContent()));
564 } catch (final SaslMechanism.AuthenticationException e) {
565 // TODO: Send auth abort tag.
566 Log.e(Config.LOGTAG, e.toString());
567 throw new StateChangingException(Account.State.UNAUTHORIZED);
568 }
569 tagWriter.writeElement(response);
570 } else if (nextTag.isStart("enabled")) {
571 final Element enabled = tagReader.readElement(nextTag);
572 if ("true".equals(enabled.getAttribute("resume"))) {
573 this.streamId = enabled.getAttribute("id");
574 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
575 + ": stream management(" + smVersion
576 + ") enabled (resumable)");
577 } else {
578 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
579 + ": stream management(" + smVersion + ") enabled");
580 }
581 this.stanzasReceived = 0;
582 this.inSmacksSession = true;
583 final RequestPacket r = new RequestPacket(smVersion);
584 tagWriter.writeStanzaAsync(r);
585 } else if (nextTag.isStart("resumed")) {
586 this.inSmacksSession = true;
587 this.isBound = true;
588 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
589 lastPacketReceived = SystemClock.elapsedRealtime();
590 final Element resumed = tagReader.readElement(nextTag);
591 final String h = resumed.getAttribute("h");
592 try {
593 ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
594 final boolean acknowledgedMessages;
595 synchronized (this.mStanzaQueue) {
596 final int serverCount = Integer.parseInt(h);
597 if (serverCount < stanzasSent) {
598 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
599 + ": session resumed with lost packages");
600 stanzasSent = serverCount;
601 } else {
602 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
603 }
604 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
605 for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
606 failedStanzas.add(mStanzaQueue.valueAt(i));
607 }
608 mStanzaQueue.clear();
609 }
610 if (acknowledgedMessages) {
611 mXmppConnectionService.updateConversationUi();
612 }
613 Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
614 for (AbstractAcknowledgeableStanza packet : failedStanzas) {
615 if (packet instanceof MessagePacket) {
616 MessagePacket message = (MessagePacket) packet;
617 mXmppConnectionService.markMessage(account,
618 message.getTo().asBareJid(),
619 message.getId(),
620 Message.STATUS_UNSEND);
621 }
622 sendPacket(packet);
623 }
624 } catch (final NumberFormatException ignored) {
625 }
626 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
627 changeStatus(Account.State.ONLINE);
628 } else if (nextTag.isStart("r")) {
629 tagReader.readElement(nextTag);
630 if (Config.EXTENDED_SM_LOGGING) {
631 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
632 }
633 final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
634 tagWriter.writeStanzaAsync(ack);
635 } else if (nextTag.isStart("a")) {
636 boolean accountUiNeedsRefresh = false;
637 synchronized (NotificationService.CATCHUP_LOCK) {
638 if (mWaitingForSmCatchup.compareAndSet(true, false)) {
639 final int messageCount = mSmCatchupMessageCounter.get();
640 final int pendingIQs = packetCallbacks.size();
641 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (messages=" + messageCount + ", pending IQs=" + pendingIQs + ")");
642 accountUiNeedsRefresh = true;
643 if (messageCount > 0) {
644 mXmppConnectionService.getNotificationService().finishBacklog(true, account);
645 }
646 }
647 }
648 if (accountUiNeedsRefresh) {
649 mXmppConnectionService.updateAccountUi();
650 }
651 final Element ack = tagReader.readElement(nextTag);
652 lastPacketReceived = SystemClock.elapsedRealtime();
653 try {
654 final boolean acknowledgedMessages;
655 synchronized (this.mStanzaQueue) {
656 final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
657 acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
658 }
659 if (acknowledgedMessages) {
660 mXmppConnectionService.updateConversationUi();
661 }
662 } catch (NumberFormatException | NullPointerException e) {
663 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
664 }
665 } else if (nextTag.isStart("failed")) {
666 Element failed = tagReader.readElement(nextTag);
667 try {
668 final int serverCount = Integer.parseInt(failed.getAttribute("h"));
669 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
670 final boolean acknowledgedMessages;
671 synchronized (this.mStanzaQueue) {
672 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
673 }
674 if (acknowledgedMessages) {
675 mXmppConnectionService.updateConversationUi();
676 }
677 } catch (NumberFormatException | NullPointerException e) {
678 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
679 }
680 resetStreamId();
681 sendBindRequest();
682 } else if (nextTag.isStart("iq")) {
683 processIq(nextTag);
684 } else if (nextTag.isStart("message")) {
685 processMessage(nextTag);
686 } else if (nextTag.isStart("presence")) {
687 processPresence(nextTag);
688 }
689 nextTag = tagReader.readTag();
690 }
691 if (nextTag != null && nextTag.isEnd("stream")) {
692 streamCountDownLatch.countDown();
693 }
694 }
695
696 private boolean acknowledgeStanzaUpTo(int serverCount) {
697 if (serverCount > stanzasSent) {
698 Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
699 }
700 boolean acknowledgedMessages = false;
701 for (int i = 0; i < mStanzaQueue.size(); ++i) {
702 if (serverCount >= mStanzaQueue.keyAt(i)) {
703 if (Config.EXTENDED_SM_LOGGING) {
704 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
705 }
706 final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
707 if (stanza instanceof MessagePacket && acknowledgedListener != null) {
708 final MessagePacket packet = (MessagePacket) stanza;
709 final String id = packet.getId();
710 final Jid to = packet.getTo();
711 if (id != null && to != null) {
712 acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, to, id);
713 }
714 }
715 mStanzaQueue.removeAt(i);
716 i--;
717 }
718 }
719 return acknowledgedMessages;
720 }
721
722 private @NonNull
723 Element processPacket(final Tag currentTag, final int packetType) throws IOException {
724 final Element element;
725 switch (packetType) {
726 case PACKET_IQ:
727 element = new IqPacket();
728 break;
729 case PACKET_MESSAGE:
730 element = new MessagePacket();
731 break;
732 case PACKET_PRESENCE:
733 element = new PresencePacket();
734 break;
735 default:
736 throw new AssertionError("Should never encounter invalid type");
737 }
738 element.setAttributes(currentTag.getAttributes());
739 Tag nextTag = tagReader.readTag();
740 if (nextTag == null) {
741 throw new IOException("interrupted mid tag");
742 }
743 while (!nextTag.isEnd(element.getName())) {
744 if (!nextTag.isNo()) {
745 element.addChild(tagReader.readElement(nextTag));
746 }
747 nextTag = tagReader.readTag();
748 if (nextTag == null) {
749 throw new IOException("interrupted mid tag");
750 }
751 }
752 if (stanzasReceived == Integer.MAX_VALUE) {
753 resetStreamId();
754 throw new IOException("time to restart the session. cant handle >2 billion pcks");
755 }
756 if (inSmacksSession) {
757 ++stanzasReceived;
758 } else if (features.sm()) {
759 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
760 }
761 lastPacketReceived = SystemClock.elapsedRealtime();
762 if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
763 Log.d(Config.LOGTAG, "[background stanza] " + element);
764 }
765 if (element instanceof IqPacket
766 && (((IqPacket) element).getType() == IqPacket.TYPE.SET)
767 && element.hasChild("jingle", Namespace.JINGLE)) {
768 return JinglePacket.upgrade((IqPacket) element);
769 } else {
770 return element;
771 }
772 }
773
774 private void processIq(final Tag currentTag) throws IOException {
775 final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
776 if (!packet.valid()) {
777 Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
778 return;
779 }
780 if (packet instanceof JinglePacket) {
781 if (this.jingleListener != null) {
782 this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
783 }
784 } else {
785 OnIqPacketReceived callback = null;
786 synchronized (this.packetCallbacks) {
787 final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
788 if (packetCallbackDuple != null) {
789 // Packets to the server should have responses from the server
790 if (packetCallbackDuple.first.toServer(account)) {
791 if (packet.fromServer(account)) {
792 callback = packetCallbackDuple.second;
793 packetCallbacks.remove(packet.getId());
794 } else {
795 Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
796 }
797 } else {
798 if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
799 callback = packetCallbackDuple.second;
800 packetCallbacks.remove(packet.getId());
801 } else {
802 Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
803 }
804 }
805 } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
806 callback = this.unregisteredIqListener;
807 }
808 }
809 if (callback != null) {
810 try {
811 callback.onIqPacketReceived(account, packet);
812 } catch (StateChangingError error) {
813 throw new StateChangingException(error.state);
814 }
815 }
816 }
817 }
818
819 private void processMessage(final Tag currentTag) throws IOException {
820 final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
821 if (!packet.valid()) {
822 Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
823 return;
824 }
825 this.messageListener.onMessagePacketReceived(account, packet);
826 }
827
828 private void processPresence(final Tag currentTag) throws IOException {
829 PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
830 if (!packet.valid()) {
831 Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
832 return;
833 }
834 this.presenceListener.onPresencePacketReceived(account, packet);
835 }
836
837 private void sendStartTLS() throws IOException {
838 final Tag startTLS = Tag.empty("starttls");
839 startTLS.setAttribute("xmlns", Namespace.TLS);
840 tagWriter.writeTag(startTLS);
841 }
842
843 private void switchOverToTls() throws XmlPullParserException, IOException {
844 tagReader.readTag();
845 final Socket socket = this.socket;
846 final SSLSocket sslSocket = upgradeSocketToTls(socket);
847 tagReader.setInputStream(sslSocket.getInputStream());
848 tagWriter.setOutputStream(sslSocket.getOutputStream());
849 sendStartStream();
850 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
851 features.encryptionEnabled = true;
852 final Tag tag = tagReader.readTag();
853 if (tag != null && tag.isStart("stream")) {
854 SSLSocketHelper.log(account, sslSocket);
855 processStream();
856 } else {
857 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
858 }
859 sslSocket.close();
860 }
861
862 private SSLSocket upgradeSocketToTls(final Socket socket) throws IOException {
863 final SSLSocketFactory sslSocketFactory;
864 try {
865 sslSocketFactory = getSSLSocketFactory();
866 } catch (final NoSuchAlgorithmException | KeyManagementException e) {
867 throw new StateChangingException(Account.State.TLS_ERROR);
868 }
869 final InetAddress address = socket.getInetAddress();
870 final SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
871 SSLSocketHelper.setSecurity(sslSocket);
872 SSLSocketHelper.setHostname(sslSocket, IDN.toASCII(account.getServer()));
873 SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
874 final XmppDomainVerifier xmppDomainVerifier = new XmppDomainVerifier();
875 try {
876 if (!xmppDomainVerifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
877 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate domain verification failed");
878 FileBackend.close(sslSocket);
879 throw new StateChangingException(Account.State.TLS_ERROR_DOMAIN);
880 }
881 } catch (final SSLPeerUnverifiedException e) {
882 FileBackend.close(sslSocket);
883 throw new StateChangingException(Account.State.TLS_ERROR);
884 }
885 return sslSocket;
886 }
887
888 private void processStreamFeatures(final Tag currentTag) throws IOException {
889 this.streamFeatures = tagReader.readElement(currentTag);
890 final boolean isSecure =
891 features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS || account.isOnion();
892 final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
893 if (this.streamFeatures.hasChild("starttls", Namespace.TLS)
894 && !features.encryptionEnabled) {
895 sendStartTLS();
896 } else if (this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
897 && account.isOptionSet(Account.OPTION_REGISTER)) {
898 if (isSecure) {
899 register();
900 } else {
901 Log.d(
902 Config.LOGTAG,
903 account.getJid().asBareJid()
904 + ": unable to find STARTTLS for registration process "
905 + XmlHelper.printElementNames(this.streamFeatures));
906 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
907 }
908 } else if (!this.streamFeatures.hasChild("register", Namespace.REGISTER_STREAM_FEATURE)
909 && account.isOptionSet(Account.OPTION_REGISTER)) {
910 throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
911 } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL_2)
912 && shouldAuthenticate
913 && isSecure) {
914 authenticate(SaslMechanism.Version.SASL_2);
915 } else if (this.streamFeatures.hasChild("mechanisms", Namespace.SASL)
916 && shouldAuthenticate
917 && isSecure) {
918 authenticate(SaslMechanism.Version.SASL);
919 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion)
920 && streamId != null) {
921 if (Config.EXTENDED_SM_LOGGING) {
922 Log.d(
923 Config.LOGTAG,
924 account.getJid().asBareJid()
925 + ": resuming after stanza #"
926 + stanzasReceived);
927 }
928 final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
929 this.mSmCatchupMessageCounter.set(0);
930 this.mWaitingForSmCatchup.set(true);
931 this.tagWriter.writeStanzaAsync(resume);
932 } else if (needsBinding) {
933 if (this.streamFeatures.hasChild("bind", Namespace.BIND) && isSecure) {
934 sendBindRequest();
935 } else {
936 Log.d(
937 Config.LOGTAG,
938 account.getJid().asBareJid()
939 + ": unable to find bind feature "
940 + XmlHelper.printElementNames(this.streamFeatures));
941 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
942 }
943 }
944 }
945
946 private void authenticate(final SaslMechanism.Version version) throws IOException {
947 final List<String> mechanisms = extractMechanisms(streamFeatures.findChild("mechanisms"));
948 if (mechanisms.contains(External.MECHANISM) && account.getPrivateKeyAlias() != null) {
949 saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
950 } else if (mechanisms.contains(ScramSha512.MECHANISM)) {
951 saslMechanism = new ScramSha512(tagWriter, account, mXmppConnectionService.getRNG());
952 } else if (mechanisms.contains(ScramSha256.MECHANISM)) {
953 saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
954 } else if (mechanisms.contains(ScramSha1.MECHANISM)) {
955 saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
956 } else if (mechanisms.contains(Plain.MECHANISM) && !account.getJid().getDomain().toEscapedString().equals("nimbuzz.com")) {
957 saslMechanism = new Plain(tagWriter, account);
958 } else if (mechanisms.contains(DigestMd5.MECHANISM)) {
959 saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
960 } else if (mechanisms.contains(Anonymous.MECHANISM)) {
961 saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
962 }
963 if (saslMechanism == null) {
964 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": unable to find supported SASL mechanism in " + mechanisms);
965 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
966 }
967 final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
968 if (pinnedMechanism > saslMechanism.getPriority()) {
969 Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
970 " has lower priority (" + saslMechanism.getPriority() +
971 ") than pinned priority (" + pinnedMechanism +
972 "). Possible downgrade attack?");
973 throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
974 }
975 final String firstMessage = saslMechanism.getClientFirstMessage();
976 final Element authenticate;
977 if (version == SaslMechanism.Version.SASL) {
978 authenticate = new Element("auth", Namespace.SASL);
979 if (!Strings.isNullOrEmpty(firstMessage)) {
980 authenticate.setContent(firstMessage);
981 }
982 } else if (version == SaslMechanism.Version.SASL_2) {
983 authenticate = new Element("authenticate", Namespace.SASL_2);
984 if (!Strings.isNullOrEmpty(firstMessage)) {
985 authenticate.addChild("initial-response").setContent(firstMessage);
986 }
987 // TODO place to add extensions
988 } else {
989 throw new AssertionError("Missing implementation for " + version);
990 }
991
992 Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with "+version+ "/" + saslMechanism.getMechanism());
993 authenticate.setAttribute("mechanism", saslMechanism.getMechanism());
994 tagWriter.writeElement(authenticate);
995 }
996
997 private List<String> extractMechanisms(final Element stream) {
998 final ArrayList<String> mechanisms = new ArrayList<>(stream
999 .getChildren().size());
1000 for (final Element child : stream.getChildren()) {
1001 mechanisms.add(child.getContent());
1002 }
1003 return mechanisms;
1004 }
1005
1006
1007 private void register() {
1008 final String preAuth = account.getKey(Account.PRE_AUTH_REGISTRATION_TOKEN);
1009 if (preAuth != null && features.invite()) {
1010 final IqPacket preAuthRequest = new IqPacket(IqPacket.TYPE.SET);
1011 preAuthRequest.addChild("preauth", Namespace.PARS).setAttribute("token", preAuth);
1012 sendUnmodifiedIqPacket(preAuthRequest, (account, response) -> {
1013 if (response.getType() == IqPacket.TYPE.RESULT) {
1014 sendRegistryRequest();
1015 } else {
1016 final String error = response.getErrorCondition();
1017 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": failed to pre auth. " + error);
1018 throw new StateChangingError(Account.State.REGISTRATION_INVALID_TOKEN);
1019 }
1020 }, true);
1021 } else {
1022 sendRegistryRequest();
1023 }
1024 }
1025
1026 private void sendRegistryRequest() {
1027 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
1028 register.query(Namespace.REGISTER);
1029 register.setTo(account.getDomain());
1030 sendUnmodifiedIqPacket(register, (account, packet) -> {
1031 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1032 return;
1033 }
1034 if (packet.getType() == IqPacket.TYPE.ERROR) {
1035 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1036 }
1037 final Element query = packet.query(Namespace.REGISTER);
1038 if (query.hasChild("username") && (query.hasChild("password"))) {
1039 final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
1040 final Element username = new Element("username").setContent(account.getUsername());
1041 final Element password = new Element("password").setContent(account.getPassword());
1042 register1.query(Namespace.REGISTER).addChild(username);
1043 register1.query().addChild(password);
1044 register1.setFrom(account.getJid().asBareJid());
1045 sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
1046 } else if (query.hasChild("x", Namespace.DATA)) {
1047 final Data data = Data.parse(query.findChild("x", Namespace.DATA));
1048 final Element blob = query.findChild("data", "urn:xmpp:bob");
1049 final String id = packet.getId();
1050 InputStream is;
1051 if (blob != null) {
1052 try {
1053 final String base64Blob = blob.getContent();
1054 final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
1055 is = new ByteArrayInputStream(strBlob);
1056 } catch (Exception e) {
1057 is = null;
1058 }
1059 } else {
1060 final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
1061 try {
1062 final String url = data.getValue("url");
1063 final String fallbackUrl = data.getValue("captcha-fallback-url");
1064 if (url != null) {
1065 is = HttpConnectionManager.open(url, useTor);
1066 } else if (fallbackUrl != null) {
1067 is = HttpConnectionManager.open(fallbackUrl, useTor);
1068 } else {
1069 is = null;
1070 }
1071 } catch (final IOException e) {
1072 Log.d(Config.LOGTAG,account.getJid().asBareJid()+": unable to fetch captcha", e);
1073 is = null;
1074 }
1075 }
1076
1077 if (is != null) {
1078 Bitmap captcha = BitmapFactory.decodeStream(is);
1079 try {
1080 if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
1081 return;
1082 }
1083 } catch (Exception e) {
1084 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1085 }
1086 }
1087 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1088 } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
1089 final String instructions = query.findChildContent("instructions");
1090 final Element oob = query.findChild("x", Namespace.OOB);
1091 final String url = oob == null ? null : oob.findChildContent("url");
1092 if (url != null) {
1093 setAccountCreationFailed(url);
1094 } else if (instructions != null) {
1095 final Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
1096 if (matcher.find()) {
1097 setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
1098 }
1099 }
1100 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1101 }
1102 }, true);
1103 }
1104
1105 private void setAccountCreationFailed(final String url) {
1106 final HttpUrl httpUrl = url == null ? null : HttpUrl.parse(url);
1107 if (httpUrl != null && httpUrl.isHttps()) {
1108 this.redirectionUrl = httpUrl;
1109 throw new StateChangingError(Account.State.REGISTRATION_WEB);
1110 }
1111 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1112 }
1113
1114 public HttpUrl getRedirectionUrl() {
1115 return this.redirectionUrl;
1116 }
1117
1118 public void resetEverything() {
1119 resetAttemptCount(true);
1120 resetStreamId();
1121 clearIqCallbacks();
1122 this.stanzasSent = 0;
1123 mStanzaQueue.clear();
1124 this.redirectionUrl = null;
1125 synchronized (this.disco) {
1126 disco.clear();
1127 }
1128 synchronized (this.commands) {
1129 this.commands.clear();
1130 }
1131 }
1132
1133 private void sendBindRequest() {
1134 try {
1135 mXmppConnectionService.restoredFromDatabaseLatch.await();
1136 } catch (InterruptedException e) {
1137 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1138 return;
1139 }
1140 clearIqCallbacks();
1141 if (account.getJid().isBareJid()) {
1142 account.setResource(this.createNewResource());
1143 } else {
1144 fixResource(mXmppConnectionService, account);
1145 }
1146 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1147 final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1148 iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1149 this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1150 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1151 return;
1152 }
1153 final Element bind = packet.findChild("bind");
1154 if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1155 isBound = true;
1156 final Element jid = bind.findChild("jid");
1157 if (jid != null && jid.getContent() != null) {
1158 try {
1159 Jid assignedJid = Jid.ofEscaped(jid.getContent());
1160 if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1161 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1162 throw new StateChangingError(Account.State.BIND_FAILURE);
1163 }
1164 if (account.setJid(assignedJid)) {
1165 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1166 mXmppConnectionService.databaseBackend.updateAccount(account);
1167 }
1168 if (streamFeatures.hasChild("session")
1169 && !streamFeatures.findChild("session").hasChild("optional")) {
1170 sendStartSession();
1171 } else {
1172 sendPostBindInitialization();
1173 }
1174 return;
1175 } catch (final IllegalArgumentException e) {
1176 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1177 }
1178 } else {
1179 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1180 }
1181 } else {
1182 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1183 }
1184 final Element error = packet.findChild("error");
1185 if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1186 account.setResource(createNewResource());
1187 }
1188 throw new StateChangingError(Account.State.BIND_FAILURE);
1189 }, true);
1190 }
1191
1192 private void clearIqCallbacks() {
1193 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1194 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1195 synchronized (this.packetCallbacks) {
1196 if (this.packetCallbacks.size() == 0) {
1197 return;
1198 }
1199 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1200 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1201 while (iterator.hasNext()) {
1202 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1203 callbacks.add(entry.second);
1204 iterator.remove();
1205 }
1206 }
1207 for (OnIqPacketReceived callback : callbacks) {
1208 try {
1209 callback.onIqPacketReceived(account, failurePacket);
1210 } catch (StateChangingError error) {
1211 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1212 //ignore
1213 }
1214 }
1215 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1216 }
1217
1218 public void sendDiscoTimeout() {
1219 if (mWaitForDisco.compareAndSet(true, false)) {
1220 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1221 finalizeBind();
1222 }
1223 }
1224
1225 private void sendStartSession() {
1226 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1227 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1228 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1229 this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1230 if (packet.getType() == IqPacket.TYPE.RESULT) {
1231 sendPostBindInitialization();
1232 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1233 throw new StateChangingError(Account.State.SESSION_FAILURE);
1234 }
1235 }, true);
1236 }
1237
1238 private void sendPostBindInitialization() {
1239 smVersion = 0;
1240 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1241 smVersion = 3;
1242 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1243 smVersion = 2;
1244 }
1245 if (smVersion != 0) {
1246 synchronized (this.mStanzaQueue) {
1247 final EnablePacket enable = new EnablePacket(smVersion);
1248 tagWriter.writeStanzaAsync(enable);
1249 stanzasSent = 0;
1250 mStanzaQueue.clear();
1251 }
1252 }
1253 features.carbonsEnabled = false;
1254 features.blockListRequested = false;
1255 synchronized (this.disco) {
1256 this.disco.clear();
1257 }
1258 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1259 mPendingServiceDiscoveries.set(0);
1260 if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain().toEscapedString())) {
1261 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1262 mWaitForDisco.set(false);
1263 } else {
1264 mWaitForDisco.set(true);
1265 }
1266 lastDiscoStarted = SystemClock.elapsedRealtime();
1267 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1268 Element caps = streamFeatures.findChild("c");
1269 final String hash = caps == null ? null : caps.getAttribute("hash");
1270 final String ver = caps == null ? null : caps.getAttribute("ver");
1271 ServiceDiscoveryResult discoveryResult = null;
1272 if (hash != null && ver != null) {
1273 discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1274 }
1275 final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1276 if (requestDiscoItemsFirst) {
1277 sendServiceDiscoveryItems(account.getDomain());
1278 }
1279 if (discoveryResult == null) {
1280 sendServiceDiscoveryInfo(account.getDomain());
1281 } else {
1282 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1283 disco.put(account.getDomain(), discoveryResult);
1284 }
1285 discoverMamPreferences();
1286 sendServiceDiscoveryInfo(account.getJid().asBareJid());
1287 if (!requestDiscoItemsFirst) {
1288 sendServiceDiscoveryItems(account.getDomain());
1289 }
1290
1291 if (!mWaitForDisco.get()) {
1292 finalizeBind();
1293 }
1294 this.lastSessionStarted = SystemClock.elapsedRealtime();
1295 }
1296
1297 private void sendServiceDiscoveryInfo(final Jid jid) {
1298 mPendingServiceDiscoveries.incrementAndGet();
1299 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1300 iq.setTo(jid);
1301 iq.query("http://jabber.org/protocol/disco#info");
1302 this.sendIqPacket(iq, (account, packet) -> {
1303 if (packet.getType() == IqPacket.TYPE.RESULT) {
1304 boolean advancedStreamFeaturesLoaded;
1305 synchronized (XmppConnection.this.disco) {
1306 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1307 if (jid.equals(account.getDomain())) {
1308 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1309 }
1310 disco.put(jid, result);
1311 advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain())
1312 && disco.containsKey(account.getJid().asBareJid());
1313 }
1314 if (advancedStreamFeaturesLoaded && (jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid()))) {
1315 enableAdvancedStreamFeatures();
1316 }
1317 } else if (packet.getType() == IqPacket.TYPE.ERROR) {
1318 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1319 final boolean serverOrAccount = jid.equals(account.getDomain()) || jid.equals(account.getJid().asBareJid());
1320 final boolean advancedStreamFeaturesLoaded;
1321 if (serverOrAccount) {
1322 synchronized (XmppConnection.this.disco) {
1323 disco.put(jid, ServiceDiscoveryResult.empty());
1324 advancedStreamFeaturesLoaded = disco.containsKey(account.getDomain()) && disco.containsKey(account.getJid().asBareJid());
1325 }
1326 } else {
1327 advancedStreamFeaturesLoaded = false;
1328 }
1329 if (advancedStreamFeaturesLoaded) {
1330 enableAdvancedStreamFeatures();
1331 }
1332 }
1333 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1334 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1335 && mWaitForDisco.compareAndSet(true, false)) {
1336 finalizeBind();
1337 }
1338 }
1339 });
1340 }
1341
1342 private void discoverMamPreferences() {
1343 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1344 request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1345 sendIqPacket(request, (account, response) -> {
1346 if (response.getType() == IqPacket.TYPE.RESULT) {
1347 Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1348 isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1349 }
1350 });
1351 }
1352
1353 private void discoverCommands() {
1354 final IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1355 request.setTo(account.getDomain());
1356 request.addChild("query", Namespace.DISCO_ITEMS).setAttribute("node", Namespace.COMMANDS);
1357 sendIqPacket(request, (account, response) -> {
1358 if (response.getType() == IqPacket.TYPE.RESULT) {
1359 final Element query = response.findChild("query", Namespace.DISCO_ITEMS);
1360 if (query == null) {
1361 return;
1362 }
1363 final HashMap<String, Jid> commands = new HashMap<>();
1364 for (final Element child : query.getChildren()) {
1365 if ("item".equals(child.getName())) {
1366 final String node = child.getAttribute("node");
1367 final Jid jid = child.getAttributeAsJid("jid");
1368 if (node != null && jid != null) {
1369 commands.put(node, jid);
1370 }
1371 }
1372 }
1373 Log.d(Config.LOGTAG, commands.toString());
1374 synchronized (this.commands) {
1375 this.commands.clear();
1376 this.commands.putAll(commands);
1377 }
1378 }
1379 });
1380 }
1381
1382 public boolean isMamPreferenceAlways() {
1383 return isMamPreferenceAlways;
1384 }
1385
1386 private void finalizeBind() {
1387 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1388 if (bindListener != null) {
1389 bindListener.onBind(account);
1390 }
1391 changeStatus(Account.State.ONLINE);
1392 }
1393
1394 private void enableAdvancedStreamFeatures() {
1395 if (getFeatures().blocking() && !features.blockListRequested) {
1396 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1397 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1398 }
1399 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1400 listener.onAdvancedStreamFeaturesAvailable(account);
1401 }
1402 if (getFeatures().carbons() && !features.carbonsEnabled) {
1403 sendEnableCarbons();
1404 }
1405 if (getFeatures().commands()) {
1406 discoverCommands();
1407 }
1408 }
1409
1410 private void sendServiceDiscoveryItems(final Jid server) {
1411 mPendingServiceDiscoveries.incrementAndGet();
1412 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1413 iq.setTo(server.getDomain());
1414 iq.query("http://jabber.org/protocol/disco#items");
1415 this.sendIqPacket(iq, (account, packet) -> {
1416 if (packet.getType() == IqPacket.TYPE.RESULT) {
1417 final HashSet<Jid> items = new HashSet<>();
1418 final List<Element> elements = packet.query().getChildren();
1419 for (final Element element : elements) {
1420 if (element.getName().equals("item")) {
1421 final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1422 if (jid != null && !jid.equals(account.getDomain())) {
1423 items.add(jid);
1424 }
1425 }
1426 }
1427 for (Jid jid : items) {
1428 sendServiceDiscoveryInfo(jid);
1429 }
1430 } else {
1431 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1432 }
1433 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1434 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1435 && mWaitForDisco.compareAndSet(true, false)) {
1436 finalizeBind();
1437 }
1438 }
1439 });
1440 }
1441
1442 private void sendEnableCarbons() {
1443 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1444 iq.addChild("enable", "urn:xmpp:carbons:2");
1445 this.sendIqPacket(iq, (account, packet) -> {
1446 if (!packet.hasChild("error")) {
1447 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1448 + ": successfully enabled carbons");
1449 features.carbonsEnabled = true;
1450 } else {
1451 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1452 + ": error enableing carbons " + packet.toString());
1453 }
1454 });
1455 }
1456
1457 private void processStreamError(final Tag currentTag) throws IOException {
1458 final Element streamError = tagReader.readElement(currentTag);
1459 if (streamError == null) {
1460 return;
1461 }
1462 if (streamError.hasChild("conflict")) {
1463 account.setResource(createNewResource());
1464 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1465 throw new IOException();
1466 } else if (streamError.hasChild("host-unknown")) {
1467 throw new StateChangingException(Account.State.HOST_UNKNOWN);
1468 } else if (streamError.hasChild("policy-violation")) {
1469 this.lastConnect = SystemClock.elapsedRealtime();
1470 final String text = streamError.findChildContent("text");
1471 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": policy violation. " + text);
1472 failPendingMessages(text);
1473 throw new StateChangingException(Account.State.POLICY_VIOLATION);
1474 } else {
1475 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1476 throw new StateChangingException(Account.State.STREAM_ERROR);
1477 }
1478 }
1479
1480 private void failPendingMessages(final String error) {
1481 synchronized (this.mStanzaQueue) {
1482 for (int i = 0; i < mStanzaQueue.size(); ++i) {
1483 final AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
1484 if (stanza instanceof MessagePacket) {
1485 final MessagePacket packet = (MessagePacket) stanza;
1486 final String id = packet.getId();
1487 final Jid to = packet.getTo();
1488 mXmppConnectionService.markMessage(account,
1489 to.asBareJid(),
1490 id,
1491 Message.STATUS_SEND_FAILED,
1492 error);
1493 }
1494 }
1495 }
1496 }
1497
1498 private void sendStartStream() throws IOException {
1499 final Tag stream = Tag.start("stream:stream");
1500 stream.setAttribute("to", account.getServer());
1501 stream.setAttribute("version", "1.0");
1502 stream.setAttribute("xml:lang", LocalizedContent.STREAM_LANGUAGE);
1503 stream.setAttribute("xmlns", "jabber:client");
1504 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1505 tagWriter.writeTag(stream);
1506 }
1507
1508 private String createNewResource() {
1509 return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1510 }
1511
1512 private String nextRandomId() {
1513 return nextRandomId(false);
1514 }
1515
1516 private String nextRandomId(boolean s) {
1517 return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1518 }
1519
1520 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1521 packet.setFrom(account.getJid());
1522 return this.sendUnmodifiedIqPacket(packet, callback, false);
1523 }
1524
1525 public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1526 if (packet.getId() == null) {
1527 packet.setAttribute("id", nextRandomId());
1528 }
1529 if (callback != null) {
1530 synchronized (this.packetCallbacks) {
1531 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1532 }
1533 }
1534 this.sendPacket(packet, force);
1535 return packet.getId();
1536 }
1537
1538 public void sendMessagePacket(final MessagePacket packet) {
1539 this.sendPacket(packet);
1540 }
1541
1542 public void sendPresencePacket(final PresencePacket packet) {
1543 this.sendPacket(packet);
1544 }
1545
1546 private synchronized void sendPacket(final AbstractStanza packet) {
1547 sendPacket(packet, false);
1548 }
1549
1550 private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1551 if (stanzasSent == Integer.MAX_VALUE) {
1552 resetStreamId();
1553 disconnect(true);
1554 return;
1555 }
1556 synchronized (this.mStanzaQueue) {
1557 if (force || isBound) {
1558 tagWriter.writeStanzaAsync(packet);
1559 } else {
1560 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1561 }
1562 if (packet instanceof AbstractAcknowledgeableStanza) {
1563 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1564
1565 if (this.mStanzaQueue.size() != 0) {
1566 int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1567 if (currentHighestKey != stanzasSent) {
1568 throw new AssertionError("Stanza count messed up");
1569 }
1570 }
1571
1572 ++stanzasSent;
1573 this.mStanzaQueue.append(stanzasSent, stanza);
1574 if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1575 if (Config.EXTENDED_SM_LOGGING) {
1576 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1577 }
1578 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1579 }
1580 }
1581 }
1582 }
1583
1584 public void sendPing() {
1585 if (!r()) {
1586 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1587 iq.setFrom(account.getJid());
1588 iq.addChild("ping", Namespace.PING);
1589 this.sendIqPacket(iq, null);
1590 }
1591 this.lastPingSent = SystemClock.elapsedRealtime();
1592 }
1593
1594 public void setOnMessagePacketReceivedListener(
1595 final OnMessagePacketReceived listener) {
1596 this.messageListener = listener;
1597 }
1598
1599 public void setOnUnregisteredIqPacketReceivedListener(
1600 final OnIqPacketReceived listener) {
1601 this.unregisteredIqListener = listener;
1602 }
1603
1604 public void setOnPresencePacketReceivedListener(
1605 final OnPresencePacketReceived listener) {
1606 this.presenceListener = listener;
1607 }
1608
1609 public void setOnJinglePacketReceivedListener(
1610 final OnJinglePacketReceived listener) {
1611 this.jingleListener = listener;
1612 }
1613
1614 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1615 this.statusListener = listener;
1616 }
1617
1618 public void setOnBindListener(final OnBindListener listener) {
1619 this.bindListener = listener;
1620 }
1621
1622 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1623 this.acknowledgedListener = listener;
1624 }
1625
1626 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1627 this.advancedStreamFeaturesLoadedListeners.add(listener);
1628 }
1629
1630 private void forceCloseSocket() {
1631 FileBackend.close(this.socket);
1632 FileBackend.close(this.tagReader);
1633 }
1634
1635 public void interrupt() {
1636 if (this.mThread != null) {
1637 this.mThread.interrupt();
1638 }
1639 }
1640
1641 public void disconnect(final boolean force) {
1642 interrupt();
1643 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + force);
1644 if (force) {
1645 forceCloseSocket();
1646 } else {
1647 final TagWriter currentTagWriter = this.tagWriter;
1648 if (currentTagWriter.isActive()) {
1649 currentTagWriter.finish();
1650 final Socket currentSocket = this.socket;
1651 final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1652 try {
1653 currentTagWriter.await(1, TimeUnit.SECONDS);
1654 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1655 currentTagWriter.writeTag(Tag.end("stream:stream"));
1656 if (streamCountDownLatch != null) {
1657 if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1658 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1659 } else {
1660 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1661 }
1662 }
1663 } catch (InterruptedException e) {
1664 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1665 } catch (final IOException e) {
1666 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1667 } finally {
1668 FileBackend.close(currentSocket);
1669 }
1670 } else {
1671 forceCloseSocket();
1672 }
1673 }
1674 }
1675
1676 private void resetStreamId() {
1677 this.streamId = null;
1678 }
1679
1680 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1681 synchronized (this.disco) {
1682 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1683 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1684 if (cursor.getValue().getFeatures().contains(feature)) {
1685 items.add(cursor);
1686 }
1687 }
1688 return items;
1689 }
1690 }
1691
1692 public Jid findDiscoItemByFeature(final String feature) {
1693 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1694 if (items.size() >= 1) {
1695 return items.get(0).getKey();
1696 }
1697 return null;
1698 }
1699
1700 public boolean r() {
1701 if (getFeatures().sm()) {
1702 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1703 return true;
1704 } else {
1705 return false;
1706 }
1707 }
1708
1709 public List<String> getMucServersWithholdAccount() {
1710 final List<String> servers = getMucServers();
1711 servers.remove(account.getDomain().toEscapedString());
1712 return servers;
1713 }
1714
1715 public List<String> getMucServers() {
1716 List<String> servers = new ArrayList<>();
1717 synchronized (this.disco) {
1718 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1719 final ServiceDiscoveryResult value = cursor.getValue();
1720 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1721 && value.hasIdentity("conference", "text")
1722 && !value.getFeatures().contains("jabber:iq:gateway")
1723 && !value.hasIdentity("conference", "irc")) {
1724 servers.add(cursor.getKey().toString());
1725 }
1726 }
1727 }
1728 return servers;
1729 }
1730
1731 public String getMucServer() {
1732 List<String> servers = getMucServers();
1733 return servers.size() > 0 ? servers.get(0) : null;
1734 }
1735
1736 public int getTimeToNextAttempt() {
1737 final int additionalTime = account.getLastErrorStatus() == Account.State.POLICY_VIOLATION ? 3 : 0;
1738 final int interval = Math.min((int) (25 * Math.pow(1.3, (additionalTime + attempt))), 300);
1739 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1740 return interval - secondsSinceLast;
1741 }
1742
1743 public int getAttempt() {
1744 return this.attempt;
1745 }
1746
1747 public Features getFeatures() {
1748 return this.features;
1749 }
1750
1751 public long getLastSessionEstablished() {
1752 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1753 return System.currentTimeMillis() - diff;
1754 }
1755
1756 public long getLastConnect() {
1757 return this.lastConnect;
1758 }
1759
1760 public long getLastPingSent() {
1761 return this.lastPingSent;
1762 }
1763
1764 public long getLastDiscoStarted() {
1765 return this.lastDiscoStarted;
1766 }
1767
1768 public long getLastPacketReceived() {
1769 return this.lastPacketReceived;
1770 }
1771
1772 public void sendActive() {
1773 this.sendPacket(new ActivePacket());
1774 }
1775
1776 public void sendInactive() {
1777 this.sendPacket(new InactivePacket());
1778 }
1779
1780 public void resetAttemptCount(boolean resetConnectTime) {
1781 this.attempt = 0;
1782 if (resetConnectTime) {
1783 this.lastConnect = 0;
1784 }
1785 }
1786
1787 public void setInteractive(boolean interactive) {
1788 this.mInteractive = interactive;
1789 }
1790
1791 public Identity getServerIdentity() {
1792 synchronized (this.disco) {
1793 ServiceDiscoveryResult result = disco.get(account.getJid().getDomain());
1794 if (result == null) {
1795 return Identity.UNKNOWN;
1796 }
1797 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1798 if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1799 switch (id.getName()) {
1800 case "Prosody":
1801 return Identity.PROSODY;
1802 case "ejabberd":
1803 return Identity.EJABBERD;
1804 case "Slack-XMPP":
1805 return Identity.SLACK;
1806 }
1807 }
1808 }
1809 }
1810 return Identity.UNKNOWN;
1811 }
1812
1813 private IqGenerator getIqGenerator() {
1814 return mXmppConnectionService.getIqGenerator();
1815 }
1816
1817 public enum Identity {
1818 FACEBOOK,
1819 SLACK,
1820 EJABBERD,
1821 PROSODY,
1822 NIMBUZZ,
1823 UNKNOWN
1824 }
1825
1826 private class MyKeyManager implements X509KeyManager {
1827 @Override
1828 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1829 return account.getPrivateKeyAlias();
1830 }
1831
1832 @Override
1833 public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1834 return null;
1835 }
1836
1837 @Override
1838 public X509Certificate[] getCertificateChain(String alias) {
1839 Log.d(Config.LOGTAG, "getting certificate chain");
1840 try {
1841 return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1842 } catch (Exception e) {
1843 Log.d(Config.LOGTAG, e.getMessage());
1844 return new X509Certificate[0];
1845 }
1846 }
1847
1848 @Override
1849 public String[] getClientAliases(String s, Principal[] principals) {
1850 final String alias = account.getPrivateKeyAlias();
1851 return alias != null ? new String[]{alias} : new String[0];
1852 }
1853
1854 @Override
1855 public String[] getServerAliases(String s, Principal[] principals) {
1856 return new String[0];
1857 }
1858
1859 @Override
1860 public PrivateKey getPrivateKey(String alias) {
1861 try {
1862 return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1863 } catch (Exception e) {
1864 return null;
1865 }
1866 }
1867 }
1868
1869 private static class StateChangingError extends Error {
1870 private final Account.State state;
1871
1872 public StateChangingError(Account.State state) {
1873 this.state = state;
1874 }
1875 }
1876
1877 private static class StateChangingException extends IOException {
1878 private final Account.State state;
1879
1880 public StateChangingException(Account.State state) {
1881 this.state = state;
1882 }
1883 }
1884
1885 public class Features {
1886 XmppConnection connection;
1887 private boolean carbonsEnabled = false;
1888 private boolean encryptionEnabled = false;
1889 private boolean blockListRequested = false;
1890
1891 public Features(final XmppConnection connection) {
1892 this.connection = connection;
1893 }
1894
1895 private boolean hasDiscoFeature(final Jid server, final String feature) {
1896 synchronized (XmppConnection.this.disco) {
1897 return connection.disco.containsKey(server) &&
1898 connection.disco.get(server).getFeatures().contains(feature);
1899 }
1900 }
1901
1902 public boolean carbons() {
1903 return hasDiscoFeature(account.getDomain(), "urn:xmpp:carbons:2");
1904 }
1905
1906 public boolean commands() {
1907 return hasDiscoFeature(account.getDomain(), Namespace.COMMANDS);
1908 }
1909
1910 public boolean easyOnboardingInvites() {
1911 synchronized (commands) {
1912 return commands.containsKey(Namespace.EASY_ONBOARDING_INVITE);
1913 }
1914 }
1915
1916 public boolean bookmarksConversion() {
1917 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1918 }
1919
1920 public boolean avatarConversion() {
1921 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.AVATAR_CONVERSION) && pepPublishOptions();
1922 }
1923
1924 public boolean blocking() {
1925 return hasDiscoFeature(account.getDomain(), Namespace.BLOCKING);
1926 }
1927
1928 public boolean spamReporting() {
1929 return hasDiscoFeature(account.getDomain(), "urn:xmpp:reporting:reason:spam:0");
1930 }
1931
1932 public boolean flexibleOfflineMessageRetrieval() {
1933 return hasDiscoFeature(account.getDomain(), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1934 }
1935
1936 public boolean register() {
1937 return hasDiscoFeature(account.getDomain(), Namespace.REGISTER);
1938 }
1939
1940 public boolean invite() {
1941 return connection.streamFeatures != null && connection.streamFeatures.hasChild("register", Namespace.INVITE);
1942 }
1943
1944 public boolean sm() {
1945 return streamId != null
1946 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1947 }
1948
1949 public boolean csi() {
1950 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1951 }
1952
1953 public boolean pep() {
1954 synchronized (XmppConnection.this.disco) {
1955 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1956 return info != null && info.hasIdentity("pubsub", "pep");
1957 }
1958 }
1959
1960 public boolean pepPersistent() {
1961 synchronized (XmppConnection.this.disco) {
1962 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1963 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1964 }
1965 }
1966
1967 public boolean pepPublishOptions() {
1968 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1969 }
1970
1971 public boolean pepOmemoWhitelisted() {
1972 return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1973 }
1974
1975 public boolean mam() {
1976 return MessageArchiveService.Version.has(getAccountFeatures());
1977 }
1978
1979 public List<String> getAccountFeatures() {
1980 ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1981 return result == null ? Collections.emptyList() : result.getFeatures();
1982 }
1983
1984 public boolean push() {
1985 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUSH)
1986 || hasDiscoFeature(account.getDomain(), Namespace.PUSH);
1987 }
1988
1989 public boolean rosterVersioning() {
1990 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1991 }
1992
1993 public void setBlockListRequested(boolean value) {
1994 this.blockListRequested = value;
1995 }
1996
1997 public boolean httpUpload(long filesize) {
1998 if (Config.DISABLE_HTTP_UPLOAD) {
1999 return false;
2000 } else {
2001 for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2002 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2003 if (items.size() > 0) {
2004 try {
2005 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2006 if (filesize <= maxsize) {
2007 return true;
2008 } else {
2009 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
2010 return false;
2011 }
2012 } catch (Exception e) {
2013 return true;
2014 }
2015 }
2016 }
2017 return false;
2018 }
2019 }
2020
2021 public boolean useLegacyHttpUpload() {
2022 return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
2023 }
2024
2025 public long getMaxHttpUploadSize() {
2026 for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
2027 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
2028 if (items.size() > 0) {
2029 try {
2030 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
2031 } catch (Exception e) {
2032 //ignored
2033 }
2034 }
2035 }
2036 return -1;
2037 }
2038
2039 public boolean stanzaIds() {
2040 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
2041 }
2042
2043 public boolean bookmarks2() {
2044 return Config.USE_BOOKMARKS2 /* || hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS2_COMPAT)*/;
2045 }
2046
2047 public boolean externalServiceDiscovery() {
2048 return hasDiscoFeature(account.getDomain(), Namespace.EXTERNAL_SERVICE_DISCOVERY);
2049 }
2050 }
2051}