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