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