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