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