conversations-classic/src/eu/siacs/conversations/xmpp/XmppConnection.java

766 lines
24 KiB
Java
Raw Normal View History

2014-02-28 17:46:01 +00:00
package eu.siacs.conversations.xmpp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.Socket;
import java.net.UnknownHostException;
2014-03-06 19:03:35 +00:00
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
2014-03-07 13:24:33 +00:00
import java.security.MessageDigest;
2014-03-06 19:03:35 +00:00
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
2014-03-06 14:11:56 +00:00
import java.security.cert.CertPathValidatorException;
2014-03-06 19:03:35 +00:00
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
2014-03-15 03:59:18 +00:00
import java.util.ArrayList;
2014-02-09 13:10:52 +00:00
import java.util.HashSet;
import java.util.Hashtable;
2014-02-09 13:10:52 +00:00
import java.util.List;
2014-03-06 19:03:35 +00:00
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
2014-03-06 19:03:35 +00:00
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
2014-03-10 18:22:13 +00:00
import org.json.JSONException;
import org.xmlpull.v1.XmlPullParserException;
import android.os.Bundle;
import android.os.PowerManager;
2014-03-11 14:44:22 +00:00
import android.os.SystemClock;
import android.util.Log;
2014-02-28 17:46:01 +00:00
import eu.siacs.conversations.entities.Account;
2014-03-07 13:24:33 +00:00
import eu.siacs.conversations.utils.CryptoHelper;
2014-02-28 17:46:01 +00:00
import eu.siacs.conversations.utils.DNSHelper;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Tag;
import eu.siacs.conversations.xml.TagWriter;
import eu.siacs.conversations.xml.XmlReader;
2014-03-10 18:22:13 +00:00
import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
public class XmppConnection implements Runnable {
protected Account account;
private static final String LOGTAG = "xmppService";
private PowerManager.WakeLock wakeLock;
private SecureRandom random = new SecureRandom();
2014-02-09 13:10:52 +00:00
private Socket socket;
private XmlReader tagReader;
private TagWriter tagWriter;
private boolean shouldBind = true;
private boolean shouldAuthenticate = true;
private Element streamFeatures;
2014-02-09 13:10:52 +00:00
private HashSet<String> discoFeatures = new HashSet<String>();
2014-03-15 03:59:18 +00:00
private List<String> discoItems = new ArrayList<String>();
2014-03-10 18:22:13 +00:00
private String streamId = null;
private int stanzasReceived = 0;
private int stanzasSent = 0;
2014-03-11 14:44:22 +00:00
public long lastPaketReceived = 0;
public long lastPingSent = 0;
public long lastConnect = 0;
public long lastSessionStarted = 0;
2014-02-09 13:10:52 +00:00
private static final int PACKET_IQ = 0;
private static final int PACKET_MESSAGE = 1;
private static final int PACKET_PRESENCE = 2;
2014-02-09 13:10:52 +00:00
2014-03-03 04:01:02 +00:00
private Hashtable<String, PacketReceived> packetCallbacks = new Hashtable<String, PacketReceived>();
2014-02-01 14:07:20 +00:00
private OnPresencePacketReceived presenceListener = null;
private OnIqPacketReceived unregisteredIqListener = null;
private OnMessagePacketReceived messageListener = null;
private OnStatusChanged statusListener = null;
private OnTLSExceptionReceived tlsListener = null;
private OnBindListener bindListener = null;
public XmppConnection(Account account, PowerManager pm) {
this.account = account;
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"XmppConnection");
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
}
2014-03-06 14:11:56 +00:00
2014-03-06 02:57:29 +00:00
protected void changeStatus(int nextStatus) {
2014-03-11 15:27:33 +00:00
if (account.getStatus() != nextStatus) {
2014-03-13 16:29:22 +00:00
if ((nextStatus == Account.STATUS_OFFLINE)&&(account.getStatus() != Account.STATUS_CONNECTING)&&(account.getStatus() != Account.STATUS_ONLINE)) {
return;
}
2014-03-11 15:27:33 +00:00
account.setStatus(nextStatus);
if (statusListener != null) {
statusListener.onStatusChanged(account);
}
2014-03-06 02:57:29 +00:00
}
}
protected void connect() {
2014-03-11 15:27:33 +00:00
Log.d(LOGTAG,account.getJid()+ ": connecting");
lastConnect = SystemClock.elapsedRealtime();
try {
shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
packetCallbacks.clear();
2014-03-06 02:57:29 +00:00
this.changeStatus(Account.STATUS_CONNECTING);
Bundle namePort = DNSHelper.getSRVRecord(account.getServer());
String srvRecordServer = namePort.getString("name");
int srvRecordPort = namePort.getInt("port");
2014-02-09 13:10:52 +00:00
if (srvRecordServer != null) {
Log.d(LOGTAG, account.getJid() + ": using values from dns "
+ srvRecordServer + ":" + srvRecordPort);
socket = new Socket(srvRecordServer, srvRecordPort);
} else {
socket = new Socket(account.getServer(), 5222);
}
OutputStream out = socket.getOutputStream();
tagWriter.setOutputStream(out);
InputStream in = socket.getInputStream();
tagReader.setInputStream(in);
tagWriter.beginDocument();
sendStartStream();
Tag nextTag;
while ((nextTag = tagReader.readTag()) != null) {
if (nextTag.isStart("stream")) {
processStream(nextTag);
break;
} else {
Log.d(LOGTAG, "found unexpected tag: " + nextTag.getName());
return;
}
}
if (socket.isConnected()) {
socket.close();
}
} catch (UnknownHostException e) {
2014-03-06 02:57:29 +00:00
this.changeStatus(Account.STATUS_SERVER_NOT_FOUND);
if (wakeLock.isHeld()) {
wakeLock.release();
}
return;
} catch (IOException e) {
2014-03-07 13:24:33 +00:00
if (account.getStatus() != Account.STATUS_TLS_ERROR) {
this.changeStatus(Account.STATUS_OFFLINE);
}
if (wakeLock.isHeld()) {
wakeLock.release();
}
return;
} catch (XmlPullParserException e) {
2014-03-06 02:57:29 +00:00
this.changeStatus(Account.STATUS_OFFLINE);
2014-02-09 13:10:52 +00:00
Log.d(LOGTAG, "xml exception " + e.getMessage());
if (wakeLock.isHeld()) {
wakeLock.release();
}
return;
}
2014-02-09 13:10:52 +00:00
}
@Override
public void run() {
connect();
}
private void processStream(Tag currentTag) throws XmlPullParserException,
IOException {
Tag nextTag = tagReader.readTag();
while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
if (nextTag.isStart("error")) {
processStreamError(nextTag);
} else if (nextTag.isStart("features")) {
processStreamFeatures(nextTag);
2014-03-06 14:11:56 +00:00
if ((streamFeatures.getChildren().size() == 1)
&& (streamFeatures.hasChild("starttls"))
&& (!account.isOptionSet(Account.OPTION_USETLS))) {
changeStatus(Account.STATUS_SERVER_REQUIRES_TLS);
}
} else if (nextTag.isStart("proceed")) {
switchOverToTls(nextTag);
} else if (nextTag.isStart("success")) {
2014-02-09 13:10:52 +00:00
Log.d(LOGTAG, account.getJid()
2014-03-08 01:06:00 +00:00
+ ": logged in");
tagReader.readTag();
tagReader.reset();
sendStartStream();
processStream(tagReader.readTag());
break;
2014-02-09 13:10:52 +00:00
} else if (nextTag.isStart("failure")) {
tagReader.readElement(nextTag);
2014-03-06 14:11:56 +00:00
changeStatus(Account.STATUS_UNAUTHORIZED);
2014-03-10 18:22:13 +00:00
} else if (nextTag.isStart("enabled")) {
this.stanzasSent = 0;
Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) {
this.streamId = enabled.getAttribute("id");
Log.d(LOGTAG,account.getJid()+": stream managment enabled (resumable)");
} else {
Log.d(LOGTAG,account.getJid()+": stream managment enabled");
}
this.lastSessionStarted = SystemClock.elapsedRealtime();
2014-03-10 18:22:13 +00:00
this.stanzasReceived = 0;
RequestPacket r = new RequestPacket();
tagWriter.writeStanzaAsync(r);
} else if (nextTag.isStart("resumed")) {
tagReader.readElement(nextTag);
sendPing();
2014-03-10 18:22:13 +00:00
changeStatus(Account.STATUS_ONLINE);
Log.d(LOGTAG,account.getJid()+": session resumed");
} else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag);
AckPacket ack = new AckPacket(this.stanzasReceived);
//Log.d(LOGTAG,ack.toString());
tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) {
Element ack = tagReader.readElement(nextTag);
2014-03-11 14:44:22 +00:00
lastPaketReceived = SystemClock.elapsedRealtime();
2014-03-10 18:22:13 +00:00
int serverSequence = Integer.parseInt(ack.getAttribute("h"));
if (serverSequence>this.stanzasSent) {
this.stanzasSent = serverSequence;
}
//Log.d(LOGTAG,"server ack"+ack.toString()+" ("+this.stanzasSent+")");
} else if (nextTag.isStart("failed")) {
2014-03-12 13:55:23 +00:00
tagReader.readElement(nextTag);
Log.d(LOGTAG,account.getJid()+": resumption failed");
streamId = null;
if (account.getStatus() != Account.STATUS_ONLINE) {
sendBindRequest();
}
} else if (nextTag.isStart("iq")) {
2014-02-01 14:07:20 +00:00
processIq(nextTag);
} else if (nextTag.isStart("message")) {
2014-02-01 14:07:20 +00:00
processMessage(nextTag);
} else if (nextTag.isStart("presence")) {
2014-02-01 14:07:20 +00:00
processPresence(nextTag);
} else {
Log.d(LOGTAG, "found unexpected tag: " + nextTag.getName()
+ " as child of " + currentTag.getName());
}
nextTag = tagReader.readTag();
}
if (account.getStatus() == Account.STATUS_ONLINE) {
account.setStatus(Account.STATUS_OFFLINE);
2014-02-09 13:10:52 +00:00
if (statusListener != null) {
statusListener.onStatusChanged(account);
}
}
}
2014-02-09 13:10:52 +00:00
private Element processPacket(Tag currentTag, int packetType)
throws XmlPullParserException, IOException {
Element element;
switch (packetType) {
case PACKET_IQ:
element = new IqPacket();
break;
case PACKET_MESSAGE:
element = new MessagePacket();
break;
case PACKET_PRESENCE:
element = new PresencePacket();
break;
default:
return null;
}
element.setAttributes(currentTag.getAttributes());
Tag nextTag = tagReader.readTag();
2014-02-09 13:10:52 +00:00
while (!nextTag.isEnd(element.getName())) {
if (!nextTag.isNo()) {
Element child = tagReader.readElement(nextTag);
element.addChild(child);
}
nextTag = tagReader.readTag();
}
2014-03-10 18:22:13 +00:00
++stanzasReceived;
2014-03-11 14:44:22 +00:00
lastPaketReceived = SystemClock.elapsedRealtime();
return element;
}
2014-03-03 04:01:02 +00:00
private void processIq(Tag currentTag) throws XmlPullParserException,
2014-02-09 13:10:52 +00:00
IOException {
IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
2014-03-03 04:01:02 +00:00
if (packetCallbacks.containsKey(packet.getId())) {
if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) {
2014-03-06 14:11:56 +00:00
((OnIqPacketReceived) packetCallbacks.get(packet.getId()))
.onIqPacketReceived(account, packet);
2014-03-03 04:01:02 +00:00
}
2014-03-06 14:11:56 +00:00
2014-03-03 04:01:02 +00:00
packetCallbacks.remove(packet.getId());
2014-02-01 14:07:20 +00:00
} else if (this.unregisteredIqListener != null) {
2014-02-09 13:10:52 +00:00
this.unregisteredIqListener.onIqPacketReceived(account, packet);
}
}
2014-02-09 13:10:52 +00:00
private void processMessage(Tag currentTag) throws XmlPullParserException,
IOException {
MessagePacket packet = (MessagePacket) processPacket(currentTag,
PACKET_MESSAGE);
2014-03-03 04:01:02 +00:00
String id = packet.getAttribute("id");
2014-03-06 14:11:56 +00:00
if ((id != null) && (packetCallbacks.containsKey(id))) {
2014-03-03 04:01:02 +00:00
if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) {
2014-03-06 14:11:56 +00:00
((OnMessagePacketReceived) packetCallbacks.get(id))
.onMessagePacketReceived(account, packet);
2014-03-03 04:01:02 +00:00
}
packetCallbacks.remove(id);
} else if (this.messageListener != null) {
2014-02-09 13:10:52 +00:00
this.messageListener.onMessagePacketReceived(account, packet);
2014-02-01 14:07:20 +00:00
}
}
2014-02-09 13:10:52 +00:00
private void processPresence(Tag currentTag) throws XmlPullParserException,
IOException {
PresencePacket packet = (PresencePacket) processPacket(currentTag,
PACKET_PRESENCE);
2014-03-03 04:01:02 +00:00
String id = packet.getAttribute("id");
2014-03-06 14:11:56 +00:00
if ((id != null) && (packetCallbacks.containsKey(id))) {
2014-03-03 04:01:02 +00:00
if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) {
2014-03-06 14:11:56 +00:00
((OnPresencePacketReceived) packetCallbacks.get(id))
.onPresencePacketReceived(account, packet);
2014-03-03 04:01:02 +00:00
}
packetCallbacks.remove(id);
} else if (this.presenceListener != null) {
2014-02-09 13:10:52 +00:00
this.presenceListener.onPresencePacketReceived(account, packet);
2014-02-01 14:07:20 +00:00
}
}
2014-03-10 18:22:13 +00:00
private void sendStartTLS() throws IOException {
Tag startTLS = Tag.empty("starttls");
startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
tagWriter.writeTag(startTLS);
}
private void switchOverToTls(Tag currentTag) throws XmlPullParserException,
IOException {
Tag nextTag = tagReader.readTag(); // should be proceed end tag
try {
2014-03-06 19:03:35 +00:00
SSLContext sc = SSLContext.getInstance("TLS");
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// Initialise the TMF as you normally would, for example:
// tmf.in
try {
tmf.init((KeyStore) null);
} catch (KeyStoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
TrustManager[] trustManagers = tmf.getTrustManagers();
final X509TrustManager origTrustmanager = (X509TrustManager) trustManagers[0];
TrustManager[] wrappedTrustManagers = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
origTrustmanager.checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
try {
origTrustmanager.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
2014-03-07 13:24:33 +00:00
if (e.getCause() instanceof CertPathValidatorException) {
String sha;
try {
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
sha1.update(chain[0].getEncoded());
sha = CryptoHelper.bytesToHex(sha1.digest());
if (!sha.equals(account.getSSLFingerprint())) {
changeStatus(Account.STATUS_TLS_ERROR);
if (tlsListener!=null) {
tlsListener.onTLSExceptionReceived(sha,account);
}
throw new CertificateException();
}
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
throw new CertificateException();
}
2014-03-06 19:03:35 +00:00
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return origTrustmanager.getAcceptedIssuers();
}
} };
sc.init(null, wrappedTrustManagers, null);
SSLSocketFactory factory = sc.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
2014-03-07 13:24:33 +00:00
socket.getInetAddress().getHostAddress(), socket.getPort(),
true);
tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream();
2014-03-08 01:06:00 +00:00
Log.d(LOGTAG,account.getJid()+": TLS connection established");
processStream(tagReader.readTag());
sslSocket.close();
2014-03-06 19:03:35 +00:00
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void sendSaslAuth() throws IOException, XmlPullParserException {
2014-03-09 11:58:29 +00:00
String saslString = CryptoHelper.saslPlain(account.getUsername(),
account.getPassword());
Element auth = new Element("auth");
auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
auth.setAttribute("mechanism", "PLAIN");
auth.setContent(saslString);
tagWriter.writeElement(auth);
}
private void processStreamFeatures(Tag currentTag)
throws XmlPullParserException, IOException {
this.streamFeatures = tagReader.readElement(currentTag);
2014-02-09 13:10:52 +00:00
if (this.streamFeatures.hasChild("starttls")
&& account.isOptionSet(Account.OPTION_USETLS)) {
sendStartTLS();
2014-03-13 16:29:22 +00:00
} else if (this.streamFeatures.hasChild("register")&&(account.isOptionSet(Account.OPTION_REGISTER))) {
sendRegistryRequest();
} else if (!this.streamFeatures.hasChild("register")&&(account.isOptionSet(Account.OPTION_REGISTER))) {
changeStatus(Account.STATUS_REGISTRATION_NOT_SUPPORTED);
disconnect(true);
2014-02-09 13:10:52 +00:00
} else if (this.streamFeatures.hasChild("mechanisms")
&& shouldAuthenticate) {
sendSaslAuth();
2014-03-10 18:22:13 +00:00
} else if (this.streamFeatures.hasChild("sm") && streamId != null) {
Log.d(LOGTAG,"found old stream id. trying to remuse");
ResumePacket resume = new ResumePacket(this.streamId,stanzasReceived);
this.tagWriter.writeStanzaAsync(resume);
} else if (this.streamFeatures.hasChild("bind") && shouldBind) {
sendBindRequest();
if (this.streamFeatures.hasChild("session")) {
2014-03-10 18:22:13 +00:00
Log.d(LOGTAG,"sending session");
IqPacket startSession = new IqPacket(IqPacket.TYPE_SET);
2014-03-20 14:49:53 +00:00
startSession.addChild("session","urn:ietf:params:xml:ns:xmpp-session"); //setContent("")
2014-03-10 18:22:13 +00:00
this.sendIqPacket(startSession, null);
}
2014-03-10 18:22:13 +00:00
}
}
2014-02-09 13:10:52 +00:00
private void sendRegistryRequest() {
IqPacket register = new IqPacket(IqPacket.TYPE_GET);
register.query("jabber:iq:register");
register.setTo(account.getServer());
sendIqPacket(register, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
Element instructions = packet.query().findChild("instructions");
if (packet.query().hasChild("username")&&(packet.query().hasChild("password"))) {
IqPacket register = new IqPacket(IqPacket.TYPE_SET);
Element username = new Element("username").setContent(account.getUsername());
Element password = new Element("password").setContent(account.getPassword());
2014-03-20 14:49:53 +00:00
register.query("jabber:iq:register").addChild(username);
register.query().addChild(password);
sendIqPacket(register, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType()==IqPacket.TYPE_RESULT) {
account.setOption(Account.OPTION_REGISTER, false);
changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
} else if (packet.hasChild("error")&&(packet.findChild("error").hasChild("conflict"))){
changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
} else {
changeStatus(Account.STATUS_REGISTRATION_FAILED);
Log.d(LOGTAG,packet.toString());
}
disconnect(true);
}
});
} else {
changeStatus(Account.STATUS_REGISTRATION_FAILED);
disconnect(true);
Log.d(LOGTAG,account.getJid()+": could not register. instructions are"+instructions.getContent());
}
}
});
}
2014-03-10 18:22:13 +00:00
private void sendInitialPresence() {
PresencePacket packet = new PresencePacket();
packet.setAttribute("from", account.getFullJid());
if (account.getKeys().has("pgp_signature")) {
try {
2014-03-20 14:49:53 +00:00
String signature = account.getKeys().getString("pgp_signature");
packet.addChild("status").setContent("online");
packet.addChild("x","jabber:x:signed").setContent(signature);
2014-03-10 18:22:13 +00:00
} catch (JSONException e) {
//
}
}
2014-03-10 18:22:13 +00:00
this.sendPresencePacket(packet);
}
private void sendBindRequest() throws IOException {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
2014-03-20 14:49:53 +00:00
iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind").addChild("resource").setContent("Conversations");
2014-02-09 13:10:52 +00:00
this.sendIqPacket(iq, new OnIqPacketReceived() {
@Override
2014-02-01 14:07:20 +00:00
public void onIqPacketReceived(Account account, IqPacket packet) {
2014-02-09 13:10:52 +00:00
String resource = packet.findChild("bind").findChild("jid")
.getContent().split("/")[1];
account.setResource(resource);
2014-03-10 18:22:13 +00:00
if (streamFeatures.hasChild("sm")) {
EnablePacket enable = new EnablePacket();
tagWriter.writeStanzaAsync(enable);
}
sendInitialPresence();
2014-03-15 03:59:18 +00:00
sendServiceDiscoveryInfo();
sendServiceDiscoveryItems();
if (bindListener !=null) {
bindListener.onBind(account);
}
changeStatus(Account.STATUS_ONLINE);
2014-02-09 13:10:52 +00:00
}
});
}
2014-03-15 03:59:18 +00:00
private void sendServiceDiscoveryInfo() {
2014-02-09 13:10:52 +00:00
IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
2014-03-15 03:59:18 +00:00
iq.setTo(account.getServer());
iq.query("http://jabber.org/protocol/disco#info");
2014-02-09 13:10:52 +00:00
this.sendIqPacket(iq, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
2014-03-15 03:59:18 +00:00
List<Element> elements = packet.query().getChildren();
2014-02-09 13:10:52 +00:00
for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("feature")) {
discoFeatures.add(elements.get(i).getAttribute(
"var"));
}
}
if (discoFeatures.contains("urn:xmpp:carbons:2")) {
sendEnableCarbons();
}
}
});
}
2014-03-15 03:59:18 +00:00
private void sendServiceDiscoveryItems() {
IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
iq.setTo(account.getServer());
iq.query("http://jabber.org/protocol/disco#items");
this.sendIqPacket(iq, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
List<Element> elements = packet.query().getChildren();
for (int i = 0; i < elements.size(); ++i) {
if (elements.get(i).getName().equals("item")) {
discoItems.add(elements.get(i).getAttribute(
"jid"));
}
}
}
});
}
2014-03-06 14:11:56 +00:00
2014-02-09 13:10:52 +00:00
private void sendEnableCarbons() {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
2014-03-20 14:49:53 +00:00
iq.addChild("enable","urn:xmpp:carbons:2");
2014-02-09 13:10:52 +00:00
this.sendIqPacket(iq, new OnIqPacketReceived() {
2014-03-06 14:11:56 +00:00
2014-02-09 13:10:52 +00:00
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (!packet.hasChild("error")) {
2014-03-06 14:11:56 +00:00
Log.d(LOGTAG, account.getJid()
+ ": successfully enabled carbons");
2014-02-09 13:10:52 +00:00
} else {
2014-03-06 14:11:56 +00:00
Log.d(LOGTAG, account.getJid()
+ ": error enableing carbons " + packet.toString());
2014-02-09 13:10:52 +00:00
}
}
});
}
private void processStreamError(Tag currentTag) {
Log.d(LOGTAG, "processStreamError");
}
2014-03-10 18:22:13 +00:00
private void sendStartStream() throws IOException {
Tag stream = Tag.start("stream:stream");
stream.setAttribute("from", account.getJid());
stream.setAttribute("to", account.getServer());
stream.setAttribute("version", "1.0");
stream.setAttribute("xml:lang", "en");
stream.setAttribute("xmlns", "jabber:client");
stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
tagWriter.writeTag(stream);
}
private String nextRandomId() {
return new BigInteger(50, random).toString(32);
}
2014-02-09 13:10:52 +00:00
public void sendIqPacket(IqPacket packet, OnIqPacketReceived callback) {
String id = nextRandomId();
2014-02-09 13:10:52 +00:00
packet.setAttribute("id", id);
2014-03-10 18:22:13 +00:00
this.sendPacket(packet, callback);
}
2014-02-09 13:10:52 +00:00
public void sendMessagePacket(MessagePacket packet) {
2014-03-10 18:22:13 +00:00
this.sendPacket(packet, null);
2014-03-03 04:01:02 +00:00
}
2014-03-06 14:11:56 +00:00
public void sendMessagePacket(MessagePacket packet,
OnMessagePacketReceived callback) {
2014-03-10 18:22:13 +00:00
this.sendPacket(packet, callback);
2014-02-01 14:07:20 +00:00
}
2014-02-09 13:10:52 +00:00
public void sendPresencePacket(PresencePacket packet) {
2014-03-10 18:22:13 +00:00
this.sendPacket(packet, null);
2014-03-03 04:01:02 +00:00
}
2014-03-06 14:11:56 +00:00
2014-03-10 18:22:13 +00:00
public void sendPresencePacket(PresencePacket packet,
2014-03-06 14:11:56 +00:00
OnPresencePacketReceived callback) {
2014-03-10 18:22:13 +00:00
this.sendPacket(packet, callback);
}
private synchronized void sendPacket(final AbstractStanza packet, PacketReceived callback) {
2014-03-11 14:44:22 +00:00
// TODO dont increment stanza count if packet = request packet or ack;
2014-03-10 18:22:13 +00:00
++stanzasSent;
tagWriter.writeStanzaAsync(packet);
2014-03-03 04:01:02 +00:00
if (callback != null) {
2014-03-10 18:22:13 +00:00
if (packet.getId()==null) {
packet.setId(nextRandomId());
}
packetCallbacks.put(packet.getId(), callback);
2014-03-03 04:01:02 +00:00
}
2014-02-01 14:07:20 +00:00
}
2014-03-11 14:44:22 +00:00
public void sendPing() {
if (streamFeatures.hasChild("sm")) {
tagWriter.writeStanzaAsync(new RequestPacket());
} else {
IqPacket iq = new IqPacket(IqPacket.TYPE_GET);
2014-03-20 14:49:53 +00:00
iq.setFrom(account.getFullJid());
iq.addChild("ping","urn:xmpp:ping");
2014-03-11 14:44:22 +00:00
this.sendIqPacket(iq, null);
}
}
2014-02-09 13:10:52 +00:00
public void setOnMessagePacketReceivedListener(
OnMessagePacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.messageListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnUnregisteredIqPacketReceivedListener(
OnIqPacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.unregisteredIqListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnPresencePacketReceivedListener(
OnPresencePacketReceived listener) {
2014-02-01 14:07:20 +00:00
this.presenceListener = listener;
}
2014-02-09 13:10:52 +00:00
public void setOnStatusChangedListener(OnStatusChanged listener) {
this.statusListener = listener;
}
2014-03-07 13:24:33 +00:00
public void setOnTLSExceptionReceivedListener(OnTLSExceptionReceived listener) {
this.tlsListener = listener;
}
public void setOnBindListener(OnBindListener listener) {
this.bindListener = listener;
}
2014-03-10 18:22:13 +00:00
public void disconnect(boolean force) {
2014-03-13 16:29:22 +00:00
changeStatus(Account.STATUS_OFFLINE);
2014-03-10 18:22:13 +00:00
Log.d(LOGTAG,"disconnecting");
try {
if (force) {
socket.close();
return;
2014-03-10 18:22:13 +00:00
}
tagWriter.finish();
while(!tagWriter.finished()) {
//Log.d(LOGTAG,"not yet finished");
2014-03-10 18:22:13 +00:00
Thread.sleep(100);
}
2014-02-13 22:40:08 +00:00
tagWriter.writeTag(Tag.end("stream:stream"));
2014-03-10 18:22:13 +00:00
} catch (IOException e) {
Log.d(LOGTAG,"io exception during disconnect");
} catch (InterruptedException e) {
Log.d(LOGTAG,"interupted while waiting for disconnect");
}
}
2014-03-08 01:06:00 +00:00
public boolean hasFeatureRosterManagment() {
if (this.streamFeatures==null) {
return false;
} else {
return this.streamFeatures.hasChild("ver");
}
}
2014-03-13 16:29:22 +00:00
public boolean hasFeatureStreamManagment() {
if (this.streamFeatures==null) {
return false;
} else {
2014-03-13 20:37:27 +00:00
return this.streamFeatures.hasChild("sm");
2014-03-13 16:29:22 +00:00
}
}
public boolean hasFeaturesCarbon() {
return discoFeatures.contains("urn:xmpp:carbons:2");
}
2014-03-10 18:22:13 +00:00
public void r() {
this.tagWriter.writeStanzaAsync(new RequestPacket());
}
public int getReceivedStanzas() {
return this.stanzasReceived;
}
public int getSentStanzas() {
return this.stanzasSent;
}
2014-03-15 03:59:18 +00:00
public String getMucServer() {
for(int i = 0; i < discoItems.size(); ++i) {
if (discoItems.get(i).contains("conference.")) {
return discoItems.get(i);
} else if (discoItems.get(i).contains("conf.")) {
return discoItems.get(i);
} else if (discoItems.get(i).contains("muc.")) {
return discoItems.get(i);
}
}
return null;
}
}