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