1package eu.siacs.conversations.xmpp;
2
3import android.content.Context;
4import android.content.SharedPreferences;
5import android.os.Bundle;
6import android.os.Parcelable;
7import android.os.PowerManager;
8import android.os.PowerManager.WakeLock;
9import android.os.SystemClock;
10import android.preference.PreferenceManager;
11import android.util.Log;
12import android.util.Pair;
13import android.util.SparseArray;
14
15import org.apache.http.conn.ssl.StrictHostnameVerifier;
16import org.json.JSONException;
17import org.json.JSONObject;
18import org.xmlpull.v1.XmlPullParserException;
19
20import java.io.IOException;
21import java.io.InputStream;
22import java.io.OutputStream;
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.security.KeyManagementException;
31import java.security.NoSuchAlgorithmException;
32import java.util.ArrayList;
33import java.util.Arrays;
34import java.util.Collection;
35import java.util.HashMap;
36import java.util.Hashtable;
37import java.util.LinkedList;
38import java.util.List;
39import java.util.Map;
40import java.util.Map.Entry;
41
42import javax.net.ssl.HostnameVerifier;
43import javax.net.ssl.SSLContext;
44import javax.net.ssl.SSLSocket;
45import javax.net.ssl.SSLSocketFactory;
46import javax.net.ssl.X509TrustManager;
47
48import eu.siacs.conversations.Config;
49import eu.siacs.conversations.crypto.sasl.DigestMd5;
50import eu.siacs.conversations.crypto.sasl.Plain;
51import eu.siacs.conversations.crypto.sasl.SaslMechanism;
52import eu.siacs.conversations.crypto.sasl.ScramSha1;
53import eu.siacs.conversations.entities.Account;
54import eu.siacs.conversations.generator.IqGenerator;
55import eu.siacs.conversations.services.XmppConnectionService;
56import eu.siacs.conversations.utils.CryptoHelper;
57import eu.siacs.conversations.utils.DNSHelper;
58import eu.siacs.conversations.utils.Xmlns;
59import eu.siacs.conversations.xml.Element;
60import eu.siacs.conversations.xml.Tag;
61import eu.siacs.conversations.xml.TagWriter;
62import eu.siacs.conversations.xml.XmlReader;
63import eu.siacs.conversations.xmpp.jid.InvalidJidException;
64import eu.siacs.conversations.xmpp.jid.Jid;
65import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
66import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
67import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
68import eu.siacs.conversations.xmpp.stanzas.IqPacket;
69import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
70import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
71import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
72import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
73import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
74import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
75import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
76import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
77
78public class XmppConnection implements Runnable {
79
80 private static final int PACKET_IQ = 0;
81 private static final int PACKET_MESSAGE = 1;
82 private static final int PACKET_PRESENCE = 2;
83 private final Context applicationContext;
84 protected Account account;
85 private final WakeLock wakeLock;
86 private Socket socket;
87 private XmlReader tagReader;
88 private TagWriter tagWriter;
89 private final Features features = new Features(this);
90 private boolean shouldBind = true;
91 private boolean shouldAuthenticate = true;
92 private Element streamFeatures;
93 private final HashMap<Jid, Info> disco = new HashMap<>();
94
95 private String streamId = null;
96 private int smVersion = 3;
97 private final SparseArray<String> messageReceipts = new SparseArray<>();
98
99 private int stanzasReceived = 0;
100 private int stanzasSent = 0;
101 private long lastPacketReceived = 0;
102 private long lastPingSent = 0;
103 private long lastConnect = 0;
104 private long lastSessionStarted = 0;
105 private int attempt = 0;
106 private final Map<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
107 private OnPresencePacketReceived presenceListener = null;
108 private OnJinglePacketReceived jingleListener = null;
109 private OnIqPacketReceived unregisteredIqListener = null;
110 private OnMessagePacketReceived messageListener = null;
111 private OnStatusChanged statusListener = null;
112 private OnBindListener bindListener = null;
113 private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
114 private OnMessageAcknowledged acknowledgedListener = null;
115 private XmppConnectionService mXmppConnectionService = null;
116
117 private SaslMechanism saslMechanism;
118
119 public XmppConnection(final Account account, final XmppConnectionService service) {
120 this.account = account;
121 this.wakeLock = service.getPowerManager().newWakeLock(
122 PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
123 tagWriter = new TagWriter();
124 mXmppConnectionService = service;
125 applicationContext = service.getApplicationContext();
126 }
127
128 protected void changeStatus(final Account.State nextStatus) {
129 if (account.getStatus() != nextStatus) {
130 if ((nextStatus == Account.State.OFFLINE)
131 && (account.getStatus() != Account.State.CONNECTING)
132 && (account.getStatus() != Account.State.ONLINE)
133 && (account.getStatus() != Account.State.DISABLED)) {
134 return;
135 }
136 if (nextStatus == Account.State.ONLINE) {
137 this.attempt = 0;
138 }
139 account.setStatus(nextStatus);
140 if (statusListener != null) {
141 statusListener.onStatusChanged(account);
142 }
143 }
144 }
145
146 protected void connect() {
147 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
148 features.encryptionEnabled = false;
149 lastConnect = SystemClock.elapsedRealtime();
150 lastPingSent = SystemClock.elapsedRealtime();
151 this.attempt++;
152 try {
153 shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
154 tagReader = new XmlReader(wakeLock);
155 tagWriter = new TagWriter();
156 packetCallbacks.clear();
157 this.changeStatus(Account.State.CONNECTING);
158 if (DNSHelper.isIp(account.getServer().toString())) {
159 socket = new Socket();
160 try {
161 socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
162 } catch (IOException e) {
163 throw new UnknownHostException();
164 }
165 } else {
166 final Bundle result = DNSHelper.getSRVRecord(account.getServer());
167 if (result == null) {
168 throw new IOException("unhandled exception in DNS resolver");
169 }
170 final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
171 if ("timeout".equals(result.getString("error"))) {
172 throw new IOException("timeout in dns");
173 } else if (values != null) {
174 int i = 0;
175 boolean socketError = true;
176 while (socketError && values.size() > i) {
177 final Bundle namePort = (Bundle) values.get(i);
178 try {
179 String srvRecordServer;
180 try {
181 srvRecordServer = IDN.toASCII(namePort.getString("name"));
182 } catch (final IllegalArgumentException e) {
183 // TODO: Handle me?`
184 srvRecordServer = "";
185 }
186 final int srvRecordPort = namePort.getInt("port");
187 final String srvIpServer = namePort.getString("ip");
188 final InetSocketAddress addr;
189 if (srvIpServer != null) {
190 addr = new InetSocketAddress(srvIpServer, srvRecordPort);
191 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
192 + ": using values from dns " + srvRecordServer
193 + "[" + srvIpServer + "]:" + srvRecordPort);
194 } else {
195 addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
196 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
197 + ": using values from dns "
198 + srvRecordServer + ":" + srvRecordPort);
199 }
200 socket = new Socket();
201 socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
202 socketError = false;
203 } catch (final UnknownHostException e) {
204 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
205 i++;
206 } catch (final IOException e) {
207 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
208 i++;
209 }
210 }
211 if (socketError) {
212 throw new UnknownHostException();
213 }
214 } else {
215 throw new IOException("unhandled exception in DNS resolver");
216 }
217 }
218 final OutputStream out = socket.getOutputStream();
219 tagWriter.setOutputStream(out);
220 final InputStream in = socket.getInputStream();
221 tagReader.setInputStream(in);
222 tagWriter.beginDocument();
223 sendStartStream();
224 Tag nextTag;
225 while ((nextTag = tagReader.readTag()) != null) {
226 if (nextTag.isStart("stream")) {
227 processStream(nextTag);
228 break;
229 } else {
230 throw new IOException("unknown tag on connect");
231 }
232 }
233 if (socket.isConnected()) {
234 socket.close();
235 }
236 } catch (final IncompatibleServerException e) {
237 this.changeStatus(Account.State.INCOMPATIBLE_SERVER);
238 } catch (final SecurityException e) {
239 this.changeStatus(Account.State.SECURITY_ERROR);
240 } catch (final UnauthorizedException e) {
241 this.changeStatus(Account.State.UNAUTHORIZED);
242 } catch (final UnknownHostException | ConnectException e) {
243 this.changeStatus(Account.State.SERVER_NOT_FOUND);
244 } catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
245 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
246 this.changeStatus(Account.State.OFFLINE);
247 this.attempt--; //don't count attempt when reconnecting instantly anyway
248 } finally {
249 if (socket != null) {
250 try {
251 socket.close();
252 } catch (IOException e) {
253
254 }
255 }
256 if (wakeLock.isHeld()) {
257 try {
258 wakeLock.release();
259 } catch (final RuntimeException ignored) {
260 }
261 }
262 }
263 }
264
265 @Override
266 public void run() {
267 try {
268 if (socket != null) {
269 socket.close();
270 }
271 } catch (final IOException ignored) {
272
273 }
274 connect();
275 }
276
277 private void processStream(final Tag currentTag) throws XmlPullParserException,
278 IOException, NoSuchAlgorithmException {
279 Tag nextTag = tagReader.readTag();
280
281 while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
282 if (nextTag.isStart("error")) {
283 processStreamError(nextTag);
284 } else if (nextTag.isStart("features")) {
285 processStreamFeatures(nextTag);
286 } else if (nextTag.isStart("proceed")) {
287 switchOverToTls(nextTag);
288 } else if (nextTag.isStart("success")) {
289 final String challenge = tagReader.readElement(nextTag).getContent();
290 try {
291 saslMechanism.getResponse(challenge);
292 } catch (final SaslMechanism.AuthenticationException e) {
293 disconnect(true);
294 Log.e(Config.LOGTAG, String.valueOf(e));
295 }
296 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
297 account.setKey(Account.PINNED_MECHANISM_KEY,
298 String.valueOf(saslMechanism.getPriority()));
299 tagReader.reset();
300 sendStartStream();
301 processStream(tagReader.readTag());
302 break;
303 } else if (nextTag.isStart("failure")) {
304 throw new UnauthorizedException();
305 } else if (nextTag.isStart("challenge")) {
306 final String challenge = tagReader.readElement(nextTag).getContent();
307 final Element response = new Element("response");
308 response.setAttribute("xmlns",
309 "urn:ietf:params:xml:ns:xmpp-sasl");
310 try {
311 response.setContent(saslMechanism.getResponse(challenge));
312 } catch (final SaslMechanism.AuthenticationException e) {
313 // TODO: Send auth abort tag.
314 Log.e(Config.LOGTAG, e.toString());
315 }
316 tagWriter.writeElement(response);
317 } else if (nextTag.isStart("enabled")) {
318 final Element enabled = tagReader.readElement(nextTag);
319 if ("true".equals(enabled.getAttribute("resume"))) {
320 this.streamId = enabled.getAttribute("id");
321 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
322 + ": stream managment(" + smVersion
323 + ") enabled (resumable)");
324 } else {
325 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
326 + ": stream managment(" + smVersion + ") enabled");
327 }
328 this.lastSessionStarted = SystemClock.elapsedRealtime();
329 this.stanzasReceived = 0;
330 final RequestPacket r = new RequestPacket(smVersion);
331 tagWriter.writeStanzaAsync(r);
332 } else if (nextTag.isStart("resumed")) {
333 lastPacketReceived = SystemClock.elapsedRealtime();
334 final Element resumed = tagReader.readElement(nextTag);
335 final String h = resumed.getAttribute("h");
336 try {
337 final int serverCount = Integer.parseInt(h);
338 if (serverCount != stanzasSent) {
339 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
340 + ": session resumed with lost packages");
341 stanzasSent = serverCount;
342 } else {
343 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
344 + ": session resumed");
345 }
346 if (acknowledgedListener != null) {
347 for (int i = 0; i < messageReceipts.size(); ++i) {
348 if (serverCount >= messageReceipts.keyAt(i)) {
349 acknowledgedListener.onMessageAcknowledged(
350 account, messageReceipts.valueAt(i));
351 }
352 }
353 }
354 messageReceipts.clear();
355 } catch (final NumberFormatException ignored) {
356 }
357 sendServiceDiscoveryInfo(account.getServer());
358 sendServiceDiscoveryInfo(account.getJid().toBareJid());
359 sendServiceDiscoveryItems(account.getServer());
360 sendInitialPing();
361 } else if (nextTag.isStart("r")) {
362 tagReader.readElement(nextTag);
363 if (Config.EXTENDED_SM_LOGGING) {
364 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
365 }
366 final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
367 tagWriter.writeStanzaAsync(ack);
368 } else if (nextTag.isStart("a")) {
369 final Element ack = tagReader.readElement(nextTag);
370 lastPacketReceived = SystemClock.elapsedRealtime();
371 try {
372 final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
373 if (Config.EXTENDED_SM_LOGGING) {
374 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + serverSequence);
375 }
376 final String msgId = this.messageReceipts.get(serverSequence);
377 if (msgId != null) {
378 if (this.acknowledgedListener != null) {
379 this.acknowledgedListener.onMessageAcknowledged(
380 account, msgId);
381 }
382 this.messageReceipts.remove(serverSequence);
383 }
384 } catch (NumberFormatException e) {
385 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
386 }
387 } else if (nextTag.isStart("failed")) {
388 tagReader.readElement(nextTag);
389 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
390 streamId = null;
391 if (account.getStatus() != Account.State.ONLINE) {
392 sendBindRequest();
393 }
394 } else if (nextTag.isStart("iq")) {
395 processIq(nextTag);
396 } else if (nextTag.isStart("message")) {
397 processMessage(nextTag);
398 } else if (nextTag.isStart("presence")) {
399 processPresence(nextTag);
400 }
401 nextTag = tagReader.readTag();
402 }
403 if (account.getStatus() == Account.State.ONLINE) {
404 account. setStatus(Account.State.OFFLINE);
405 if (statusListener != null) {
406 statusListener.onStatusChanged(account);
407 }
408 }
409 }
410
411 private void sendInitialPing() {
412 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": sending intial ping");
413 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
414 iq.setFrom(account.getJid());
415 iq.addChild("ping", "urn:xmpp:ping");
416 this.sendIqPacket(iq, new OnIqPacketReceived() {
417 @Override
418 public void onIqPacketReceived(final Account account, final IqPacket packet) {
419 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
420 + ": online with resource " + account.getResource());
421 changeStatus(Account.State.ONLINE);
422 }
423 });
424 }
425
426 private Element processPacket(final Tag currentTag, final int packetType)
427 throws XmlPullParserException, IOException {
428 Element element;
429 switch (packetType) {
430 case PACKET_IQ:
431 element = new IqPacket();
432 break;
433 case PACKET_MESSAGE:
434 element = new MessagePacket();
435 break;
436 case PACKET_PRESENCE:
437 element = new PresencePacket();
438 break;
439 default:
440 return null;
441 }
442 element.setAttributes(currentTag.getAttributes());
443 Tag nextTag = tagReader.readTag();
444 if (nextTag == null) {
445 throw new IOException("interrupted mid tag");
446 }
447 while (!nextTag.isEnd(element.getName())) {
448 if (!nextTag.isNo()) {
449 final Element child = tagReader.readElement(nextTag);
450 final String type = currentTag.getAttribute("type");
451 if (packetType == PACKET_IQ
452 && "jingle".equals(child.getName())
453 && ("set".equalsIgnoreCase(type) || "get"
454 .equalsIgnoreCase(type))) {
455 element = new JinglePacket();
456 element.setAttributes(currentTag.getAttributes());
457 }
458 element.addChild(child);
459 }
460 nextTag = tagReader.readTag();
461 if (nextTag == null) {
462 throw new IOException("interrupted mid tag");
463 }
464 }
465 if (stanzasReceived == Integer.MAX_VALUE) {
466 resetStreamId();
467 throw new IOException("time to restart the session. cant handle >2 billion pcks");
468 }
469 ++stanzasReceived;
470 lastPacketReceived = SystemClock.elapsedRealtime();
471 return element;
472 }
473
474 private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
475 final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
476
477 if (packet.getId() == null) {
478 return; // an iq packet without id is definitely invalid
479 }
480
481 if (packet instanceof JinglePacket) {
482 if (this.jingleListener != null) {
483 this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
484 }
485 } else {
486 if (packetCallbacks.containsKey(packet.getId())) {
487 final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
488 // Packets to the server should have responses from the server
489 if (packetCallbackDuple.first.toServer(account)) {
490 if (packet.fromServer(account)) {
491 packetCallbackDuple.second.onIqPacketReceived(account, packet);
492 packetCallbacks.remove(packet.getId());
493 } else {
494 Log.e(Config.LOGTAG,account.getJid().toBareJid().toString()+": ignoring spoofed iq packet");
495 }
496 } else {
497 if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
498 packetCallbackDuple.second.onIqPacketReceived(account, packet);
499 packetCallbacks.remove(packet.getId());
500 } else {
501 Log.e(Config.LOGTAG,account.getJid().toBareJid().toString()+": ignoring spoofed iq packet");
502 }
503 }
504 } else if (packet.getType() == IqPacket.TYPE.GET|| packet.getType() == IqPacket.TYPE.SET) {
505 this.unregisteredIqListener.onIqPacketReceived(account, packet);
506 }
507 }
508 }
509
510 private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
511 final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
512 this.messageListener.onMessagePacketReceived(account, packet);
513 }
514
515 private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
516 PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
517 this.presenceListener.onPresencePacketReceived(account, packet);
518 }
519
520 private void sendStartTLS() throws IOException {
521 final Tag startTLS = Tag.empty("starttls");
522 startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
523 tagWriter.writeTag(startTLS);
524 }
525
526 private SharedPreferences getPreferences() {
527 return PreferenceManager.getDefaultSharedPreferences(applicationContext);
528 }
529
530 private boolean enableLegacySSL() {
531 return getPreferences().getBoolean("enable_legacy_ssl", false);
532 }
533
534 private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
535 tagReader.readTag();
536 try {
537 final SSLContext sc = SSLContext.getInstance("TLS");
538 sc.init(null,new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},mXmppConnectionService.getRNG());
539 final SSLSocketFactory factory = sc.getSocketFactory();
540 final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
541 final InetAddress address = socket == null ? null : socket.getInetAddress();
542
543 if (factory == null || address == null || verifier == null) {
544 throw new IOException("could not setup ssl");
545 }
546
547 final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
548
549 if (sslSocket == null) {
550 throw new IOException("could not initialize ssl socket");
551 }
552
553 final String[] supportProtocols;
554 final Collection<String> supportedProtocols = new LinkedList<>(
555 Arrays.asList(sslSocket.getSupportedProtocols()));
556 supportedProtocols.remove("SSLv3");
557 supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
558
559 sslSocket.setEnabledProtocols(supportProtocols);
560
561 final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
562 sslSocket.getSupportedCipherSuites());
563 //Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
564 if (cipherSuites.length > 0) {
565 sslSocket.setEnabledCipherSuites(cipherSuites);
566 }
567
568 if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
569 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
570 throw new SecurityException();
571 }
572 tagReader.setInputStream(sslSocket.getInputStream());
573 tagWriter.setOutputStream(sslSocket.getOutputStream());
574 sendStartStream();
575 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
576 features.encryptionEnabled = true;
577 processStream(tagReader.readTag());
578 sslSocket.close();
579 } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
580 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
581 throw new SecurityException();
582 }
583 }
584
585 private void processStreamFeatures(final Tag currentTag)
586 throws XmlPullParserException, IOException {
587 this.streamFeatures = tagReader.readElement(currentTag);
588 if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
589 sendStartTLS();
590 } else if (this.streamFeatures.hasChild("register")
591 && account.isOptionSet(Account.OPTION_REGISTER)
592 && features.encryptionEnabled) {
593 sendRegistryRequest();
594 } else if (!this.streamFeatures.hasChild("register")
595 && account.isOptionSet(Account.OPTION_REGISTER)) {
596 changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
597 disconnect(true);
598 } else if (this.streamFeatures.hasChild("mechanisms")
599 && shouldAuthenticate && features.encryptionEnabled) {
600 final List<String> mechanisms = extractMechanisms(streamFeatures
601 .findChild("mechanisms"));
602 final Element auth = new Element("auth");
603 auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
604 if (mechanisms.contains("SCRAM-SHA-1")) {
605 saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
606 } else if (mechanisms.contains("PLAIN")) {
607 saslMechanism = new Plain(tagWriter, account);
608 } else if (mechanisms.contains("DIGEST-MD5")) {
609 saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
610 }
611 if (saslMechanism != null) {
612 final JSONObject keys = account.getKeys();
613 try {
614 if (keys.has(Account.PINNED_MECHANISM_KEY) &&
615 keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
616 Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
617 " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
618 ") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
619 "). Possible downgrade attack?");
620 throw new SecurityException();
621 }
622 } catch (final JSONException e) {
623 Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
624 }
625 Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
626 auth.setAttribute("mechanism", saslMechanism.getMechanism());
627 if (!saslMechanism.getClientFirstMessage().isEmpty()) {
628 auth.setContent(saslMechanism.getClientFirstMessage());
629 }
630 tagWriter.writeElement(auth);
631 } else {
632 throw new IncompatibleServerException();
633 }
634 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
635 + smVersion)
636 && streamId != null) {
637 if (Config.EXTENDED_SM_LOGGING) {
638 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
639 }
640 final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
641 this.tagWriter.writeStanzaAsync(resume);
642 } else if (this.streamFeatures.hasChild("bind") && shouldBind) {
643 sendBindRequest();
644 } else {
645 disconnect(true);
646 changeStatus(Account.State.INCOMPATIBLE_SERVER);
647 }
648 }
649
650 private List<String> extractMechanisms(final Element stream) {
651 final ArrayList<String> mechanisms = new ArrayList<>(stream
652 .getChildren().size());
653 for (final Element child : stream.getChildren()) {
654 mechanisms.add(child.getContent());
655 }
656 return mechanisms;
657 }
658
659 private void sendRegistryRequest() {
660 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
661 register.query("jabber:iq:register");
662 register.setTo(account.getServer());
663 sendIqPacket(register, new OnIqPacketReceived() {
664
665 @Override
666 public void onIqPacketReceived(final Account account, final IqPacket packet) {
667 final Element instructions = packet.query().findChild("instructions");
668 if (packet.query().hasChild("username")
669 && (packet.query().hasChild("password"))) {
670 final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
671 final Element username = new Element("username").setContent(account.getUsername());
672 final Element password = new Element("password").setContent(account.getPassword());
673 register.query("jabber:iq:register").addChild(username);
674 register.query().addChild(password);
675 sendIqPacket(register, new OnIqPacketReceived() {
676
677 @Override
678 public void onIqPacketReceived(final Account account, final IqPacket packet) {
679 if (packet.getType() == IqPacket.TYPE.RESULT) {
680 account.setOption(Account.OPTION_REGISTER,
681 false);
682 changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
683 } else if (packet.hasChild("error")
684 && (packet.findChild("error")
685 .hasChild("conflict"))) {
686 changeStatus(Account.State.REGISTRATION_CONFLICT);
687 } else {
688 changeStatus(Account.State.REGISTRATION_FAILED);
689 Log.d(Config.LOGTAG, packet.toString());
690 }
691 disconnect(true);
692 }
693 });
694 } else {
695 changeStatus(Account.State.REGISTRATION_FAILED);
696 disconnect(true);
697 Log.d(Config.LOGTAG, account.getJid().toBareJid()
698 + ": could not register. instructions are"
699 + (instructions != null ? instructions.getContent() : ""));
700 }
701 }
702 });
703 }
704
705 private void sendBindRequest() {
706 while(!mXmppConnectionService.areMessagesInitialized()) {
707 try {
708 Thread.sleep(500);
709 } catch (final InterruptedException ignored) {
710 }
711 }
712 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
713 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
714 .addChild("resource").setContent(account.getResource());
715 this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
716 @Override
717 public void onIqPacketReceived(final Account account, final IqPacket packet) {
718 final Element bind = packet.findChild("bind");
719 if (bind != null) {
720 final Element jid = bind.findChild("jid");
721 if (jid != null && jid.getContent() != null) {
722 try {
723 account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
724 } catch (final InvalidJidException e) {
725 // TODO: Handle the case where an external JID is technically invalid?
726 }
727 if (streamFeatures.hasChild("session")) {
728 sendStartSession();
729 } else {
730 sendPostBindInitialization();
731 }
732 } else {
733 disconnect(true);
734 }
735 } else {
736 disconnect(true);
737 }
738 }
739 });
740 }
741
742 private void sendStartSession() {
743 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
744 startSession.addChild("session","urn:ietf:params:xml:ns:xmpp-session");
745 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
746 @Override
747 public void onIqPacketReceived(Account account, IqPacket packet) {
748 if (packet.getType() == IqPacket.TYPE.RESULT) {
749 sendPostBindInitialization();
750 } else {
751 disconnect(true);
752 }
753 }
754 });
755 }
756
757 private void sendPostBindInitialization() {
758 smVersion = 0;
759 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
760 smVersion = 3;
761 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
762 smVersion = 2;
763 }
764 if (smVersion != 0) {
765 final EnablePacket enable = new EnablePacket(smVersion);
766 tagWriter.writeStanzaAsync(enable);
767 stanzasSent = 0;
768 messageReceipts.clear();
769 }
770 features.carbonsEnabled = false;
771 features.blockListRequested = false;
772 disco.clear();
773 sendServiceDiscoveryInfo(account.getServer());
774 sendServiceDiscoveryInfo(account.getJid().toBareJid());
775 sendServiceDiscoveryItems(account.getServer());
776 if (bindListener != null) {
777 bindListener.onBind(account);
778 }
779 sendInitialPing();
780 }
781
782 private void sendServiceDiscoveryInfo(final Jid jid) {
783 if (disco.containsKey(jid)) {
784 if (account.getServer().equals(jid)) {
785 enableAdvancedStreamFeatures();
786 }
787 } else {
788 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
789 iq.setTo(jid);
790 iq.query("http://jabber.org/protocol/disco#info");
791 this.sendIqPacket(iq, new OnIqPacketReceived() {
792
793 @Override
794 public void onIqPacketReceived(final Account account, final IqPacket packet) {
795 final List<Element> elements = packet.query().getChildren();
796 final Info info = new Info();
797 for (final Element element : elements) {
798 if (element.getName().equals("identity")) {
799 String type = element.getAttribute("type");
800 String category = element.getAttribute("category");
801 if (type != null && category != null) {
802 info.identities.add(new Pair<>(category,type));
803 }
804 } else if (element.getName().equals("feature")) {
805 info.features.add(element.getAttribute("var"));
806 }
807 }
808 disco.put(jid, info);
809
810 if (account.getServer().equals(jid)) {
811 enableAdvancedStreamFeatures();
812 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
813 listener.onAdvancedStreamFeaturesAvailable(account);
814 }
815 }
816 }
817 });
818 }
819 }
820
821 private void enableAdvancedStreamFeatures() {
822 if (getFeatures().carbons() && !features.carbonsEnabled) {
823 sendEnableCarbons();
824 }
825 if (getFeatures().blocking() && !features.blockListRequested) {
826 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": Requesting block list");
827 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
828 }
829 }
830
831 private void sendServiceDiscoveryItems(final Jid server) {
832 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
833 iq.setTo(server.toDomainJid());
834 iq.query("http://jabber.org/protocol/disco#items");
835 this.sendIqPacket(iq, new OnIqPacketReceived() {
836
837 @Override
838 public void onIqPacketReceived(final Account account, final IqPacket packet) {
839 final List<Element> elements = packet.query().getChildren();
840 for (final Element element : elements) {
841 if (element.getName().equals("item")) {
842 final Jid jid = element.getAttributeAsJid("jid");
843 if (jid != null && !jid.equals(account.getServer())) {
844 sendServiceDiscoveryInfo(jid);
845 }
846 }
847 }
848 }
849 });
850 }
851
852 private void sendEnableCarbons() {
853 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
854 iq.addChild("enable", "urn:xmpp:carbons:2");
855 this.sendIqPacket(iq, new OnIqPacketReceived() {
856
857 @Override
858 public void onIqPacketReceived(final Account account, final IqPacket packet) {
859 if (!packet.hasChild("error")) {
860 Log.d(Config.LOGTAG, account.getJid().toBareJid()
861 + ": successfully enabled carbons");
862 features.carbonsEnabled = true;
863 } else {
864 Log.d(Config.LOGTAG, account.getJid().toBareJid()
865 + ": error enableing carbons " + packet.toString());
866 }
867 }
868 });
869 }
870
871 private void processStreamError(final Tag currentTag)
872 throws XmlPullParserException, IOException {
873 final Element streamError = tagReader.readElement(currentTag);
874 if (streamError != null && streamError.hasChild("conflict")) {
875 final String resource = account.getResource().split("\\.")[0];
876 account.setResource(resource + "." + nextRandomId());
877 Log.d(Config.LOGTAG,
878 account.getJid().toBareJid() + ": switching resource due to conflict ("
879 + account.getResource() + ")");
880 }
881 }
882
883 private void sendStartStream() throws IOException {
884 final Tag stream = Tag.start("stream:stream");
885 stream.setAttribute("from", account.getJid().toBareJid().toString());
886 stream.setAttribute("to", account.getServer().toString());
887 stream.setAttribute("version", "1.0");
888 stream.setAttribute("xml:lang", "en");
889 stream.setAttribute("xmlns", "jabber:client");
890 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
891 tagWriter.writeTag(stream);
892 }
893
894 private String nextRandomId() {
895 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
896 }
897
898 public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
899 packet.setFrom(account.getJid());
900 this.sendUnmodifiedIqPacket(packet,callback);
901
902 }
903
904 private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
905 if (packet.getId() == null) {
906 final String id = nextRandomId();
907 packet.setAttribute("id", id);
908 }
909 if (callback != null) {
910 if (packet.getId() == null) {
911 packet.setId(nextRandomId());
912 }
913 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
914 }
915 this.sendPacket(packet);
916 }
917
918 public void sendMessagePacket(final MessagePacket packet) {
919 this.sendPacket(packet);
920 }
921
922 public void sendPresencePacket(final PresencePacket packet) {
923 this.sendPacket(packet);
924 }
925
926 private synchronized void sendPacket(final AbstractStanza packet) {
927 if (stanzasSent == Integer.MAX_VALUE) {
928 resetStreamId();
929 disconnect(true);
930 return;
931 }
932 final String name = packet.getName();
933 if (name.equals("iq") || name.equals("message") || name.equals("presence")) {
934 ++stanzasSent;
935 }
936 tagWriter.writeStanzaAsync(packet);
937 if (packet instanceof MessagePacket && packet.getId() != null && getFeatures().sm()) {
938 if (Config.EXTENDED_SM_LOGGING) {
939 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
940 }
941 this.messageReceipts.put(stanzasSent, packet.getId());
942 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
943 }
944 }
945
946 public void sendPing() {
947 if (streamFeatures.hasChild("sm")) {
948 tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
949 } else {
950 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
951 iq.setFrom(account.getJid());
952 iq.addChild("ping", "urn:xmpp:ping");
953 this.sendIqPacket(iq, null);
954 }
955 this.lastPingSent = SystemClock.elapsedRealtime();
956 }
957
958 public void setOnMessagePacketReceivedListener(
959 final OnMessagePacketReceived listener) {
960 this.messageListener = listener;
961 }
962
963 public void setOnUnregisteredIqPacketReceivedListener(
964 final OnIqPacketReceived listener) {
965 this.unregisteredIqListener = listener;
966 }
967
968 public void setOnPresencePacketReceivedListener(
969 final OnPresencePacketReceived listener) {
970 this.presenceListener = listener;
971 }
972
973 public void setOnJinglePacketReceivedListener(
974 final OnJinglePacketReceived listener) {
975 this.jingleListener = listener;
976 }
977
978 public void setOnStatusChangedListener(final OnStatusChanged listener) {
979 this.statusListener = listener;
980 }
981
982 public void setOnBindListener(final OnBindListener listener) {
983 this.bindListener = listener;
984 }
985
986 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
987 this.acknowledgedListener = listener;
988 }
989
990 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
991 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
992 this.advancedStreamFeaturesLoadedListeners.add(listener);
993 }
994 }
995
996 public void disconnect(final boolean force) {
997 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
998 try {
999 if (force) {
1000 socket.close();
1001 return;
1002 }
1003 new Thread(new Runnable() {
1004
1005 @Override
1006 public void run() {
1007 if (tagWriter.isActive()) {
1008 tagWriter.finish();
1009 try {
1010 while (!tagWriter.finished()) {
1011 Log.d(Config.LOGTAG, "not yet finished");
1012 Thread.sleep(100);
1013 }
1014 tagWriter.writeTag(Tag.end("stream:stream"));
1015 socket.close();
1016 } catch (final IOException e) {
1017 Log.d(Config.LOGTAG,
1018 "io exception during disconnect");
1019 } catch (final InterruptedException e) {
1020 Log.d(Config.LOGTAG, "interrupted");
1021 }
1022 }
1023 }
1024 }).start();
1025 } catch (final IOException e) {
1026 Log.d(Config.LOGTAG, "io exception during disconnect");
1027 }
1028 }
1029
1030 public void resetStreamId() {
1031 this.streamId = null;
1032 }
1033
1034 public List<Jid> findDiscoItemsByFeature(final String feature) {
1035 final List<Jid> items = new ArrayList<>();
1036 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1037 if (cursor.getValue().features.contains(feature)) {
1038 items.add(cursor.getKey());
1039 }
1040 }
1041 return items;
1042 }
1043
1044 public Jid findDiscoItemByFeature(final String feature) {
1045 final List<Jid> items = findDiscoItemsByFeature(feature);
1046 if (items.size() >= 1) {
1047 return items.get(0);
1048 }
1049 return null;
1050 }
1051
1052 public void r() {
1053 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1054 }
1055
1056 public String getMucServer() {
1057 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1058 final Info value = cursor.getValue();
1059 if (value.features.contains("http://jabber.org/protocol/muc")
1060 && !value.features.contains("jabber:iq:gateway")
1061 && !value.identities.contains(new Pair<>("conference","irc"))) {
1062 return cursor.getKey().toString();
1063 }
1064 }
1065 return null;
1066 }
1067
1068 public int getTimeToNextAttempt() {
1069 final int interval = (int) (25 * Math.pow(1.5, attempt));
1070 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1071 return interval - secondsSinceLast;
1072 }
1073
1074 public int getAttempt() {
1075 return this.attempt;
1076 }
1077
1078 public Features getFeatures() {
1079 return this.features;
1080 }
1081
1082 public long getLastSessionEstablished() {
1083 final long diff;
1084 if (this.lastSessionStarted == 0) {
1085 diff = SystemClock.elapsedRealtime() - this.lastConnect;
1086 } else {
1087 diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1088 }
1089 return System.currentTimeMillis() - diff;
1090 }
1091
1092 public long getLastConnect() {
1093 return this.lastConnect;
1094 }
1095
1096 public long getLastPingSent() {
1097 return this.lastPingSent;
1098 }
1099
1100 public long getLastPacketReceived() {
1101 return this.lastPacketReceived;
1102 }
1103
1104 public void sendActive() {
1105 this.sendPacket(new ActivePacket());
1106 }
1107
1108 public void sendInactive() {
1109 this.sendPacket(new InactivePacket());
1110 }
1111
1112 public void resetAttemptCount() {
1113 this.attempt = 0;
1114 this.lastConnect = 0;
1115 }
1116
1117 private class Info {
1118 public final ArrayList<String> features = new ArrayList<>();
1119 public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1120 }
1121
1122 private class UnauthorizedException extends IOException {
1123
1124 }
1125
1126 private class SecurityException extends IOException {
1127
1128 }
1129
1130 private class IncompatibleServerException extends IOException {
1131
1132 }
1133
1134 public class Features {
1135 XmppConnection connection;
1136 private boolean carbonsEnabled = false;
1137 private boolean encryptionEnabled = false;
1138 private boolean blockListRequested = false;
1139
1140 public Features(final XmppConnection connection) {
1141 this.connection = connection;
1142 }
1143
1144 private boolean hasDiscoFeature(final Jid server, final String feature) {
1145 return connection.disco.containsKey(server) &&
1146 connection.disco.get(server).features.contains(feature);
1147 }
1148
1149 public boolean carbons() {
1150 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1151 }
1152
1153 public boolean blocking() {
1154 return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1155 }
1156
1157 public boolean register() {
1158 return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1159 }
1160
1161 public boolean sm() {
1162 return streamId != null
1163 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1164 }
1165
1166 public boolean csi() {
1167 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1168 }
1169
1170 public boolean pep() {
1171 final Pair<String,String> needle = new Pair<>("pubsub","pep");
1172 Info info = disco.get(account.getServer());
1173 if (info != null && info.identities.contains(needle)) {
1174 return true;
1175 } else {
1176 info = disco.get(account.getJid().toBareJid());
1177 return info != null && info.identities.contains(needle);
1178 }
1179 }
1180
1181 public boolean mam() {
1182 if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1183 return true;
1184 } else {
1185 return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1186 }
1187 }
1188
1189 public boolean advancedStreamFeaturesLoaded() {
1190 return disco.containsKey(account.getServer());
1191 }
1192
1193 public boolean rosterVersioning() {
1194 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1195 }
1196
1197 public void setBlockListRequested(boolean value) {
1198 this.blockListRequested = value;
1199 }
1200
1201 public boolean httpUpload() {
1202 return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1203 }
1204 }
1205
1206 private IqGenerator getIqGenerator() {
1207 return mXmppConnectionService.getIqGenerator();
1208 }
1209}