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