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