1package eu.siacs.conversations.xmpp;
2
3import android.graphics.Bitmap;
4import android.graphics.BitmapFactory;
5import android.os.Bundle;
6import android.os.Parcelable;
7import android.os.PowerManager;
8import android.os.PowerManager.WakeLock;
9import android.os.SystemClock;
10import android.security.KeyChain;
11import android.util.Base64;
12import android.util.Log;
13import android.util.Pair;
14import android.util.SparseArray;
15
16import org.xmlpull.v1.XmlPullParserException;
17
18import java.io.ByteArrayInputStream;
19import java.io.IOException;
20import java.io.InputStream;
21import java.math.BigInteger;
22import java.net.ConnectException;
23import java.net.IDN;
24import java.net.InetAddress;
25import java.net.InetSocketAddress;
26import java.net.Socket;
27import java.net.URL;
28import java.net.UnknownHostException;
29import java.security.KeyManagementException;
30import java.security.NoSuchAlgorithmException;
31import java.security.Principal;
32import java.security.PrivateKey;
33import java.security.cert.X509Certificate;
34import java.util.ArrayList;
35import java.util.Arrays;
36import java.util.HashMap;
37import java.util.Hashtable;
38import java.util.Iterator;
39import java.util.List;
40import java.util.Map.Entry;
41import java.util.concurrent.atomic.AtomicBoolean;
42import java.util.concurrent.atomic.AtomicInteger;
43
44import javax.net.ssl.HostnameVerifier;
45import javax.net.ssl.KeyManager;
46import javax.net.ssl.SSLContext;
47import javax.net.ssl.SSLSession;
48import javax.net.ssl.SSLSocket;
49import javax.net.ssl.SSLSocketFactory;
50import javax.net.ssl.X509KeyManager;
51import javax.net.ssl.X509TrustManager;
52
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.DNSHelper;
70import eu.siacs.conversations.utils.SSLSocketHelper;
71import eu.siacs.conversations.utils.SocksSocketFactory;
72import eu.siacs.conversations.xml.Element;
73import eu.siacs.conversations.xml.Tag;
74import eu.siacs.conversations.xml.TagWriter;
75import eu.siacs.conversations.xml.XmlReader;
76import eu.siacs.conversations.xml.Namespace;
77import eu.siacs.conversations.xmpp.forms.Data;
78import eu.siacs.conversations.xmpp.forms.Field;
79import eu.siacs.conversations.xmpp.jid.InvalidJidException;
80import eu.siacs.conversations.xmpp.jid.Jid;
81import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
82import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
83import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
84import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
85import eu.siacs.conversations.xmpp.stanzas.IqPacket;
86import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
87import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
88import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
89import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
90import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
91import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
92import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
93import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
94
95public class XmppConnection implements Runnable {
96
97 private static final int PACKET_IQ = 0;
98 private static final int PACKET_MESSAGE = 1;
99 private static final int PACKET_PRESENCE = 2;
100 protected final Account account;
101 private final WakeLock wakeLock;
102 private Socket socket;
103 private XmlReader tagReader;
104 private TagWriter tagWriter = new TagWriter();
105 private final Features features = new Features(this);
106 private boolean needsBinding = true;
107 private boolean shouldAuthenticate = true;
108 private Element streamFeatures;
109 private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
110
111 private String streamId = null;
112 private int smVersion = 3;
113 private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
114
115 private int stanzasReceived = 0;
116 private int stanzasSent = 0;
117 private long lastPacketReceived = 0;
118 private long lastPingSent = 0;
119 private long lastConnect = 0;
120 private long lastSessionStarted = 0;
121 private long lastDiscoStarted = 0;
122 private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
123 private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
124 private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
125 private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
126 private boolean mInteractive = false;
127 private int attempt = 0;
128 private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
129 private OnPresencePacketReceived presenceListener = null;
130 private OnJinglePacketReceived jingleListener = null;
131 private OnIqPacketReceived unregisteredIqListener = null;
132 private OnMessagePacketReceived messageListener = null;
133 private OnStatusChanged statusListener = null;
134 private OnBindListener bindListener = null;
135 private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
136 private OnMessageAcknowledged acknowledgedListener = null;
137 private final XmppConnectionService mXmppConnectionService;
138
139 private SaslMechanism saslMechanism;
140
141 private class MyKeyManager implements X509KeyManager {
142 @Override
143 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
144 return account.getPrivateKeyAlias();
145 }
146
147 @Override
148 public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
149 return null;
150 }
151
152 @Override
153 public X509Certificate[] getCertificateChain(String alias) {
154 Log.d(Config.LOGTAG,"getting certificate chain");
155 try {
156 return KeyChain.getCertificateChain(mXmppConnectionService, alias);
157 } catch (Exception e) {
158 Log.d(Config.LOGTAG,e.getMessage());
159 return new X509Certificate[0];
160 }
161 }
162
163 @Override
164 public String[] getClientAliases(String s, Principal[] principals) {
165 final String alias = account.getPrivateKeyAlias();
166 return alias != null ? new String[]{alias} : new String[0];
167 }
168
169 @Override
170 public String[] getServerAliases(String s, Principal[] principals) {
171 return new String[0];
172 }
173
174 @Override
175 public PrivateKey getPrivateKey(String alias) {
176 try {
177 return KeyChain.getPrivateKey(mXmppConnectionService, alias);
178 } catch (Exception e) {
179 return null;
180 }
181 }
182 }
183
184 public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
185 @Override
186 public void onIqPacketReceived(Account account, IqPacket packet) {
187 if (packet.getType() == IqPacket.TYPE.RESULT) {
188 account.setOption(Account.OPTION_REGISTER, false);
189 forceCloseSocket();
190 changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
191 } else {
192 final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
193 "The password is too weak",
194 "Please use a longer password.");
195 Element error = packet.findChild("error");
196 Account.State state = Account.State.REGISTRATION_FAILED;
197 if (error != null) {
198 if (error.hasChild("conflict")) {
199 state = Account.State.REGISTRATION_CONFLICT;
200 } else if (error.hasChild("resource-constraint")
201 && "wait".equals(error.getAttribute("type"))) {
202 state = Account.State.REGISTRATION_PLEASE_WAIT;
203 } else if (error.hasChild("not-acceptable")
204 && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
205 state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
206 }
207 }
208 changeStatus(state);
209 forceCloseSocket();
210 }
211 }
212 };
213
214 public XmppConnection(final Account account, final XmppConnectionService service) {
215 this.account = account;
216 this.wakeLock = service.getPowerManager().newWakeLock(
217 PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
218 mXmppConnectionService = service;
219 }
220
221 protected void changeStatus(final Account.State nextStatus) {
222 synchronized (this) {
223 if (Thread.currentThread().isInterrupted()) {
224 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
225 return;
226 }
227 if (account.getStatus() != nextStatus) {
228 if ((nextStatus == Account.State.OFFLINE)
229 && (account.getStatus() != Account.State.CONNECTING)
230 && (account.getStatus() != Account.State.ONLINE)
231 && (account.getStatus() != Account.State.DISABLED)) {
232 return;
233 }
234 if (nextStatus == Account.State.ONLINE) {
235 this.attempt = 0;
236 }
237 account.setStatus(nextStatus);
238 } else {
239 return;
240 }
241 }
242 if (statusListener != null) {
243 statusListener.onStatusChanged(account);
244 }
245 }
246
247 public void prepareNewConnection() {
248 this.lastConnect = SystemClock.elapsedRealtime();
249 this.lastPingSent = SystemClock.elapsedRealtime();
250 this.lastDiscoStarted = Long.MAX_VALUE;
251 this.mWaitingForSmCatchup.set(false);
252 this.changeStatus(Account.State.CONNECTING);
253 }
254
255 public boolean isWaitingForSmCatchup() {
256 return mWaitingForSmCatchup.get();
257 }
258
259 public void incrementSmCatchupMessageCounter() {
260 this.mSmCatchupMessageCounter.incrementAndGet();
261 }
262
263 protected void connect() {
264 if (mXmppConnectionService.areMessagesInitialized()) {
265 mXmppConnectionService.resetSendingToWaiting(account);
266 }
267 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
268 features.encryptionEnabled = false;
269 this.attempt++;
270 try {
271 Socket localSocket;
272 shouldAuthenticate = needsBinding = !account.isOptionSet(Account.OPTION_REGISTER);
273 this.changeStatus(Account.State.CONNECTING);
274 final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
275 final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
276 if (useTor) {
277 String destination;
278 if (account.getHostname() == null || account.getHostname().isEmpty()) {
279 destination = account.getServer().toString();
280 } else {
281 destination = account.getHostname();
282 }
283 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": connect to " + destination + " via Tor");
284 localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
285 try {
286 startXmpp(localSocket);
287 } catch (InterruptedException e) {
288 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": thread was interrupted before beginning stream");
289 return;
290 } catch (Exception e) {
291 throw new IOException(e.getMessage());
292 }
293 } else if (extended && account.getHostname() != null && !account.getHostname().isEmpty()) {
294
295 InetSocketAddress address = new InetSocketAddress(account.getHostname(), account.getPort());
296
297 features.encryptionEnabled = account.getPort() == 5223;
298
299 try {
300 if (features.encryptionEnabled) {
301 try {
302 final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
303 localSocket = tlsFactoryVerifier.factory.createSocket();
304 localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
305 final SSLSession session = ((SSLSocket) localSocket).getSession();
306 if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), session)) {
307 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
308 throw new StateChangingException(Account.State.TLS_ERROR);
309 }
310 } catch (KeyManagementException e) {
311 features.encryptionEnabled = false;
312 localSocket = new Socket();
313 }
314 } else {
315 localSocket = new Socket();
316 localSocket.connect(address, Config.SOCKET_TIMEOUT * 1000);
317 }
318 } catch (IOException e) {
319 throw new UnknownHostException();
320 }
321 try {
322 startXmpp(localSocket);
323 } catch (InterruptedException e) {
324 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": thread was interrupted before beginning stream");
325 return;
326 } catch (Exception e) {
327 throw new IOException(e.getMessage());
328 }
329 } else if (DNSHelper.isIp(account.getServer().toString())) {
330 localSocket = new Socket();
331 try {
332 localSocket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
333 } catch (IOException e) {
334 throw new UnknownHostException();
335 }
336 try {
337 startXmpp(localSocket);
338 } catch (InterruptedException e) {
339 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": thread was interrupted before beginning stream");
340 return;
341 } catch (Exception e) {
342 throw new IOException(e.getMessage());
343 }
344 } else {
345 final Bundle result = DNSHelper.getSRVRecord(account.getServer(), mXmppConnectionService);
346 final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
347 for (Iterator<Parcelable> iterator = values.iterator(); iterator.hasNext(); ) {
348 if (Thread.currentThread().isInterrupted()) {
349 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Thread was interrupted");
350 return;
351 }
352 final Bundle namePort = (Bundle) iterator.next();
353 try {
354 String srvRecordServer;
355 try {
356 srvRecordServer = IDN.toASCII(namePort.getString("name"));
357 } catch (final IllegalArgumentException e) {
358 // TODO: Handle me?`
359 srvRecordServer = "";
360 }
361 final int srvRecordPort = namePort.getInt("port");
362 final String srvIpServer = namePort.getString("ip");
363 // if tls is true, encryption is implied and must not be started
364 features.encryptionEnabled = namePort.getBoolean("tls");
365 final InetSocketAddress addr;
366 if (srvIpServer != null) {
367 addr = new InetSocketAddress(srvIpServer, srvRecordPort);
368 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
369 + ": using values from dns " + srvRecordServer
370 + "[" + srvIpServer + "]:" + srvRecordPort + " tls: " + features.encryptionEnabled);
371 } else {
372 addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
373 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
374 + ": using values from dns "
375 + srvRecordServer + ":" + srvRecordPort + " 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(), ((SSLSocket) localSocket).getSession())) {
396 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
397 throw new StateChangingException(Account.State.TLS_ERROR);
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 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 HostnameVerifier verifier;
471
472 public TlsFactoryVerifier(final SSLSocketFactory factory, final HostnameVerifier 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 HostnameVerifier verifier;
494 if (mInteractive) {
495 verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier());
496 } else {
497 verifier = trustManager.wrapHostnameVerifierNonInteractive(new XmppDomainVerifier());
498 }
499
500 return new TlsFactoryVerifier(factory, verifier);
501 }
502
503 @Override
504 public void run() {
505 forceCloseSocket();
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(), 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 instructions = packet.query().findChild("instructions");
980 setAccountCreationFailed((instructions != null) ? instructions.getContent() : "");
981 }
982 }
983 });
984 }
985
986 private void setAccountCreationFailed(String instructions) {
987 changeStatus(Account.State.REGISTRATION_FAILED);
988 disconnect(true);
989 Log.d(Config.LOGTAG, account.getJid().toBareJid()
990 + ": could not register. instructions are"
991 + instructions);
992 }
993
994 public void resetEverything() {
995 resetAttemptCount(true);
996 resetStreamId();
997 clearIqCallbacks();
998 mStanzaQueue.clear();
999 synchronized (this.disco) {
1000 disco.clear();
1001 }
1002 }
1003
1004 private void sendBindRequest() {
1005 while(!mXmppConnectionService.areMessagesInitialized() && socket != null && !socket.isClosed()) {
1006 try {
1007 Thread.sleep(500);
1008 } catch (final InterruptedException ignored) {
1009 }
1010 }
1011 needsBinding = false;
1012 clearIqCallbacks();
1013 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1014 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
1015 .addChild("resource").setContent(account.getResource());
1016 this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
1017 @Override
1018 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1019 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1020 return;
1021 }
1022 final Element bind = packet.findChild("bind");
1023 if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1024 final Element jid = bind.findChild("jid");
1025 if (jid != null && jid.getContent() != null) {
1026 try {
1027 if (account.setJid(Jid.fromString(jid.getContent()))) {
1028 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": bare jid changed during bind. updating database");
1029 mXmppConnectionService.databaseBackend.updateAccount(account);
1030 }
1031 if (streamFeatures.hasChild("session")
1032 && !streamFeatures.findChild("session").hasChild("optional")) {
1033 sendStartSession();
1034 } else {
1035 sendPostBindInitialization();
1036 }
1037 return;
1038 } catch (final InvalidJidException e) {
1039 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server reported invalid jid ("+jid.getContent()+") on bind");
1040 }
1041 } else {
1042 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1043 }
1044 } else {
1045 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1046 }
1047 final Element error = packet.findChild("error");
1048 final String resource = account.getResource().split("\\.")[0];
1049 if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1050 account.setResource(resource + "." + nextRandomId());
1051 } else {
1052 account.setResource(resource);
1053 }
1054 throw new StateChangingError(Account.State.BIND_FAILURE);
1055 }
1056 });
1057 }
1058
1059 private void clearIqCallbacks() {
1060 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1061 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1062 synchronized (this.packetCallbacks) {
1063 if (this.packetCallbacks.size() == 0) {
1064 return;
1065 }
1066 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
1067 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1068 while (iterator.hasNext()) {
1069 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1070 callbacks.add(entry.second);
1071 iterator.remove();
1072 }
1073 }
1074 for(OnIqPacketReceived callback : callbacks) {
1075 callback.onIqPacketReceived(account,failurePacket);
1076 }
1077 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1078 }
1079
1080 public void sendDiscoTimeout() {
1081 if (mWaitForDisco.compareAndSet(true, false)) {
1082 finalizeBind();
1083 }
1084 }
1085
1086 private void sendStartSession() {
1087 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending legacy session to outdated server");
1088 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1089 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1090 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
1091 @Override
1092 public void onIqPacketReceived(Account account, IqPacket packet) {
1093 if (packet.getType() == IqPacket.TYPE.RESULT) {
1094 sendPostBindInitialization();
1095 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1096 throw new StateChangingError(Account.State.SESSION_FAILURE);
1097 }
1098 }
1099 });
1100 }
1101
1102 private void sendPostBindInitialization() {
1103 smVersion = 0;
1104 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1105 smVersion = 3;
1106 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1107 smVersion = 2;
1108 }
1109 if (smVersion != 0) {
1110 synchronized (this.mStanzaQueue) {
1111 final EnablePacket enable = new EnablePacket(smVersion);
1112 tagWriter.writeStanzaAsync(enable);
1113 stanzasSent = 0;
1114 mStanzaQueue.clear();
1115 }
1116 }
1117 features.carbonsEnabled = false;
1118 features.blockListRequested = false;
1119 synchronized (this.disco) {
1120 this.disco.clear();
1121 }
1122 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1123 mPendingServiceDiscoveries.set(0);
1124 if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomainpart())) {
1125 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": do not wait for service discovery");
1126 mWaitForDisco.set(false);
1127 } else {
1128 mWaitForDisco.set(true);
1129 }
1130 lastDiscoStarted = SystemClock.elapsedRealtime();
1131 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1132 Element caps = streamFeatures.findChild("c");
1133 final String hash = caps == null ? null : caps.getAttribute("hash");
1134 final String ver = caps == null ? null : caps.getAttribute("ver");
1135 ServiceDiscoveryResult discoveryResult = null;
1136 if (hash != null && ver != null) {
1137 discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1138 }
1139 if (discoveryResult == null) {
1140 sendServiceDiscoveryInfo(account.getServer());
1141 } else {
1142 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server caps came from cache");
1143 disco.put(account.getServer(), discoveryResult);
1144 }
1145 sendServiceDiscoveryInfo(account.getJid().toBareJid());
1146 sendServiceDiscoveryItems(account.getServer());
1147
1148 if (!mWaitForDisco.get()) {
1149 finalizeBind();
1150 }
1151 this.lastSessionStarted = SystemClock.elapsedRealtime();
1152 }
1153
1154 private void sendServiceDiscoveryInfo(final Jid jid) {
1155 mPendingServiceDiscoveries.incrementAndGet();
1156 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1157 iq.setTo(jid);
1158 iq.query("http://jabber.org/protocol/disco#info");
1159 this.sendIqPacket(iq, new OnIqPacketReceived() {
1160
1161 @Override
1162 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1163 if (packet.getType() == IqPacket.TYPE.RESULT) {
1164 boolean advancedStreamFeaturesLoaded;
1165 synchronized (XmppConnection.this.disco) {
1166 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1167 if (jid.equals(account.getServer())) {
1168 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1169 }
1170 disco.put(jid, result);
1171 advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1172 && disco.containsKey(account.getJid().toBareJid());
1173 }
1174 if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1175 enableAdvancedStreamFeatures();
1176 }
1177 } else {
1178 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1179 }
1180 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1181 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1182 && mWaitForDisco.compareAndSet(true, false)) {
1183 finalizeBind();
1184 }
1185 }
1186 }
1187 });
1188 }
1189
1190 private void finalizeBind() {
1191 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1192 if (bindListener != null) {
1193 bindListener.onBind(account);
1194 }
1195 changeStatus(Account.State.ONLINE);
1196 }
1197
1198 private void enableAdvancedStreamFeatures() {
1199 if (getFeatures().carbons() && !features.carbonsEnabled) {
1200 sendEnableCarbons();
1201 }
1202 if (getFeatures().blocking() && !features.blockListRequested) {
1203 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1204 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1205 }
1206 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1207 listener.onAdvancedStreamFeaturesAvailable(account);
1208 }
1209 }
1210
1211 private void sendServiceDiscoveryItems(final Jid server) {
1212 mPendingServiceDiscoveries.incrementAndGet();
1213 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1214 iq.setTo(server.toDomainJid());
1215 iq.query("http://jabber.org/protocol/disco#items");
1216 this.sendIqPacket(iq, new OnIqPacketReceived() {
1217
1218 @Override
1219 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1220 if (packet.getType() == IqPacket.TYPE.RESULT) {
1221 final List<Element> elements = packet.query().getChildren();
1222 for (final Element element : elements) {
1223 if (element.getName().equals("item")) {
1224 final Jid jid = element.getAttributeAsJid("jid");
1225 if (jid != null && !jid.equals(account.getServer())) {
1226 sendServiceDiscoveryInfo(jid);
1227 }
1228 }
1229 }
1230 } else {
1231 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1232 }
1233 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1234 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1235 && mWaitForDisco.compareAndSet(true, false)) {
1236 finalizeBind();
1237 }
1238 }
1239 }
1240 });
1241 }
1242
1243 private void sendEnableCarbons() {
1244 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1245 iq.addChild("enable", "urn:xmpp:carbons:2");
1246 this.sendIqPacket(iq, new OnIqPacketReceived() {
1247
1248 @Override
1249 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1250 if (!packet.hasChild("error")) {
1251 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1252 + ": successfully enabled carbons");
1253 features.carbonsEnabled = true;
1254 } else {
1255 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1256 + ": error enableing carbons " + packet.toString());
1257 }
1258 }
1259 });
1260 }
1261
1262 private void processStreamError(final Tag currentTag)
1263 throws XmlPullParserException, IOException {
1264 final Element streamError = tagReader.readElement(currentTag);
1265 if (streamError == null) {
1266 return;
1267 }
1268 if (streamError.hasChild("conflict")) {
1269 final String resource = account.getResource().split("\\.")[0];
1270 account.setResource(resource + "." + nextRandomId());
1271 Log.d(Config.LOGTAG,
1272 account.getJid().toBareJid() + ": switching resource due to conflict ("
1273 + account.getResource() + ")");
1274 throw new IOException();
1275 } else if (streamError.hasChild("host-unknown")) {
1276 throw new StateChangingException(Account.State.HOST_UNKNOWN);
1277 } else if (streamError.hasChild("policy-violation")) {
1278 throw new StateChangingException(Account.State.POLICY_VIOLATION);
1279 } else {
1280 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1281 throw new StateChangingException(Account.State.STREAM_ERROR);
1282 }
1283 }
1284
1285 private void sendStartStream() throws IOException {
1286 final Tag stream = Tag.start("stream:stream");
1287 stream.setAttribute("to", account.getServer().toString());
1288 stream.setAttribute("version", "1.0");
1289 stream.setAttribute("xml:lang", "en");
1290 stream.setAttribute("xmlns", "jabber:client");
1291 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1292 tagWriter.writeTag(stream);
1293 }
1294
1295 private String nextRandomId() {
1296 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(36);
1297 }
1298
1299 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1300 packet.setFrom(account.getJid());
1301 return this.sendUnmodifiedIqPacket(packet, callback);
1302 }
1303
1304 public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1305 if (packet.getId() == null) {
1306 final String id = nextRandomId();
1307 packet.setAttribute("id", id);
1308 }
1309 if (callback != null) {
1310 synchronized (this.packetCallbacks) {
1311 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1312 }
1313 }
1314 this.sendPacket(packet);
1315 return packet.getId();
1316 }
1317
1318 public void sendMessagePacket(final MessagePacket packet) {
1319 this.sendPacket(packet);
1320 }
1321
1322 public void sendPresencePacket(final PresencePacket packet) {
1323 this.sendPacket(packet);
1324 }
1325
1326 private synchronized void sendPacket(final AbstractStanza packet) {
1327 if (stanzasSent == Integer.MAX_VALUE) {
1328 resetStreamId();
1329 disconnect(true);
1330 return;
1331 }
1332 synchronized (this.mStanzaQueue) {
1333 tagWriter.writeStanzaAsync(packet);
1334 if (packet instanceof AbstractAcknowledgeableStanza) {
1335 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1336 ++stanzasSent;
1337 this.mStanzaQueue.append(stanzasSent, stanza);
1338 if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1339 if (Config.EXTENDED_SM_LOGGING) {
1340 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1341 }
1342 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1343 }
1344 }
1345 }
1346 }
1347
1348 public void sendPing() {
1349 if (!r()) {
1350 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1351 iq.setFrom(account.getJid());
1352 iq.addChild("ping", "urn:xmpp:ping");
1353 this.sendIqPacket(iq, null);
1354 }
1355 this.lastPingSent = SystemClock.elapsedRealtime();
1356 }
1357
1358 public void setOnMessagePacketReceivedListener(
1359 final OnMessagePacketReceived listener) {
1360 this.messageListener = listener;
1361 }
1362
1363 public void setOnUnregisteredIqPacketReceivedListener(
1364 final OnIqPacketReceived listener) {
1365 this.unregisteredIqListener = listener;
1366 }
1367
1368 public void setOnPresencePacketReceivedListener(
1369 final OnPresencePacketReceived listener) {
1370 this.presenceListener = listener;
1371 }
1372
1373 public void setOnJinglePacketReceivedListener(
1374 final OnJinglePacketReceived listener) {
1375 this.jingleListener = listener;
1376 }
1377
1378 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1379 this.statusListener = listener;
1380 }
1381
1382 public void setOnBindListener(final OnBindListener listener) {
1383 this.bindListener = listener;
1384 }
1385
1386 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1387 this.acknowledgedListener = listener;
1388 }
1389
1390 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1391 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1392 this.advancedStreamFeaturesLoadedListeners.add(listener);
1393 }
1394 }
1395
1396 private void forceCloseSocket() {
1397 if (socket != null) {
1398 try {
1399 socket.close();
1400 } catch (IOException e) {
1401 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception "+e.getMessage()+" during force close");
1402 }
1403 } else {
1404 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": socket was null during force close");
1405 }
1406 }
1407
1408 public void interrupt() {
1409 Thread.currentThread().interrupt();
1410 }
1411
1412 public void disconnect(final boolean force) {
1413 interrupt();
1414 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1415 if (force) {
1416 forceCloseSocket();
1417 } else {
1418 if (tagWriter.isActive()) {
1419 tagWriter.finish();
1420 try {
1421 int i = 0;
1422 boolean warned = false;
1423 while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1424 if (!warned) {
1425 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1426 warned = true;
1427 }
1428 try {
1429 Thread.sleep(200);
1430 } catch(InterruptedException e) {
1431 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sleep interrupted");
1432 }
1433 i++;
1434 }
1435 if (warned) {
1436 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1437 }
1438 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1439 tagWriter.writeTag(Tag.end("stream:stream"));
1440 } catch (final IOException e) {
1441 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1442 } finally {
1443 forceCloseSocket();
1444 }
1445 }
1446 }
1447 }
1448
1449 public void resetStreamId() {
1450 this.streamId = null;
1451 }
1452
1453 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1454 synchronized (this.disco) {
1455 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1456 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1457 if (cursor.getValue().getFeatures().contains(feature)) {
1458 items.add(cursor);
1459 }
1460 }
1461 return items;
1462 }
1463 }
1464
1465 public Jid findDiscoItemByFeature(final String feature) {
1466 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1467 if (items.size() >= 1) {
1468 return items.get(0).getKey();
1469 }
1470 return null;
1471 }
1472
1473 public boolean r() {
1474 if (getFeatures().sm()) {
1475 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1476 return true;
1477 } else {
1478 return false;
1479 }
1480 }
1481
1482 public String getMucServer() {
1483 synchronized (this.disco) {
1484 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1485 final ServiceDiscoveryResult value = cursor.getValue();
1486 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1487 && !value.getFeatures().contains("jabber:iq:gateway")
1488 && !value.hasIdentity("conference", "irc")) {
1489 return cursor.getKey().toString();
1490 }
1491 }
1492 }
1493 return null;
1494 }
1495
1496 public int getTimeToNextAttempt() {
1497 final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1498 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1499 return interval - secondsSinceLast;
1500 }
1501
1502 public int getAttempt() {
1503 return this.attempt;
1504 }
1505
1506 public Features getFeatures() {
1507 return this.features;
1508 }
1509
1510 public long getLastSessionEstablished() {
1511 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1512 return System.currentTimeMillis() - diff;
1513 }
1514
1515 public long getLastConnect() {
1516 return this.lastConnect;
1517 }
1518
1519 public long getLastPingSent() {
1520 return this.lastPingSent;
1521 }
1522
1523 public long getLastDiscoStarted() {
1524 return this.lastDiscoStarted;
1525 }
1526 public long getLastPacketReceived() {
1527 return this.lastPacketReceived;
1528 }
1529
1530 public void sendActive() {
1531 this.sendPacket(new ActivePacket());
1532 }
1533
1534 public void sendInactive() {
1535 this.sendPacket(new InactivePacket());
1536 }
1537
1538 public void resetAttemptCount(boolean resetConnectTime) {
1539 this.attempt = 0;
1540 if (resetConnectTime) {
1541 this.lastConnect = 0;
1542 }
1543 }
1544
1545 public void setInteractive(boolean interactive) {
1546 this.mInteractive = interactive;
1547 }
1548
1549 public Identity getServerIdentity() {
1550 synchronized (this.disco) {
1551 ServiceDiscoveryResult result = disco.get(account.getJid().toDomainJid());
1552 if (result == null) {
1553 return Identity.UNKNOWN;
1554 }
1555 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1556 if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1557 switch (id.getName()) {
1558 case "Prosody":
1559 return Identity.PROSODY;
1560 case "ejabberd":
1561 return Identity.EJABBERD;
1562 case "Slack-XMPP":
1563 return Identity.SLACK;
1564 }
1565 }
1566 }
1567 }
1568 return Identity.UNKNOWN;
1569 }
1570
1571 private class StateChangingError extends Error {
1572 private final Account.State state;
1573
1574 public StateChangingError(Account.State state) {
1575 this.state = state;
1576 }
1577 }
1578
1579 private class StateChangingException extends IOException {
1580 private final Account.State state;
1581
1582 public StateChangingException(Account.State state) {
1583 this.state = state;
1584 }
1585 }
1586
1587 public enum Identity {
1588 FACEBOOK,
1589 SLACK,
1590 EJABBERD,
1591 PROSODY,
1592 NIMBUZZ,
1593 UNKNOWN
1594 }
1595
1596 public class Features {
1597 XmppConnection connection;
1598 private boolean carbonsEnabled = false;
1599 private boolean encryptionEnabled = false;
1600 private boolean blockListRequested = false;
1601
1602 public Features(final XmppConnection connection) {
1603 this.connection = connection;
1604 }
1605
1606 private boolean hasDiscoFeature(final Jid server, final String feature) {
1607 synchronized (XmppConnection.this.disco) {
1608 return connection.disco.containsKey(server) &&
1609 connection.disco.get(server).getFeatures().contains(feature);
1610 }
1611 }
1612
1613 public boolean carbons() {
1614 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1615 }
1616
1617 public boolean blocking() {
1618 return hasDiscoFeature(account.getServer(), Namespace.BLOCKING);
1619 }
1620
1621 public boolean spamReporting() {
1622 return hasDiscoFeature(account.getServer(), "urn:xmpp:reporting:reason:spam:0");
1623 }
1624
1625 public boolean register() {
1626 return hasDiscoFeature(account.getServer(), Namespace.REGISTER);
1627 }
1628
1629 public boolean sm() {
1630 return streamId != null
1631 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1632 }
1633
1634 public boolean csi() {
1635 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1636 }
1637
1638 public boolean pep() {
1639 synchronized (XmppConnection.this.disco) {
1640 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1641 return info != null && info.hasIdentity("pubsub", "pep");
1642 }
1643 }
1644
1645 public boolean pepPersistent() {
1646 synchronized (XmppConnection.this.disco) {
1647 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1648 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1649 }
1650 }
1651
1652 public boolean mam() {
1653 return hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1654 || hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1655 }
1656
1657 public boolean mamLegacy() {
1658 return !hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1659 && hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1660 }
1661
1662 public boolean push() {
1663 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1664 || hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1665 }
1666
1667 public boolean rosterVersioning() {
1668 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1669 }
1670
1671 public void setBlockListRequested(boolean value) {
1672 this.blockListRequested = value;
1673 }
1674
1675 public boolean httpUpload(long filesize) {
1676 if (Config.DISABLE_HTTP_UPLOAD) {
1677 return false;
1678 } else {
1679 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1680 if (items.size() > 0) {
1681 try {
1682 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1683 if(filesize <= maxsize) {
1684 return true;
1685 } else {
1686 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": http upload is not available for files with size "+filesize+" (max is "+maxsize+")");
1687 return false;
1688 }
1689 } catch (Exception e) {
1690 return true;
1691 }
1692 } else {
1693 return false;
1694 }
1695 }
1696 }
1697
1698 public long getMaxHttpUploadSize() {
1699 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1700 if (items.size() > 0) {
1701 try {
1702 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1703 } catch (Exception e) {
1704 return -1;
1705 }
1706 } else {
1707 return -1;
1708 }
1709 }
1710
1711 public boolean stanzaIds() {
1712 return hasDiscoFeature(account.getJid().toBareJid(), Namespace.STANZA_IDS);
1713 }
1714 }
1715
1716 private IqGenerator getIqGenerator() {
1717 return mXmppConnectionService.getIqGenerator();
1718 }
1719}