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