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