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