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