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