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