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