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