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 tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
419 .getOutputStream()));
420 tagReader
421 .setInputStream(new ZLibInputStream(tagReader.getInputStream()));
422
423 sendStartStream();
424 Log.d(LOGTAG, account.getJid() + ": compression enabled");
425 processStream(tagReader.readTag());
426 }
427
428 private void sendStartTLS() throws IOException {
429 Tag startTLS = Tag.empty("starttls");
430 startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
431 tagWriter.writeTag(startTLS);
432 }
433
434 private void switchOverToTls(Tag currentTag) throws XmlPullParserException,
435 IOException {
436 tagReader.readTag();
437 try {
438 SSLContext sc = SSLContext.getInstance("TLS");
439 sc.init(null, new X509TrustManager[] { this.mMemorizingTrustManager }, mRandom);
440 SSLSocketFactory factory = sc.getSocketFactory();
441
442 HostnameVerifier verifier = this.mMemorizingTrustManager.wrapHostnameVerifier(new org.apache.http.conn.ssl.StrictHostnameVerifier());
443 SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
444 socket.getInetAddress().getHostAddress(), socket.getPort(),
445 true);
446
447 if (verifier != null && !verifier.verify(account.getServer(), sslSocket.getSession())) {
448 Log.d(LOGTAG, account.getJid() + ": host mismatch in TLS connection");
449 sslSocket.close();
450 throw new IOException();
451 }
452 tagReader.setInputStream(sslSocket.getInputStream());
453 tagWriter.setOutputStream(sslSocket.getOutputStream());
454 sendStartStream();
455 Log.d(LOGTAG, account.getJid() + ": TLS connection established");
456 processStream(tagReader.readTag());
457 sslSocket.close();
458 } catch (NoSuchAlgorithmException e1) {
459 e1.printStackTrace();
460 } catch (KeyManagementException e) {
461 e.printStackTrace();
462 }
463 }
464
465 private void sendSaslAuthPlain() throws IOException {
466 String saslString = CryptoHelper.saslPlain(account.getUsername(),
467 account.getPassword());
468 Element auth = new Element("auth");
469 auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
470 auth.setAttribute("mechanism", "PLAIN");
471 auth.setContent(saslString);
472 tagWriter.writeElement(auth);
473 }
474
475 private void sendSaslAuthDigestMd5() throws IOException {
476 Element auth = new Element("auth");
477 auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
478 auth.setAttribute("mechanism", "DIGEST-MD5");
479 tagWriter.writeElement(auth);
480 }
481
482 private void processStreamFeatures(Tag currentTag)
483 throws XmlPullParserException, IOException {
484 this.streamFeatures = tagReader.readElement(currentTag);
485 if (this.streamFeatures.hasChild("starttls")
486 && account.isOptionSet(Account.OPTION_USETLS)) {
487 sendStartTLS();
488 } else if (compressionAvailable()) {
489 sendCompressionZlib();
490 } else if (this.streamFeatures.hasChild("register")
491 && (account.isOptionSet(Account.OPTION_REGISTER))) {
492 sendRegistryRequest();
493 } else if (!this.streamFeatures.hasChild("register")
494 && (account.isOptionSet(Account.OPTION_REGISTER))) {
495 changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
496 disconnect(true);
497 } else if (this.streamFeatures.hasChild("mechanisms")
498 && shouldAuthenticate) {
499 List<String> mechanisms = extractMechanisms(streamFeatures
500 .findChild("mechanisms"));
501 if (mechanisms.contains("PLAIN")) {
502 sendSaslAuthPlain();
503 } else if (mechanisms.contains("DIGEST-MD5")) {
504 sendSaslAuthDigestMd5();
505 }
506 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
507 + smVersion)
508 && streamId != null) {
509 ResumePacket resume = new ResumePacket(this.streamId,
510 stanzasReceived, smVersion);
511 this.tagWriter.writeStanzaAsync(resume);
512 } else if (this.streamFeatures.hasChild("bind") && shouldBind) {
513 sendBindRequest();
514 }
515 }
516
517 private boolean compressionAvailable() {
518 if (!this.streamFeatures.hasChild("compression",
519 "http://jabber.org/features/compress"))
520 return false;
521 if (!ZLibOutputStream.SUPPORTED)
522 return false;
523 if (!account.isOptionSet(Account.OPTION_USECOMPRESSION))
524 return false;
525
526 Element compression = this.streamFeatures.findChild("compression",
527 "http://jabber.org/features/compress");
528 for (Element child : compression.getChildren()) {
529 if (!"method".equals(child.getName()))
530 continue;
531
532 if ("zlib".equalsIgnoreCase(child.getContent())) {
533 return true;
534 }
535 }
536 return false;
537 }
538
539 private List<String> extractMechanisms(Element stream) {
540 ArrayList<String> mechanisms = new ArrayList<String>(stream
541 .getChildren().size());
542 for (Element child : stream.getChildren()) {
543 mechanisms.add(child.getContent());
544 }
545 return mechanisms;
546 }
547
548 private void sendRegistryRequest() {
549 IqPacket register = new IqPacket(IqPacket.TYPE_GET);
550 register.query("jabber:iq:register");
551 register.setTo(account.getServer());
552 sendIqPacket(register, new OnIqPacketReceived() {
553
554 @Override
555 public void onIqPacketReceived(Account account, IqPacket packet) {
556 Element instructions = packet.query().findChild("instructions");
557 if (packet.query().hasChild("username")
558 && (packet.query().hasChild("password"))) {
559 IqPacket register = new IqPacket(IqPacket.TYPE_SET);
560 Element username = new Element("username")
561 .setContent(account.getUsername());
562 Element password = new Element("password")
563 .setContent(account.getPassword());
564 register.query("jabber:iq:register").addChild(username);
565 register.query().addChild(password);
566 sendIqPacket(register, new OnIqPacketReceived() {
567
568 @Override
569 public void onIqPacketReceived(Account account,
570 IqPacket packet) {
571 if (packet.getType() == IqPacket.TYPE_RESULT) {
572 account.setOption(Account.OPTION_REGISTER,
573 false);
574 changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
575 } else if (packet.hasChild("error")
576 && (packet.findChild("error")
577 .hasChild("conflict"))) {
578 changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
579 } else {
580 changeStatus(Account.STATUS_REGISTRATION_FAILED);
581 Log.d(LOGTAG, packet.toString());
582 }
583 disconnect(true);
584 }
585 });
586 } else {
587 changeStatus(Account.STATUS_REGISTRATION_FAILED);
588 disconnect(true);
589 Log.d(LOGTAG, account.getJid()
590 + ": could not register. instructions are"
591 + instructions.getContent());
592 }
593 }
594 });
595 }
596
597 private void sendBindRequest() throws IOException {
598 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
599 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
600 .addChild("resource").setContent(account.getResource());
601 this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
602 @Override
603 public void onIqPacketReceived(Account account, IqPacket packet) {
604 Element bind = packet.findChild("bind");
605 if (bind!=null) {
606 Element jid = bind.findChild("jid");
607 if (jid!=null) {
608 account.setResource(jid.getContent().split("/")[1]);
609 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
610 smVersion = 3;
611 EnablePacket enable = new EnablePacket(smVersion);
612 tagWriter.writeStanzaAsync(enable);
613 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
614 smVersion = 2;
615 EnablePacket enable = new EnablePacket(smVersion);
616 tagWriter.writeStanzaAsync(enable);
617 }
618 sendServiceDiscoveryInfo(account.getServer());
619 sendServiceDiscoveryItems(account.getServer());
620 if (bindListener != null) {
621 bindListener.onBind(account);
622 }
623 changeStatus(Account.STATUS_ONLINE);
624 } else {
625 disconnect(true);
626 }
627 } else {
628 disconnect(true);
629 }
630 }
631 });
632 if (this.streamFeatures.hasChild("session")) {
633 Log.d(LOGTAG, account.getJid() + ": sending deprecated session");
634 IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
635 startSession.addChild("session",
636 "urn:ietf:params:xml:ns:xmpp-session");
637 this.sendUnboundIqPacket(startSession, null);
638 }
639 }
640
641 private void sendServiceDiscoveryInfo(final String server) {
642 IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
643 iq.setTo(server);
644 iq.query("http://jabber.org/protocol/disco#info");
645 this.sendIqPacket(iq, new OnIqPacketReceived() {
646
647 @Override
648 public void onIqPacketReceived(Account account, IqPacket packet) {
649 List<Element> elements = packet.query().getChildren();
650 List<String> features = new ArrayList<String>();
651 for (int i = 0; i < elements.size(); ++i) {
652 if (elements.get(i).getName().equals("feature")) {
653 features.add(elements.get(i).getAttribute("var"));
654 }
655 }
656 disco.put(server, features);
657
658 if (account.getServer().equals(server)) {
659 enableAdvancedStreamFeatures();
660 }
661 }
662 });
663 }
664
665 private void enableAdvancedStreamFeatures() {
666 if (getFeatures().carbons()) {
667 sendEnableCarbons();
668 }
669 }
670
671 private void sendServiceDiscoveryItems(final String server) {
672 IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
673 iq.setTo(server);
674 iq.query("http://jabber.org/protocol/disco#items");
675 this.sendIqPacket(iq, new OnIqPacketReceived() {
676
677 @Override
678 public void onIqPacketReceived(Account account, IqPacket packet) {
679 List<Element> elements = packet.query().getChildren();
680 for (int i = 0; i < elements.size(); ++i) {
681 if (elements.get(i).getName().equals("item")) {
682 String jid = elements.get(i).getAttribute("jid");
683 sendServiceDiscoveryInfo(jid);
684 }
685 }
686 }
687 });
688 }
689
690 private void sendEnableCarbons() {
691 IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
692 iq.addChild("enable", "urn:xmpp:carbons:2");
693 this.sendIqPacket(iq, new OnIqPacketReceived() {
694
695 @Override
696 public void onIqPacketReceived(Account account, IqPacket packet) {
697 if (!packet.hasChild("error")) {
698 Log.d(LOGTAG, account.getJid()
699 + ": successfully enabled carbons");
700 } else {
701 Log.d(LOGTAG, account.getJid()
702 + ": error enableing carbons " + packet.toString());
703 }
704 }
705 });
706 }
707
708 private void processStreamError(Tag currentTag) {
709 Log.d(LOGTAG, "processStreamError");
710 }
711
712 private void sendStartStream() throws IOException {
713 Tag stream = Tag.start("stream:stream");
714 stream.setAttribute("from", account.getJid());
715 stream.setAttribute("to", account.getServer());
716 stream.setAttribute("version", "1.0");
717 stream.setAttribute("xml:lang", "en");
718 stream.setAttribute("xmlns", "jabber:client");
719 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
720 tagWriter.writeTag(stream);
721 }
722
723 private String nextRandomId() {
724 return new BigInteger(50, mRandom).toString(32);
725 }
726
727 public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
728 if (packet.getId() == null) {
729 String id = nextRandomId();
730 packet.setAttribute("id", id);
731 }
732 packet.setFrom(account.getFullJid());
733 this.sendPacket(packet, callback);
734 }
735
736 public void sendUnboundIqPacket(IqPacket packet, OnIqPacketReceived callback) {
737 if (packet.getId() == null) {
738 String id = nextRandomId();
739 packet.setAttribute("id", id);
740 }
741 this.sendPacket(packet, callback);
742 }
743
744 public void sendMessagePacket(MessagePacket packet) {
745 this.sendPacket(packet, null);
746 }
747
748 public void sendPresencePacket(PresencePacket packet) {
749 this.sendPacket(packet, null);
750 }
751
752 private synchronized void sendPacket(final AbstractStanza packet,
753 PacketReceived callback) {
754 // TODO dont increment stanza count if packet = request packet or ack;
755 ++stanzasSent;
756 tagWriter.writeStanzaAsync(packet);
757 if (callback != null) {
758 if (packet.getId() == null) {
759 packet.setId(nextRandomId());
760 }
761 packetCallbacks.put(packet.getId(), callback);
762 }
763 }
764
765 public void sendPing() {
766 if (streamFeatures.hasChild("sm")) {
767 tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
768 } else {
769 IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
770 iq.setFrom(account.getFullJid());
771 iq.addChild("ping", "urn:xmpp:ping");
772 this.sendIqPacket(iq, null);
773 }
774 }
775
776 public void setOnMessagePacketReceivedListener(
777 OnMessagePacketReceived listener) {
778 this.messageListener = listener;
779 }
780
781 public void setOnUnregisteredIqPacketReceivedListener(
782 OnIqPacketReceived listener) {
783 this.unregisteredIqListener = listener;
784 }
785
786 public void setOnPresencePacketReceivedListener(
787 OnPresencePacketReceived listener) {
788 this.presenceListener = listener;
789 }
790
791 public void setOnJinglePacketReceivedListener(
792 OnJinglePacketReceived listener) {
793 this.jingleListener = listener;
794 }
795
796 public void setOnStatusChangedListener(OnStatusChanged listener) {
797 this.statusListener = listener;
798 }
799
800 public void setOnBindListener(OnBindListener listener) {
801 this.bindListener = listener;
802 }
803
804 public void disconnect(boolean force) {
805 changeStatus(Account.STATUS_OFFLINE);
806 Log.d(LOGTAG, "disconnecting");
807 try {
808 if (force) {
809 socket.close();
810 return;
811 }
812 new Thread(new Runnable() {
813
814 @Override
815 public void run() {
816 if (tagWriter.isActive()) {
817 tagWriter.finish();
818 try {
819 while (!tagWriter.finished()) {
820 Log.d(LOGTAG, "not yet finished");
821 Thread.sleep(100);
822 }
823 tagWriter.writeTag(Tag.end("stream:stream"));
824 } catch (IOException e) {
825 Log.d(LOGTAG, "io exception during disconnect");
826 } catch (InterruptedException e) {
827 Log.d(LOGTAG, "interrupted");
828 }
829 }
830 }
831 }).start();
832 } catch (IOException e) {
833 Log.d(LOGTAG, "io exception during disconnect");
834 }
835 }
836
837 public List<String> findDiscoItemsByFeature(String feature) {
838 List<String> items = new ArrayList<String>();
839 for (Entry<String, List<String>> cursor : disco.entrySet()) {
840 if (cursor.getValue().contains(feature)) {
841 items.add(cursor.getKey());
842 }
843 }
844 return items;
845 }
846
847 public String findDiscoItemByFeature(String feature) {
848 List<String> items = findDiscoItemsByFeature(feature);
849 if (items.size()>=1) {
850 return items.get(0);
851 }
852 return null;
853 }
854
855 public void r() {
856 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
857 }
858
859 public int getReceivedStanzas() {
860 return this.stanzasReceived;
861 }
862
863 public int getSentStanzas() {
864 return this.stanzasSent;
865 }
866
867 public String getMucServer() {
868 return findDiscoItemByFeature("http://jabber.org/protocol/muc");
869 }
870
871 public int getTimeToNextAttempt() {
872 int interval = (int) (25 * Math.pow(1.5, attempt));
873 int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
874 return interval - secondsSinceLast;
875 }
876
877 public int getAttempt() {
878 return this.attempt;
879 }
880
881 public Features getFeatures() {
882 return this.features;
883 }
884
885 public class Features {
886 XmppConnection connection;
887 public Features(XmppConnection connection) {
888 this.connection = connection;
889 }
890
891 private boolean hasDiscoFeature(String server, String feature) {
892 if (!connection.disco.containsKey(server)) {
893 return false;
894 }
895 return connection.disco.get(server).contains(feature);
896 }
897
898 public boolean carbons() {
899 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
900 }
901
902 public boolean sm() {
903 if (connection.streamFeatures == null) {
904 return false;
905 } else {
906 return connection.streamFeatures.hasChild("sm");
907 }
908 }
909
910 public boolean pubsub() {
911 return hasDiscoFeature(account.getServer(), "http://jabber.org/protocol/pubsub#publish");
912 }
913
914 public boolean rosterVersioning() {
915 if (connection.streamFeatures == null) {
916 return false;
917 } else {
918 return connection.streamFeatures.hasChild("ver");
919 }
920 }
921 }
922}