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