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