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