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