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