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