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