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