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