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