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