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