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 account.setResource(account.getResource().split("\\.")[0]);
1048 throw new StateChangingError(Account.State.BIND_FAILURE);
1049 }
1050 });
1051 }
1052
1053 private void clearIqCallbacks() {
1054 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1055 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1056 synchronized (this.packetCallbacks) {
1057 if (this.packetCallbacks.size() == 0) {
1058 return;
1059 }
1060 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
1061 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1062 while (iterator.hasNext()) {
1063 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1064 callbacks.add(entry.second);
1065 iterator.remove();
1066 }
1067 }
1068 for(OnIqPacketReceived callback : callbacks) {
1069 callback.onIqPacketReceived(account,failurePacket);
1070 }
1071 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1072 }
1073
1074 public void sendDiscoTimeout() {
1075 if (mWaitForDisco.compareAndSet(true, false)) {
1076 finalizeBind();
1077 }
1078 }
1079
1080 private void sendStartSession() {
1081 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending legacy session to outdated server");
1082 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1083 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1084 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
1085 @Override
1086 public void onIqPacketReceived(Account account, IqPacket packet) {
1087 if (packet.getType() == IqPacket.TYPE.RESULT) {
1088 sendPostBindInitialization();
1089 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1090 throw new StateChangingError(Account.State.SESSION_FAILURE);
1091 }
1092 }
1093 });
1094 }
1095
1096 private void sendPostBindInitialization() {
1097 smVersion = 0;
1098 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1099 smVersion = 3;
1100 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1101 smVersion = 2;
1102 }
1103 if (smVersion != 0) {
1104 synchronized (this.mStanzaQueue) {
1105 final EnablePacket enable = new EnablePacket(smVersion);
1106 tagWriter.writeStanzaAsync(enable);
1107 stanzasSent = 0;
1108 mStanzaQueue.clear();
1109 }
1110 }
1111 features.carbonsEnabled = false;
1112 features.blockListRequested = false;
1113 synchronized (this.disco) {
1114 this.disco.clear();
1115 }
1116 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1117 mPendingServiceDiscoveries.set(0);
1118 if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomainpart())) {
1119 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": do not wait for service discovery");
1120 mWaitForDisco.set(false);
1121 } else {
1122 mWaitForDisco.set(true);
1123 }
1124 lastDiscoStarted = SystemClock.elapsedRealtime();
1125 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1126 Element caps = streamFeatures.findChild("c");
1127 final String hash = caps == null ? null : caps.getAttribute("hash");
1128 final String ver = caps == null ? null : caps.getAttribute("ver");
1129 ServiceDiscoveryResult discoveryResult = null;
1130 if (hash != null && ver != null) {
1131 discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1132 }
1133 if (discoveryResult == null) {
1134 sendServiceDiscoveryInfo(account.getServer());
1135 } else {
1136 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server caps came from cache");
1137 disco.put(account.getServer(), discoveryResult);
1138 }
1139 sendServiceDiscoveryInfo(account.getJid().toBareJid());
1140 sendServiceDiscoveryItems(account.getServer());
1141
1142 if (!mWaitForDisco.get()) {
1143 finalizeBind();
1144 }
1145 this.lastSessionStarted = SystemClock.elapsedRealtime();
1146 }
1147
1148 private void sendServiceDiscoveryInfo(final Jid jid) {
1149 mPendingServiceDiscoveries.incrementAndGet();
1150 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1151 iq.setTo(jid);
1152 iq.query("http://jabber.org/protocol/disco#info");
1153 this.sendIqPacket(iq, new OnIqPacketReceived() {
1154
1155 @Override
1156 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1157 if (packet.getType() == IqPacket.TYPE.RESULT) {
1158 boolean advancedStreamFeaturesLoaded;
1159 synchronized (XmppConnection.this.disco) {
1160 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1161 if (jid.equals(account.getServer())) {
1162 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1163 }
1164 disco.put(jid, result);
1165 advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1166 && disco.containsKey(account.getJid().toBareJid());
1167 }
1168 if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1169 enableAdvancedStreamFeatures();
1170 }
1171 } else {
1172 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1173 }
1174 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1175 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1176 && mWaitForDisco.compareAndSet(true, false)) {
1177 finalizeBind();
1178 }
1179 }
1180 }
1181 });
1182 }
1183
1184 private void finalizeBind() {
1185 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1186 if (bindListener != null) {
1187 bindListener.onBind(account);
1188 }
1189 changeStatus(Account.State.ONLINE);
1190 }
1191
1192 private void enableAdvancedStreamFeatures() {
1193 if (getFeatures().carbons() && !features.carbonsEnabled) {
1194 sendEnableCarbons();
1195 }
1196 if (getFeatures().blocking() && !features.blockListRequested) {
1197 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1198 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1199 }
1200 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1201 listener.onAdvancedStreamFeaturesAvailable(account);
1202 }
1203 }
1204
1205 private void sendServiceDiscoveryItems(final Jid server) {
1206 mPendingServiceDiscoveries.incrementAndGet();
1207 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1208 iq.setTo(server.toDomainJid());
1209 iq.query("http://jabber.org/protocol/disco#items");
1210 this.sendIqPacket(iq, new OnIqPacketReceived() {
1211
1212 @Override
1213 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1214 if (packet.getType() == IqPacket.TYPE.RESULT) {
1215 final List<Element> elements = packet.query().getChildren();
1216 for (final Element element : elements) {
1217 if (element.getName().equals("item")) {
1218 final Jid jid = element.getAttributeAsJid("jid");
1219 if (jid != null && !jid.equals(account.getServer())) {
1220 sendServiceDiscoveryInfo(jid);
1221 }
1222 }
1223 }
1224 } else {
1225 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1226 }
1227 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1228 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1229 && mWaitForDisco.compareAndSet(true, false)) {
1230 finalizeBind();
1231 }
1232 }
1233 }
1234 });
1235 }
1236
1237 private void sendEnableCarbons() {
1238 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1239 iq.addChild("enable", "urn:xmpp:carbons:2");
1240 this.sendIqPacket(iq, new OnIqPacketReceived() {
1241
1242 @Override
1243 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1244 if (!packet.hasChild("error")) {
1245 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1246 + ": successfully enabled carbons");
1247 features.carbonsEnabled = true;
1248 } else {
1249 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1250 + ": error enableing carbons " + packet.toString());
1251 }
1252 }
1253 });
1254 }
1255
1256 private void processStreamError(final Tag currentTag)
1257 throws XmlPullParserException, IOException {
1258 final Element streamError = tagReader.readElement(currentTag);
1259 if (streamError == null) {
1260 return;
1261 }
1262 if (streamError.hasChild("conflict")) {
1263 final String resource = account.getResource().split("\\.")[0];
1264 account.setResource(resource + "." + nextRandomId());
1265 Log.d(Config.LOGTAG,
1266 account.getJid().toBareJid() + ": switching resource due to conflict ("
1267 + account.getResource() + ")");
1268 throw new IOException();
1269 } else if (streamError.hasChild("host-unknown")) {
1270 throw new StateChangingException(Account.State.HOST_UNKNOWN);
1271 } else if (streamError.hasChild("policy-violation")) {
1272 throw new StateChangingException(Account.State.POLICY_VIOLATION);
1273 } else {
1274 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1275 throw new StateChangingException(Account.State.STREAM_ERROR);
1276 }
1277 }
1278
1279 private void sendStartStream() throws IOException {
1280 final Tag stream = Tag.start("stream:stream");
1281 stream.setAttribute("to", account.getServer().toString());
1282 stream.setAttribute("version", "1.0");
1283 stream.setAttribute("xml:lang", "en");
1284 stream.setAttribute("xmlns", "jabber:client");
1285 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1286 tagWriter.writeTag(stream);
1287 }
1288
1289 private String nextRandomId() {
1290 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(36);
1291 }
1292
1293 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1294 packet.setFrom(account.getJid());
1295 return this.sendUnmodifiedIqPacket(packet, callback);
1296 }
1297
1298 public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1299 if (packet.getId() == null) {
1300 final String id = nextRandomId();
1301 packet.setAttribute("id", id);
1302 }
1303 if (callback != null) {
1304 synchronized (this.packetCallbacks) {
1305 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1306 }
1307 }
1308 this.sendPacket(packet);
1309 return packet.getId();
1310 }
1311
1312 public void sendMessagePacket(final MessagePacket packet) {
1313 this.sendPacket(packet);
1314 }
1315
1316 public void sendPresencePacket(final PresencePacket packet) {
1317 this.sendPacket(packet);
1318 }
1319
1320 private synchronized void sendPacket(final AbstractStanza packet) {
1321 if (stanzasSent == Integer.MAX_VALUE) {
1322 resetStreamId();
1323 disconnect(true);
1324 return;
1325 }
1326 synchronized (this.mStanzaQueue) {
1327 tagWriter.writeStanzaAsync(packet);
1328 if (packet instanceof AbstractAcknowledgeableStanza) {
1329 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1330 ++stanzasSent;
1331 this.mStanzaQueue.append(stanzasSent, stanza);
1332 if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1333 if (Config.EXTENDED_SM_LOGGING) {
1334 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1335 }
1336 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1337 }
1338 }
1339 }
1340 }
1341
1342 public void sendPing() {
1343 if (!r()) {
1344 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1345 iq.setFrom(account.getJid());
1346 iq.addChild("ping", "urn:xmpp:ping");
1347 this.sendIqPacket(iq, null);
1348 }
1349 this.lastPingSent = SystemClock.elapsedRealtime();
1350 }
1351
1352 public void setOnMessagePacketReceivedListener(
1353 final OnMessagePacketReceived listener) {
1354 this.messageListener = listener;
1355 }
1356
1357 public void setOnUnregisteredIqPacketReceivedListener(
1358 final OnIqPacketReceived listener) {
1359 this.unregisteredIqListener = listener;
1360 }
1361
1362 public void setOnPresencePacketReceivedListener(
1363 final OnPresencePacketReceived listener) {
1364 this.presenceListener = listener;
1365 }
1366
1367 public void setOnJinglePacketReceivedListener(
1368 final OnJinglePacketReceived listener) {
1369 this.jingleListener = listener;
1370 }
1371
1372 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1373 this.statusListener = listener;
1374 }
1375
1376 public void setOnBindListener(final OnBindListener listener) {
1377 this.bindListener = listener;
1378 }
1379
1380 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1381 this.acknowledgedListener = listener;
1382 }
1383
1384 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1385 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1386 this.advancedStreamFeaturesLoadedListeners.add(listener);
1387 }
1388 }
1389
1390 private void forceCloseSocket() {
1391 if (socket != null) {
1392 try {
1393 socket.close();
1394 } catch (IOException e) {
1395 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception "+e.getMessage()+" during force close");
1396 }
1397 } else {
1398 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": socket was null during force close");
1399 }
1400 }
1401
1402 public void interrupt() {
1403 Thread.currentThread().interrupt();
1404 }
1405
1406 public void disconnect(final boolean force) {
1407 interrupt();
1408 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1409 if (force) {
1410 forceCloseSocket();
1411 } else {
1412 if (tagWriter.isActive()) {
1413 tagWriter.finish();
1414 try {
1415 int i = 0;
1416 boolean warned = false;
1417 while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1418 if (!warned) {
1419 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1420 warned = true;
1421 }
1422 try {
1423 Thread.sleep(200);
1424 } catch(InterruptedException e) {
1425 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sleep interrupted");
1426 }
1427 i++;
1428 }
1429 if (warned) {
1430 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1431 }
1432 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1433 tagWriter.writeTag(Tag.end("stream:stream"));
1434 } catch (final IOException e) {
1435 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1436 } finally {
1437 forceCloseSocket();
1438 }
1439 }
1440 }
1441 }
1442
1443 public void resetStreamId() {
1444 this.streamId = null;
1445 }
1446
1447 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1448 synchronized (this.disco) {
1449 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1450 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1451 if (cursor.getValue().getFeatures().contains(feature)) {
1452 items.add(cursor);
1453 }
1454 }
1455 return items;
1456 }
1457 }
1458
1459 public Jid findDiscoItemByFeature(final String feature) {
1460 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1461 if (items.size() >= 1) {
1462 return items.get(0).getKey();
1463 }
1464 return null;
1465 }
1466
1467 public boolean r() {
1468 if (getFeatures().sm()) {
1469 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1470 return true;
1471 } else {
1472 return false;
1473 }
1474 }
1475
1476 public String getMucServer() {
1477 synchronized (this.disco) {
1478 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1479 final ServiceDiscoveryResult value = cursor.getValue();
1480 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1481 && !value.getFeatures().contains("jabber:iq:gateway")
1482 && !value.hasIdentity("conference", "irc")) {
1483 return cursor.getKey().toString();
1484 }
1485 }
1486 }
1487 return null;
1488 }
1489
1490 public int getTimeToNextAttempt() {
1491 final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1492 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1493 return interval - secondsSinceLast;
1494 }
1495
1496 public int getAttempt() {
1497 return this.attempt;
1498 }
1499
1500 public Features getFeatures() {
1501 return this.features;
1502 }
1503
1504 public long getLastSessionEstablished() {
1505 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1506 return System.currentTimeMillis() - diff;
1507 }
1508
1509 public long getLastConnect() {
1510 return this.lastConnect;
1511 }
1512
1513 public long getLastPingSent() {
1514 return this.lastPingSent;
1515 }
1516
1517 public long getLastDiscoStarted() {
1518 return this.lastDiscoStarted;
1519 }
1520 public long getLastPacketReceived() {
1521 return this.lastPacketReceived;
1522 }
1523
1524 public void sendActive() {
1525 this.sendPacket(new ActivePacket());
1526 }
1527
1528 public void sendInactive() {
1529 this.sendPacket(new InactivePacket());
1530 }
1531
1532 public void resetAttemptCount(boolean resetConnectTime) {
1533 this.attempt = 0;
1534 if (resetConnectTime) {
1535 this.lastConnect = 0;
1536 }
1537 }
1538
1539 public void setInteractive(boolean interactive) {
1540 this.mInteractive = interactive;
1541 }
1542
1543 public Identity getServerIdentity() {
1544 synchronized (this.disco) {
1545 ServiceDiscoveryResult result = disco.get(account.getJid().toDomainJid());
1546 if (result == null) {
1547 return Identity.UNKNOWN;
1548 }
1549 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1550 if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1551 switch (id.getName()) {
1552 case "Prosody":
1553 return Identity.PROSODY;
1554 case "ejabberd":
1555 return Identity.EJABBERD;
1556 case "Slack-XMPP":
1557 return Identity.SLACK;
1558 }
1559 }
1560 }
1561 }
1562 return Identity.UNKNOWN;
1563 }
1564
1565 private class StateChangingError extends Error {
1566 private final Account.State state;
1567
1568 public StateChangingError(Account.State state) {
1569 this.state = state;
1570 }
1571 }
1572
1573 private class StateChangingException extends IOException {
1574 private final Account.State state;
1575
1576 public StateChangingException(Account.State state) {
1577 this.state = state;
1578 }
1579 }
1580
1581 public enum Identity {
1582 FACEBOOK,
1583 SLACK,
1584 EJABBERD,
1585 PROSODY,
1586 NIMBUZZ,
1587 UNKNOWN
1588 }
1589
1590 public class Features {
1591 XmppConnection connection;
1592 private boolean carbonsEnabled = false;
1593 private boolean encryptionEnabled = false;
1594 private boolean blockListRequested = false;
1595
1596 public Features(final XmppConnection connection) {
1597 this.connection = connection;
1598 }
1599
1600 private boolean hasDiscoFeature(final Jid server, final String feature) {
1601 synchronized (XmppConnection.this.disco) {
1602 return connection.disco.containsKey(server) &&
1603 connection.disco.get(server).getFeatures().contains(feature);
1604 }
1605 }
1606
1607 public boolean carbons() {
1608 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1609 }
1610
1611 public boolean blocking() {
1612 return hasDiscoFeature(account.getServer(), Namespace.BLOCKING);
1613 }
1614
1615 public boolean spamReporting() {
1616 return hasDiscoFeature(account.getServer(), "urn:xmpp:reporting:reason:spam:0");
1617 }
1618
1619 public boolean register() {
1620 return hasDiscoFeature(account.getServer(), Namespace.REGISTER);
1621 }
1622
1623 public boolean sm() {
1624 return streamId != null
1625 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1626 }
1627
1628 public boolean csi() {
1629 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1630 }
1631
1632 public boolean pep() {
1633 synchronized (XmppConnection.this.disco) {
1634 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1635 return info != null && info.hasIdentity("pubsub", "pep");
1636 }
1637 }
1638
1639 public boolean pepPersistent() {
1640 synchronized (XmppConnection.this.disco) {
1641 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1642 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1643 }
1644 }
1645
1646 public boolean mam() {
1647 return hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1648 || hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1649 }
1650
1651 public boolean mamLegacy() {
1652 return !hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM)
1653 && hasDiscoFeature(account.getJid().toBareJid(), Namespace.MAM_LEGACY);
1654 }
1655
1656 public boolean push() {
1657 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1658 || hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1659 }
1660
1661 public boolean rosterVersioning() {
1662 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1663 }
1664
1665 public void setBlockListRequested(boolean value) {
1666 this.blockListRequested = value;
1667 }
1668
1669 public boolean httpUpload(long filesize) {
1670 if (Config.DISABLE_HTTP_UPLOAD) {
1671 return false;
1672 } else {
1673 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1674 if (items.size() > 0) {
1675 try {
1676 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1677 if(filesize <= maxsize) {
1678 return true;
1679 } else {
1680 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": http upload is not available for files with size "+filesize+" (max is "+maxsize+")");
1681 return false;
1682 }
1683 } catch (Exception e) {
1684 return true;
1685 }
1686 } else {
1687 return false;
1688 }
1689 }
1690 }
1691
1692 public long getMaxHttpUploadSize() {
1693 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Namespace.HTTP_UPLOAD);
1694 if (items.size() > 0) {
1695 try {
1696 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Namespace.HTTP_UPLOAD, "max-file-size"));
1697 } catch (Exception e) {
1698 return -1;
1699 }
1700 } else {
1701 return -1;
1702 }
1703 }
1704
1705 public boolean stanzaIds() {
1706 return hasDiscoFeature(account.getJid().toBareJid(), Namespace.STANZA_IDS);
1707 }
1708 }
1709
1710 private IqGenerator getIqGenerator() {
1711 return mXmppConnectionService.getIqGenerator();
1712 }
1713}