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