Conversations/src/main/java/eu/siacs/conversations/xmpp/XmppConnection.java

1512 lines
52 KiB
Java
Raw Normal View History

2014-02-28 12:46:01 -05:00
package eu.siacs.conversations.xmpp;
2015-10-11 07:11:50 -04:00
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
2014-11-03 04:03:45 -05:00
import android.os.Bundle;
import android.os.Parcelable;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.security.KeyChain;
2015-10-11 07:11:50 -04:00
import android.util.Base64;
2014-11-03 04:03:45 -05:00
import android.util.Log;
import android.util.Pair;
2014-11-03 04:03:45 -05:00
import android.util.SparseArray;
2014-11-15 09:42:40 -05:00
import org.json.JSONException;
import org.json.JSONObject;
2014-11-03 04:03:45 -05:00
import org.xmlpull.v1.XmlPullParserException;
2015-10-11 07:11:50 -04:00
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.ConnectException;
2014-11-07 23:08:31 -05:00
import java.net.IDN;
import java.net.InetAddress;
2014-10-27 16:48:25 -04:00
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
2015-10-11 07:11:50 -04:00
import java.net.URL;
2014-03-06 14:03:35 -05:00
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
2014-03-14 23:59:18 -04:00
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
2015-08-06 08:54:37 -04:00
import java.util.Iterator;
2014-02-09 08:10:52 -05:00
import java.util.List;
import java.util.Map.Entry;
2014-07-22 11:27:44 -04:00
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
2014-03-06 14:03:35 -05:00
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509KeyManager;
2014-03-06 14:03:35 -05:00
import javax.net.ssl.X509TrustManager;
import de.duenndns.ssl.MemorizingTrustManager;
2014-08-31 10:28:21 -04:00
import eu.siacs.conversations.Config;
import eu.siacs.conversations.crypto.XmppDomainVerifier;
2014-11-12 10:15:38 -05:00
import eu.siacs.conversations.crypto.sasl.DigestMd5;
import eu.siacs.conversations.crypto.sasl.External;
2014-11-12 10:15:38 -05:00
import eu.siacs.conversations.crypto.sasl.Plain;
import eu.siacs.conversations.crypto.sasl.SaslMechanism;
import eu.siacs.conversations.crypto.sasl.ScramSha1;
2014-02-28 12:46:01 -05:00
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.generator.IqGenerator;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
2014-02-28 12:46:01 -05:00
import eu.siacs.conversations.utils.DNSHelper;
import eu.siacs.conversations.utils.SSLSocketHelper;
import eu.siacs.conversations.utils.SocksSocketFactory;
import eu.siacs.conversations.utils.Xmlns;
2014-02-28 12:46:01 -05:00
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xml.Tag;
import eu.siacs.conversations.xml.TagWriter;
import eu.siacs.conversations.xml.XmlReader;
2015-10-11 07:11:50 -04:00
import eu.siacs.conversations.xmpp.forms.Data;
import eu.siacs.conversations.xmpp.forms.Field;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
2015-08-13 12:25:10 -04:00
import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
2014-03-10 14:22:13 -04: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;
2014-08-26 11:43:44 -04:00
import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
2014-03-10 14:22:13 -04:00
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 {
private static final int PACKET_IQ = 0;
private static final int PACKET_MESSAGE = 1;
private static final int PACKET_PRESENCE = 2;
protected Account account;
private final WakeLock wakeLock;
private Socket socket;
private XmlReader tagReader;
private TagWriter tagWriter;
private final Features features = new Features(this);
private boolean needsBinding = true;
private boolean shouldAuthenticate = true;
private Element streamFeatures;
private final HashMap<Jid, Info> disco = new HashMap<>();
2014-03-10 14:22:13 -04:00
private String streamId = null;
2014-04-05 06:08:35 -04:00
private int smVersion = 3;
2015-08-13 12:25:10 -04:00
private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
2014-03-10 14:22:13 -04:00
private int stanzasReceived = 0;
private int stanzasSent = 0;
private long lastPacketReceived = 0;
private long lastPingSent = 0;
private long lastConnect = 0;
private long lastSessionStarted = 0;
2015-12-15 13:14:38 -05:00
private long lastDiscoStarted = 0;
private int mPendingServiceDiscoveries = 0;
2015-12-15 13:14:38 -05:00
private final ArrayList<String> mPendingServiceDiscoveriesIds = new ArrayList<>();
private boolean mInteractive = false;
2014-05-18 05:25:04 -04:00
private int attempt = 0;
private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
2014-02-01 09:07:20 -05:00
private OnPresencePacketReceived presenceListener = null;
private OnJinglePacketReceived jingleListener = null;
2014-02-01 09:07:20 -05:00
private OnIqPacketReceived unregisteredIqListener = null;
private OnMessagePacketReceived messageListener = null;
private OnStatusChanged statusListener = null;
private OnBindListener bindListener = null;
private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
2014-08-26 10:52:42 -04:00
private OnMessageAcknowledged acknowledgedListener = null;
private XmppConnectionService mXmppConnectionService = null;
private SaslMechanism saslMechanism;
2014-11-12 10:15:38 -05:00
private X509KeyManager mKeyManager = new X509KeyManager() {
@Override
public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
return account.getPrivateKeyAlias();
}
@Override
public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
return null;
}
@Override
public X509Certificate[] getCertificateChain(String alias) {
try {
return KeyChain.getCertificateChain(mXmppConnectionService, alias);
} catch (Exception e) {
return new X509Certificate[0];
}
}
@Override
public String[] getClientAliases(String s, Principal[] principals) {
return new String[0];
}
@Override
public String[] getServerAliases(String s, Principal[] principals) {
return new String[0];
}
@Override
public PrivateKey getPrivateKey(String alias) {
try {
return KeyChain.getPrivateKey(mXmppConnectionService, alias);
} catch (Exception e) {
return null;
}
}
};
private Identity mServerIdentity = Identity.UNKNOWN;
2015-10-11 07:11:50 -04:00
private OnIqPacketReceived createPacketReceiveHandler() {
2015-10-12 06:36:54 -04:00
return new OnIqPacketReceived() {
2015-10-11 07:11:50 -04:00
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) {
account.setOption(Account.OPTION_REGISTER,
false);
changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
} else if (packet.hasChild("error")
&& (packet.findChild("error")
.hasChild("conflict"))) {
changeStatus(Account.State.REGISTRATION_CONFLICT);
} else {
changeStatus(Account.State.REGISTRATION_FAILED);
Log.d(Config.LOGTAG, packet.toString());
}
disconnect(true);
}
};
}
public XmppConnection(final Account account, final XmppConnectionService service) {
this.account = account;
2014-08-31 10:28:21 -04:00
this.wakeLock = service.getPowerManager().newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
tagWriter = new TagWriter();
mXmppConnectionService = service;
}
2014-03-06 09:11:56 -05:00
2014-11-15 11:09:02 -05:00
protected void changeStatus(final Account.State nextStatus) {
2014-03-11 11:27:33 -04:00
if (account.getStatus() != nextStatus) {
2014-11-15 11:09:02 -05:00
if ((nextStatus == Account.State.OFFLINE)
&& (account.getStatus() != Account.State.CONNECTING)
&& (account.getStatus() != Account.State.ONLINE)
&& (account.getStatus() != Account.State.DISABLED)) {
2014-03-13 12:29:22 -04:00
return;
}
2014-11-15 11:09:02 -05:00
if (nextStatus == Account.State.ONLINE) {
2014-05-18 05:25:04 -04:00
this.attempt = 0;
}
2014-03-11 11:27:33 -04:00
account.setStatus(nextStatus);
if (statusListener != null) {
statusListener.onStatusChanged(account);
}
2014-03-05 21:57:29 -05:00
}
}
protected void connect() {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
features.encryptionEnabled = false;
lastConnect = SystemClock.elapsedRealtime();
lastPingSent = SystemClock.elapsedRealtime();
2015-12-15 13:14:38 -05:00
lastDiscoStarted = Long.MAX_VALUE;
2014-05-18 05:25:04 -04:00
this.attempt++;
switch (account.getJid().getDomainpart()) {
case "chat.facebook.com":
mServerIdentity = Identity.FACEBOOK;
break;
case "nimbuzz.com":
mServerIdentity = Identity.NIMBUZZ;
break;
default:
mServerIdentity = Identity.UNKNOWN;
break;
}
try {
shouldAuthenticate = needsBinding = !account.isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter();
2014-11-15 11:09:02 -05:00
this.changeStatus(Account.State.CONNECTING);
2015-11-29 09:44:45 -05:00
final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
if (useTor) {
String destination;
2015-11-29 09:44:45 -05:00
if (account.getHostname() == null || account.getHostname().isEmpty()) {
destination = account.getServer().toString();
2015-11-29 09:44:45 -05:00
} else {
destination = account.getHostname();
2015-11-29 09:44:45 -05:00
}
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": connect to "+destination+" via TOR");
socket = SocksSocketFactory.createSocketOverTor(destination,account.getPort());
startXmpp();
2015-11-29 09:44:45 -05:00
} else if (DNSHelper.isIp(account.getServer().toString())) {
socket = new Socket();
try {
socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
} catch (IOException e) {
throw new UnknownHostException();
}
startXmpp();
} else {
final Bundle result = DNSHelper.getSRVRecord(account.getServer(), mXmppConnectionService);
2015-11-29 09:44:45 -05:00
final ArrayList<Parcelable>values = result.getParcelableArrayList("values");
for(Iterator<Parcelable> iterator = values.iterator(); iterator.hasNext();) {
final Bundle namePort = (Bundle) iterator.next();
try {
String srvRecordServer;
try {
srvRecordServer = IDN.toASCII(namePort.getString("name"));
} catch (final IllegalArgumentException e) {
// TODO: Handle me?`
srvRecordServer = "";
2014-10-16 17:31:48 -04:00
}
final int srvRecordPort = namePort.getInt("port");
final String srvIpServer = namePort.getString("ip");
// if tls is true, encryption is implied and must not be started
features.encryptionEnabled = namePort.getBoolean("tls");
final InetSocketAddress addr;
if (srvIpServer != null) {
addr = new InetSocketAddress(srvIpServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns " + srvRecordServer
+ "[" + srvIpServer + "]:" + srvRecordPort + " tls: " + features.encryptionEnabled);
} else {
addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": using values from dns "
+ srvRecordServer + ":" + srvRecordPort + " tls: " + features.encryptionEnabled);
}
if (!features.encryptionEnabled) {
socket = new Socket();
socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
} else {
final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
socket = tlsFactoryVerifier.factory.createSocket();
if (socket == null) {
throw new IOException("could not initialize ssl socket");
}
SSLSocketHelper.setSecurity((SSLSocket) socket);
SSLSocketHelper.setSNIHost(tlsFactoryVerifier.factory, (SSLSocket) socket, account.getServer().getDomainpart());
SSLSocketHelper.setAlpnProtocol(tlsFactoryVerifier.factory, (SSLSocket) socket, "xmpp-client");
socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), ((SSLSocket) socket).getSession())) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
throw new SecurityException();
}
}
if (startXmpp())
break; // successfully connected to server that speaks xmpp
} catch(final SecurityException e) {
throw e;
} catch (final Throwable e) {
2015-11-28 14:11:38 -05:00
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage() +"("+e.getClass().getName()+")");
if (!iterator.hasNext()) {
throw new UnknownHostException();
}
2014-10-16 17:31:48 -04:00
}
}
}
processStream();
} catch (final IncompatibleServerException e) {
this.changeStatus(Account.State.INCOMPATIBLE_SERVER);
} catch (final SecurityException e) {
this.changeStatus(Account.State.SECURITY_ERROR);
} catch (final UnauthorizedException e) {
this.changeStatus(Account.State.UNAUTHORIZED);
} catch (final UnknownHostException | ConnectException e) {
this.changeStatus(Account.State.SERVER_NOT_FOUND);
} catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
} catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
2014-11-15 11:09:02 -05:00
this.changeStatus(Account.State.OFFLINE);
this.attempt--; //don't count attempt when reconnecting instantly anyway
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
2014-04-03 12:16:14 -04:00
if (wakeLock.isHeld()) {
2014-08-31 10:28:21 -04:00
try {
wakeLock.release();
} catch (final RuntimeException ignored) {
2014-08-31 10:28:21 -04:00
}
}
}
}
/**
* Starts xmpp protocol, call after connecting to socket
* @return true if server returns with valid xmpp, false otherwise
* @throws IOException Unknown tag on connect
* @throws XmlPullParserException Bad Xml
* @throws NoSuchAlgorithmException Other error
*/
private boolean startXmpp() throws IOException, XmlPullParserException, NoSuchAlgorithmException {
tagWriter.setOutputStream(socket.getOutputStream());
tagReader.setInputStream(socket.getInputStream());
tagWriter.beginDocument();
sendStartStream();
Tag nextTag;
while ((nextTag = tagReader.readTag()) != null) {
if (nextTag.isStart("stream")) {
return true;
} else {
throw new IOException("unknown tag on connect");
}
}
if (socket.isConnected()) {
socket.close();
}
return false;
}
private static class TlsFactoryVerifier {
private final SSLSocketFactory factory;
private final HostnameVerifier verifier;
public TlsFactoryVerifier(final SSLSocketFactory factory, final HostnameVerifier verifier) throws IOException {
this.factory = factory;
this.verifier = verifier;
if (factory == null || verifier == null) {
throw new IOException("could not setup ssl");
}
}
}
private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
final SSLContext sc = SSLContext.getInstance("TLS");
MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
KeyManager[] keyManager;
if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
keyManager = new KeyManager[]{mKeyManager};
} else {
keyManager = null;
}
sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager : trustManager.getNonInteractive()}, mXmppConnectionService.getRNG());
final SSLSocketFactory factory = sc.getSocketFactory();
final HostnameVerifier verifier;
if (mInteractive) {
verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier());
} else {
verifier = trustManager.wrapHostnameVerifierNonInteractive(new XmppDomainVerifier());
}
return new TlsFactoryVerifier(factory, verifier);
}
@Override
public void run() {
2015-03-05 09:46:33 -05:00
try {
if (socket != null) {
socket.close();
}
} catch (final IOException ignored) {
}
connect();
}
2015-10-13 17:34:09 -04:00
private void processStream() throws XmlPullParserException, IOException, NoSuchAlgorithmException {
Tag nextTag = tagReader.readTag();
while (nextTag != null && !nextTag.isEnd("stream")) {
if (nextTag.isStart("error")) {
processStreamError(nextTag);
} else if (nextTag.isStart("features")) {
processStreamFeatures(nextTag);
} else if (nextTag.isStart("proceed")) {
switchOverToTls(nextTag);
} else if (nextTag.isStart("success")) {
final String challenge = tagReader.readElement(nextTag).getContent();
try {
saslMechanism.getResponse(challenge);
} catch (final SaslMechanism.AuthenticationException e) {
disconnect(true);
Log.e(Config.LOGTAG, String.valueOf(e));
}
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
account.setKey(Account.PINNED_MECHANISM_KEY,
String.valueOf(saslMechanism.getPriority()));
tagReader.reset();
sendStartStream();
final Tag tag = tagReader.readTag();
if (tag != null && tag.isStart("stream")) {
processStream();
} else {
throw new IOException("server didn't restart stream after successful auth");
}
break;
} else if (nextTag.isStart("failure")) {
throw new UnauthorizedException();
} else if (nextTag.isStart("challenge")) {
final String challenge = tagReader.readElement(nextTag).getContent();
final Element response = new Element("response");
response.setAttribute("xmlns",
"urn:ietf:params:xml:ns:xmpp-sasl");
try {
response.setContent(saslMechanism.getResponse(challenge));
} catch (final SaslMechanism.AuthenticationException e) {
// TODO: Send auth abort tag.
Log.e(Config.LOGTAG, e.toString());
}
tagWriter.writeElement(response);
} else if (nextTag.isStart("enabled")) {
final Element enabled = tagReader.readElement(nextTag);
if ("true".equals(enabled.getAttribute("resume"))) {
this.streamId = enabled.getAttribute("id");
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": stream managment(" + smVersion
+ ") enabled (resumable)");
} else {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": stream management(" + smVersion + ") enabled");
}
this.stanzasReceived = 0;
final RequestPacket r = new RequestPacket(smVersion);
tagWriter.writeStanzaAsync(r);
} else if (nextTag.isStart("resumed")) {
lastPacketReceived = SystemClock.elapsedRealtime();
final Element resumed = tagReader.readElement(nextTag);
final String h = resumed.getAttribute("h");
try {
final int serverCount = Integer.parseInt(h);
if (serverCount != stanzasSent) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
+ ": session resumed with lost packages");
stanzasSent = serverCount;
} else {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
}
acknowledgeStanzaUpTo(serverCount);
ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
failedStanzas.add(mStanzaQueue.valueAt(i));
}
mStanzaQueue.clear();
Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
for(AbstractAcknowledgeableStanza packet : failedStanzas) {
if (packet instanceof MessagePacket) {
MessagePacket message = (MessagePacket) packet;
mXmppConnectionService.markMessage(account,
message.getTo().toBareJid(),
message.getId(),
Message.STATUS_UNSEND);
}
sendPacket(packet);
}
} catch (final NumberFormatException ignored) {
}
Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
changeStatus(Account.State.ONLINE);
} else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag);
if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
}
final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) {
final Element ack = tagReader.readElement(nextTag);
lastPacketReceived = SystemClock.elapsedRealtime();
try {
final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
acknowledgeStanzaUpTo(serverSequence);
} catch (NumberFormatException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
}
} else if (nextTag.isStart("failed")) {
tagReader.readElement(nextTag);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
streamId = null;
if (account.getStatus() != Account.State.ONLINE) {
sendBindRequest();
}
} else if (nextTag.isStart("iq")) {
processIq(nextTag);
} else if (nextTag.isStart("message")) {
processMessage(nextTag);
} else if (nextTag.isStart("presence")) {
processPresence(nextTag);
}
nextTag = tagReader.readTag();
}
throw new IOException("reached end of stream. last tag was "+nextTag);
}
2015-08-06 14:48:55 -04:00
private void acknowledgeStanzaUpTo(int serverCount) {
2015-08-13 12:25:10 -04:00
for (int i = 0; i < mStanzaQueue.size(); ++i) {
if (serverCount >= mStanzaQueue.keyAt(i)) {
2015-08-06 14:48:55 -04:00
if (Config.EXTENDED_SM_LOGGING) {
2015-08-13 12:25:10 -04:00
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
2015-08-06 14:48:55 -04:00
}
2015-08-13 12:25:10 -04:00
AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
if (stanza instanceof MessagePacket && acknowledgedListener != null) {
MessagePacket packet = (MessagePacket) stanza;
acknowledgedListener.onMessageAcknowledged(account, packet.getId());
2015-08-06 14:48:55 -04:00
}
2015-08-13 12:25:10 -04:00
mStanzaQueue.removeAt(i);
2015-08-06 14:48:55 -04:00
i--;
}
}
}
private Element processPacket(final Tag currentTag, final int packetType)
throws XmlPullParserException, IOException {
Element element;
switch (packetType) {
2014-11-03 04:03:45 -05:00
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-08-31 10:28:21 -04:00
if (nextTag == null) {
2014-05-23 04:15:58 -04:00
throw new IOException("interrupted mid tag");
}
2014-02-09 08:10:52 -05:00
while (!nextTag.isEnd(element.getName())) {
if (!nextTag.isNo()) {
final Element child = tagReader.readElement(nextTag);
final String type = currentTag.getAttribute("type");
if (packetType == PACKET_IQ
&& "jingle".equals(child.getName())
&& ("set".equalsIgnoreCase(type) || "get"
.equalsIgnoreCase(type))) {
element = new JinglePacket();
element.setAttributes(currentTag.getAttributes());
}
element.addChild(child);
}
nextTag = tagReader.readTag();
2014-08-31 10:28:21 -04:00
if (nextTag == null) {
2014-05-23 04:15:58 -04:00
throw new IOException("interrupted mid tag");
}
}
if (stanzasReceived == Integer.MAX_VALUE) {
resetStreamId();
throw new IOException("time to restart the session. cant handle >2 billion pcks");
}
2014-03-10 14:22:13 -04:00
++stanzasReceived;
lastPacketReceived = SystemClock.elapsedRealtime();
return element;
}
private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
2014-05-21 16:22:36 -04:00
if (packet.getId() == null) {
return; // an iq packet without id is definitely invalid
}
2014-05-21 16:22:36 -04:00
if (packet instanceof JinglePacket) {
if (this.jingleListener != null) {
this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
}
} else {
OnIqPacketReceived callback = null;
2015-08-16 06:12:22 -04:00
synchronized (this.packetCallbacks) {
if (packetCallbacks.containsKey(packet.getId())) {
final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
// Packets to the server should have responses from the server
if (packetCallbackDuple.first.toServer(account)) {
if (packet.fromServer(account) || mServerIdentity == Identity.FACEBOOK) {
callback = packetCallbackDuple.second;
2015-08-16 06:12:22 -04:00
packetCallbacks.remove(packet.getId());
} else {
Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
}
} else {
2015-08-16 06:12:22 -04:00
if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
callback = packetCallbackDuple.second;
2015-08-16 06:12:22 -04:00
packetCallbacks.remove(packet.getId());
} else {
Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
}
}
2015-08-16 06:12:22 -04:00
} else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
callback = this.unregisteredIqListener;
}
}
if (callback != null) {
callback.onIqPacketReceived(account,packet);
}
}
}
2014-02-09 08:10:52 -05:00
private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
this.messageListener.onMessagePacketReceived(account, packet);
}
2014-02-09 08:10:52 -05:00
private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
this.presenceListener.onPresencePacketReceived(account, packet);
}
2014-03-10 14:22:13 -04:00
private void sendStartTLS() throws IOException {
final Tag startTLS = Tag.empty("starttls");
startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
tagWriter.writeTag(startTLS);
}
2014-12-29 19:17:11 -05:00
private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
2014-12-30 08:16:25 -05:00
tagReader.readTag();
try {
final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
2014-12-30 08:16:25 -05:00
final InetAddress address = socket == null ? null : socket.getInetAddress();
2014-12-29 19:17:11 -05:00
if (address == null) {
2014-12-29 19:17:11 -05:00
throw new IOException("could not setup ssl");
}
2014-11-03 04:03:45 -05:00
final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
2014-12-29 19:17:11 -05:00
if (sslSocket == null) {
throw new IOException("could not initialize ssl socket");
}
SSLSocketHelper.setSecurity(sslSocket);
2015-01-17 13:40:15 -05:00
if (!tlsFactoryVerifier.verifier.verify(account.getServer().getDomainpart(), sslSocket.getSession())) {
2014-12-30 08:16:25 -05:00
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
throw new SecurityException();
2014-12-29 19:17:11 -05:00
}
tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream();
Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
features.encryptionEnabled = true;
final Tag tag = tagReader.readTag();
if (tag != null && tag.isStart("stream")) {
2015-10-13 17:34:09 -04:00
processStream();
} else {
throw new IOException("server didn't restart stream after STARTTLS");
}
2014-12-29 19:17:11 -05:00
sslSocket.close();
2014-12-30 08:16:25 -05:00
} catch (final NoSuchAlgorithmException | KeyManagementException e1) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": TLS certificate verification failed");
throw new SecurityException();
2014-12-30 08:16:25 -05:00
}
}
private void processStreamFeatures(final Tag currentTag)
throws XmlPullParserException, IOException {
this.streamFeatures = tagReader.readElement(currentTag);
if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
sendStartTLS();
} else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
if (features.encryptionEnabled) {
sendRegistryRequest();
} else {
throw new IncompatibleServerException();
}
2014-05-21 16:22:36 -04:00
} else if (!this.streamFeatures.hasChild("register")
2014-10-19 17:14:17 -04:00
&& account.isOptionSet(Account.OPTION_REGISTER)) {
2014-11-15 11:09:02 -05:00
changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
disconnect(true);
2014-02-09 08:10:52 -05:00
} else if (this.streamFeatures.hasChild("mechanisms")
&& shouldAuthenticate && features.encryptionEnabled) {
2014-11-12 10:15:38 -05:00
final List<String> mechanisms = extractMechanisms(streamFeatures
2014-05-21 16:22:36 -04:00
.findChild("mechanisms"));
final Element auth = new Element("auth");
auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
} else if (mechanisms.contains("SCRAM-SHA-1")) {
saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
2014-11-15 09:42:40 -05:00
} else if (mechanisms.contains("PLAIN")) {
saslMechanism = new Plain(tagWriter, account);
} else if (mechanisms.contains("DIGEST-MD5")) {
saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
}
if (saslMechanism != null) {
final JSONObject keys = account.getKeys();
try {
if (keys.has(Account.PINNED_MECHANISM_KEY) &&
keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
" has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
"). Possible downgrade attack?");
throw new SecurityException();
}
} catch (final JSONException e) {
Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
}
Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
auth.setAttribute("mechanism", saslMechanism.getMechanism());
if (!saslMechanism.getClientFirstMessage().isEmpty()) {
auth.setContent(saslMechanism.getClientFirstMessage());
}
tagWriter.writeElement(auth);
} else {
throw new IncompatibleServerException();
2014-11-15 09:42:40 -05:00
}
2015-08-23 11:29:31 -04:00
} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
}
final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
2014-03-10 14:22:13 -04:00
this.tagWriter.writeStanzaAsync(resume);
} else if (needsBinding) {
if (this.streamFeatures.hasChild("bind")) {
sendBindRequest();
} else {
throw new IncompatibleServerException();
}
2014-03-10 14:22:13 -04:00
}
}
2014-02-09 08:10:52 -05:00
private List<String> extractMechanisms(final Element stream) {
final ArrayList<String> mechanisms = new ArrayList<>(stream
2014-05-21 16:22:36 -04:00
.getChildren().size());
for (final Element child : stream.getChildren()) {
mechanisms.add(child.getContent());
}
return mechanisms;
}
2015-10-11 07:11:50 -04:00
public void sendCaptchaRegistryRequest(String id, Data data) {
if (data == null) {
setAccountCreationFailed("");
} else {
IqPacket request = getIqGenerator().generateCreateAccountWithCaptcha(account, id, data);
sendIqPacket(request, createPacketReceiveHandler());
}
}
private void sendRegistryRequest() {
2014-12-30 08:16:25 -05:00
final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
register.query("jabber:iq:register");
register.setTo(account.getServer());
sendIqPacket(register, new OnIqPacketReceived() {
2014-05-21 16:22:36 -04:00
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
2015-10-11 07:11:50 -04:00
boolean failed = false;
if (packet.getType() == IqPacket.TYPE.RESULT
&& packet.query().hasChild("username")
2014-05-21 16:22:36 -04:00
&& (packet.query().hasChild("password"))) {
2014-12-30 08:16:25 -05:00
final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
final Element username = new Element("username").setContent(account.getUsername());
final Element password = new Element("password").setContent(account.getPassword());
2014-03-20 10:49:53 -04:00
register.query("jabber:iq:register").addChild(username);
register.query().addChild(password);
2015-10-11 07:11:50 -04:00
sendIqPacket(register, createPacketReceiveHandler());
} else if (packet.getType() == IqPacket.TYPE.RESULT
&& (packet.query().hasChild("x", "jabber:x:data"))) {
final Data data = Data.parse(packet.query().findChild("x", "jabber:x:data"));
final Element blob = packet.query().findChild("data", "urn:xmpp:bob");
final String id = packet.getId();
Bitmap captcha = null;
if (blob != null) {
try {
final String base64Blob = blob.getContent();
final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
InputStream stream = new ByteArrayInputStream(strBlob);
captcha = BitmapFactory.decodeStream(stream);
} catch (Exception e) {
2015-10-12 06:36:54 -04:00
//ignored
}
2015-10-11 07:11:50 -04:00
} else {
try {
Field url = data.getFieldByName("url");
String urlString = url.findChildContent("value");
URL uri = new URL(urlString);
captcha = BitmapFactory.decodeStream(uri.openConnection().getInputStream());
} catch (IOException e) {
2015-10-11 07:11:50 -04:00
Log.e(Config.LOGTAG, e.toString());
}
}
if (captcha != null) {
failed = !mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha);
}
} else {
2015-10-11 07:11:50 -04:00
failed = true;
}
if (failed) {
final Element instructions = packet.query().findChild("instructions");
2015-10-11 07:11:50 -04:00
setAccountCreationFailed((instructions != null) ? instructions.getContent() : "");
}
}
});
}
2015-10-11 07:11:50 -04:00
private void setAccountCreationFailed(String instructions) {
changeStatus(Account.State.REGISTRATION_FAILED);
disconnect(true);
Log.d(Config.LOGTAG, account.getJid().toBareJid()
+ ": could not register. instructions are"
+ instructions);
}
private void sendBindRequest() {
2015-10-19 17:03:19 -04:00
while(!mXmppConnectionService.areMessagesInitialized() && socket != null && !socket.isClosed()) {
2015-02-12 12:53:00 -05:00
try {
Thread.sleep(500);
} catch (final InterruptedException ignored) {
}
}
needsBinding = false;
2015-08-06 08:54:37 -04:00
clearIqCallbacks();
2014-12-30 08:16:25 -05:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2014-05-21 16:22:36 -04:00
iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
.addChild("resource").setContent(account.getResource());
this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
return;
}
final Element bind = packet.findChild("bind");
if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
final Element jid = bind.findChild("jid");
2014-09-22 10:04:37 -04:00
if (jid != null && jid.getContent() != null) {
try {
account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
} catch (final InvalidJidException e) {
// TODO: Handle the case where an external JID is technically invalid?
}
if (streamFeatures.hasChild("session")) {
sendStartSession();
} else {
sendPostBindInitialization();
2014-07-26 09:44:32 -04:00
}
} else {
Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
2014-07-26 09:44:32 -04:00
disconnect(true);
}
} else {
Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure");
2014-07-26 09:44:32 -04:00
disconnect(true);
}
2014-02-09 08:10:52 -05:00
}
});
}
2015-08-06 08:54:37 -04:00
private void clearIqCallbacks() {
final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
2015-08-16 06:12:22 -04:00
synchronized (this.packetCallbacks) {
if (this.packetCallbacks.size() == 0) {
return;
}
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
2015-08-16 06:12:22 -04:00
while (iterator.hasNext()) {
Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
callbacks.add(entry.second);
2015-08-16 06:12:22 -04:00
iterator.remove();
}
2015-08-06 08:54:37 -04:00
}
for(OnIqPacketReceived callback : callbacks) {
callback.onIqPacketReceived(account,failurePacket);
2015-08-06 08:54:37 -04:00
}
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
2015-08-06 08:54:37 -04:00
}
2015-12-15 13:14:38 -05:00
public void sendDiscoTimeout() {
final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR); //don't use timeout
final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
synchronized (this.mPendingServiceDiscoveriesIds) {
for(String id : mPendingServiceDiscoveriesIds) {
synchronized (this.packetCallbacks) {
Pair<IqPacket, OnIqPacketReceived> pair = this.packetCallbacks.remove(id);
if (pair != null) {
callbacks.add(pair.second);
}
}
}
this.mPendingServiceDiscoveriesIds.clear();
}
if (callbacks.size() > 0) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending disco timeout");
resetStreamId(); //we don't want to live with this for ever
}
for(OnIqPacketReceived callback : callbacks) {
callback.onIqPacketReceived(account,failurePacket);
}
}
private void sendStartSession() {
final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
2015-08-06 14:48:55 -04:00
startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(Account account, IqPacket packet) {
2015-10-12 06:36:54 -04:00
if (packet.getType() == IqPacket.TYPE.RESULT) {
sendPostBindInitialization();
} else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
disconnect(true);
}
}
});
}
private void sendPostBindInitialization() {
smVersion = 0;
if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
smVersion = 3;
} else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
smVersion = 2;
}
if (smVersion != 0) {
final EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable);
stanzasSent = 0;
2015-08-13 12:25:10 -04:00
mStanzaQueue.clear();
}
features.carbonsEnabled = false;
features.blockListRequested = false;
2015-10-19 17:03:19 -04:00
synchronized (this.disco) {
this.disco.clear();
}
mPendingServiceDiscoveries = mServerIdentity == Identity.NIMBUZZ ? 1 : 0;
2015-12-15 13:14:38 -05:00
lastDiscoStarted = SystemClock.elapsedRealtime();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
sendServiceDiscoveryItems(account.getServer());
sendServiceDiscoveryInfo(account.getServer());
sendServiceDiscoveryInfo(account.getJid().toBareJid());
2015-08-25 05:11:32 -04:00
this.lastSessionStarted = SystemClock.elapsedRealtime();
2014-02-09 08:10:52 -05:00
}
private void sendServiceDiscoveryInfo(final Jid jid) {
if (mServerIdentity != Identity.NIMBUZZ) {
mPendingServiceDiscoveries++;
}
2015-10-19 17:03:19 -04:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setTo(jid);
iq.query("http://jabber.org/protocol/disco#info");
2015-12-15 13:14:38 -05:00
String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
2014-02-09 08:10:52 -05:00
2015-10-19 17:03:19 -04:00
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) {
boolean advancedStreamFeaturesLoaded;
2015-10-19 17:03:19 -04:00
synchronized (XmppConnection.this.disco) {
final List<Element> elements = packet.query().getChildren();
final Info info = new Info();
for (final Element element : elements) {
if (element.getName().equals("identity")) {
String type = element.getAttribute("type");
String category = element.getAttribute("category");
String name = element.getAttribute("name");
if (type != null && category != null) {
info.identities.add(new Pair<>(category, type));
if (mServerIdentity == Identity.UNKNOWN
&& type.equals("im")
&& category.equals("server")) {
if (name != null && jid.equals(account.getServer())) {
switch (name) {
case "Prosody":
mServerIdentity = Identity.PROSODY;
break;
case "ejabberd":
mServerIdentity = Identity.EJABBERD;
break;
case "Slack-XMPP":
mServerIdentity = Identity.SLACK;
break;
}
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server name: " + name);
}
}
}
} else if (element.getName().equals("feature")) {
info.features.add(element.getAttribute("var"));
}
2014-11-15 11:24:06 -05:00
}
disco.put(jid, info);
2015-10-19 17:03:19 -04:00
advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
&& disco.containsKey(account.getJid().toBareJid());
}
if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
enableAdvancedStreamFeatures();
2014-11-15 11:24:06 -05:00
}
2015-10-19 17:03:19 -04:00
} else {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
2014-02-09 08:10:52 -05:00
}
if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
mPendingServiceDiscoveries--;
if (mPendingServiceDiscoveries == 0) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": done with service discovery");
2015-12-15 13:14:38 -05:00
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
changeStatus(Account.State.ONLINE);
if (bindListener != null) {
bindListener.onBind(account);
}
}
}
2015-10-19 17:03:19 -04:00
}
});
2015-12-15 13:14:38 -05:00
synchronized (this.mPendingServiceDiscoveriesIds) {
this.mPendingServiceDiscoveriesIds.add(id);
}
2014-02-09 08:10:52 -05:00
}
2014-05-21 16:22:36 -04:00
private void enableAdvancedStreamFeatures() {
if (getFeatures().carbons() && !features.carbonsEnabled) {
sendEnableCarbons();
}
if (getFeatures().blocking() && !features.blockListRequested) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
}
for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
listener.onAdvancedStreamFeaturesAvailable(account);
}
}
2014-05-21 16:22:36 -04:00
private void sendServiceDiscoveryItems(final Jid server) {
2014-12-30 08:16:25 -05:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setTo(server.toDomainJid());
2014-03-14 23:59:18 -04:00
iq.query("http://jabber.org/protocol/disco#items");
this.sendIqPacket(iq, new OnIqPacketReceived() {
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
if (packet.getType() == IqPacket.TYPE.RESULT) {
final List<Element> elements = packet.query().getChildren();
for (final Element element : elements) {
if (element.getName().equals("item")) {
final Jid jid = element.getAttributeAsJid("jid");
if (jid != null && !jid.equals(account.getServer())) {
sendServiceDiscoveryInfo(jid);
}
}
}
} else {
2015-12-15 13:14:38 -05:00
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
}
2014-03-14 23:59:18 -04:00
}
});
}
2014-03-06 09:11:56 -05:00
2014-02-09 08:10:52 -05:00
private void sendEnableCarbons() {
2014-12-30 08:16:25 -05:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
2014-05-21 16:22:36 -04:00
iq.addChild("enable", "urn:xmpp:carbons:2");
2014-02-09 08:10:52 -05:00
this.sendIqPacket(iq, new OnIqPacketReceived() {
2014-03-06 09:11:56 -05:00
2014-02-09 08:10:52 -05:00
@Override
public void onIqPacketReceived(final Account account, final IqPacket packet) {
2014-02-09 08:10:52 -05:00
if (!packet.hasChild("error")) {
Log.d(Config.LOGTAG, account.getJid().toBareJid()
2014-03-06 09:11:56 -05:00
+ ": successfully enabled carbons");
features.carbonsEnabled = true;
2014-02-09 08:10:52 -05:00
} else {
Log.d(Config.LOGTAG, account.getJid().toBareJid()
2014-03-06 09:11:56 -05:00
+ ": error enableing carbons " + packet.toString());
2014-02-09 08:10:52 -05:00
}
}
});
}
private void processStreamError(final Tag currentTag)
throws XmlPullParserException, IOException {
final Element streamError = tagReader.readElement(currentTag);
if (streamError != null && streamError.hasChild("conflict")) {
final String resource = account.getResource().split("\\.")[0];
account.setResource(resource + "." + nextRandomId());
Log.d(Config.LOGTAG,
account.getJid().toBareJid() + ": switching resource due to conflict ("
+ account.getResource() + ")");
} else if (streamError != null) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
2014-09-03 08:57:40 -04:00
}
}
2014-03-10 14:22:13 -04:00
private void sendStartStream() throws IOException {
final Tag stream = Tag.start("stream:stream");
stream.setAttribute("to", account.getServer().toString());
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, mXmppConnectionService.getRNG()).toString(32);
}
2014-02-09 08:10:52 -05:00
2015-12-15 13:14:38 -05:00
public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
packet.setFrom(account.getJid());
2015-12-15 13:14:38 -05:00
return this.sendUnmodifiedIqPacket(packet, callback);
}
2014-05-21 16:22:36 -04:00
2015-12-15 13:14:38 -05:00
private synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
2014-05-21 16:22:36 -04:00
if (packet.getId() == null) {
final String id = nextRandomId();
packet.setAttribute("id", id);
}
if (callback != null) {
2015-08-16 06:12:22 -04:00
synchronized (this.packetCallbacks) {
packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
}
}
this.sendPacket(packet);
2015-12-15 13:14:38 -05:00
return packet.getId();
}
2014-02-09 08:10:52 -05:00
public void sendMessagePacket(final MessagePacket packet) {
this.sendPacket(packet);
2014-03-02 23:01:02 -05:00
}
2014-03-06 09:11:56 -05:00
public void sendPresencePacket(final PresencePacket packet) {
this.sendPacket(packet);
2014-03-02 23:01:02 -05:00
}
2014-08-31 10:28:21 -04:00
private synchronized void sendPacket(final AbstractStanza packet) {
if (stanzasSent == Integer.MAX_VALUE) {
resetStreamId();
disconnect(true);
return;
}
2014-03-10 14:22:13 -04:00
tagWriter.writeStanzaAsync(packet);
2015-08-13 12:25:10 -04:00
if (packet instanceof AbstractAcknowledgeableStanza) {
AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
++stanzasSent;
this.mStanzaQueue.put(stanzasSent, stanza);
if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
2015-08-13 12:25:10 -04:00
if (Config.EXTENDED_SM_LOGGING) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
}
tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
}
2014-03-02 23:01:02 -05:00
}
2014-02-01 09:07:20 -05:00
}
2014-05-21 16:22:36 -04:00
2014-03-11 10:44:22 -04:00
public void sendPing() {
if (!r()) {
2014-12-30 08:16:25 -05:00
final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
iq.setFrom(account.getJid());
2014-05-21 16:22:36 -04:00
iq.addChild("ping", "urn:xmpp:ping");
2014-03-11 10:44:22 -04:00
this.sendIqPacket(iq, null);
}
this.lastPingSent = SystemClock.elapsedRealtime();
2014-03-11 10:44:22 -04:00
}
2014-02-09 08:10:52 -05:00
public void setOnMessagePacketReceivedListener(
final OnMessagePacketReceived listener) {
2014-02-01 09:07:20 -05:00
this.messageListener = listener;
}
2014-02-09 08:10:52 -05:00
public void setOnUnregisteredIqPacketReceivedListener(
final OnIqPacketReceived listener) {
2014-02-01 09:07:20 -05:00
this.unregisteredIqListener = listener;
}
2014-02-09 08:10:52 -05:00
public void setOnPresencePacketReceivedListener(
final OnPresencePacketReceived listener) {
2014-02-01 09:07:20 -05:00
this.presenceListener = listener;
}
2014-05-21 16:22:36 -04:00
public void setOnJinglePacketReceivedListener(
final OnJinglePacketReceived listener) {
this.jingleListener = listener;
}
2014-02-09 08:10:52 -05:00
public void setOnStatusChangedListener(final OnStatusChanged listener) {
this.statusListener = listener;
}
2014-05-21 16:22:36 -04:00
public void setOnBindListener(final OnBindListener listener) {
this.bindListener = listener;
}
2014-08-31 10:28:21 -04:00
public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
2014-08-26 10:52:42 -04:00
this.acknowledgedListener = listener;
}
public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
this.advancedStreamFeaturesLoadedListeners.add(listener);
}
2014-12-04 19:54:16 -05:00
}
public void disconnect(final boolean force) {
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
if (force) {
try {
2014-03-10 14:22:13 -04:00
socket.close();
} catch(Exception e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid().toString()+": exception during force close ("+e.getMessage()+")");
2014-04-03 09:08:53 -04:00
}
return;
} else {
resetStreamId();
if (tagWriter.isActive()) {
tagWriter.finish();
try {
int i = 0;
boolean warned = false;
while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
if (!warned) {
Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
warned = true;
2014-05-21 16:22:36 -04:00
}
Thread.sleep(200);
i++;
}
if (warned) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
2014-05-21 16:22:36 -04:00
}
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
tagWriter.writeTag(Tag.end("stream:stream"));
} catch (final IOException e) {
Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
} catch (final InterruptedException e) {
Log.d(Config.LOGTAG, "interrupted");
2014-05-21 16:22:36 -04:00
}
}
2014-03-10 14:22:13 -04:00
}
}
2014-05-21 16:22:36 -04:00
public void resetStreamId() {
this.streamId = null;
}
public List<Jid> findDiscoItemsByFeature(final String feature) {
2015-10-19 17:03:19 -04:00
synchronized (this.disco) {
final List<Jid> items = new ArrayList<>();
for (final Entry<Jid, Info> cursor : this.disco.entrySet()) {
if (cursor.getValue().features.contains(feature)) {
items.add(cursor.getKey());
}
2014-05-21 16:22:36 -04:00
}
2015-10-19 17:03:19 -04:00
return items;
2014-05-21 16:22:36 -04:00
}
}
2014-08-31 10:28:21 -04:00
public Jid findDiscoItemByFeature(final String feature) {
final List<Jid> items = findDiscoItemsByFeature(feature);
2014-08-31 10:28:21 -04:00
if (items.size() >= 1) {
return items.get(0);
}
return null;
2014-03-13 12:29:22 -04:00
}
2014-03-10 14:22:13 -04:00
public boolean r() {
if (getFeatures().sm()) {
this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
return true;
} else {
return false;
}
2014-03-10 14:22:13 -04:00
}
2014-08-31 10:28:21 -04:00
2014-03-14 23:59:18 -04:00
public String getMucServer() {
2015-10-19 17:03:19 -04:00
synchronized (this.disco) {
for (final Entry<Jid, Info> cursor : disco.entrySet()) {
final Info value = cursor.getValue();
if (value.features.contains("http://jabber.org/protocol/muc")
&& !value.features.contains("jabber:iq:gateway")
&& !value.identities.contains(new Pair<>("conference", "irc"))) {
return cursor.getKey().toString();
}
}
}
return null;
2014-03-14 23:59:18 -04:00
}
2014-05-21 16:22:36 -04:00
2014-05-18 05:25:04 -04:00
public int getTimeToNextAttempt() {
final int interval = (int) (25 * Math.pow(1.5, attempt));
final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
2014-05-18 05:25:04 -04:00
return interval - secondsSinceLast;
}
2014-05-21 16:22:36 -04:00
2014-05-18 05:25:04 -04:00
public int getAttempt() {
return this.attempt;
}
2014-08-31 10:28:21 -04:00
public Features getFeatures() {
return this.features;
}
2014-08-31 10:28:21 -04:00
public long getLastSessionEstablished() {
2015-08-25 05:11:32 -04:00
final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
return System.currentTimeMillis() - diff;
}
public long getLastConnect() {
return this.lastConnect;
}
public long getLastPingSent() {
return this.lastPingSent;
}
2015-12-15 13:14:38 -05:00
public long getLastDiscoStarted() {
return this.lastDiscoStarted;
}
public long getLastPacketReceived() {
return this.lastPacketReceived;
}
public void sendActive() {
this.sendPacket(new ActivePacket());
}
public void sendInactive() {
this.sendPacket(new InactivePacket());
}
2015-02-10 11:13:34 -05:00
public void resetAttemptCount() {
this.attempt = 0;
this.lastConnect = 0;
}
public void setInteractive(boolean interactive) {
this.mInteractive = interactive;
}
public Identity getServerIdentity() {
return mServerIdentity;
}
private class Info {
public final ArrayList<String> features = new ArrayList<>();
public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
}
private class UnauthorizedException extends IOException {
}
private class SecurityException extends IOException {
}
private class IncompatibleServerException extends IOException {
}
public enum Identity {
FACEBOOK,
SLACK,
EJABBERD,
PROSODY,
NIMBUZZ,
UNKNOWN
}
public class Features {
XmppConnection connection;
private boolean carbonsEnabled = false;
private boolean encryptionEnabled = false;
private boolean blockListRequested = false;
2014-08-31 10:28:21 -04:00
public Features(final XmppConnection connection) {
this.connection = connection;
}
2014-08-31 10:28:21 -04:00
private boolean hasDiscoFeature(final Jid server, final String feature) {
2015-10-19 17:03:19 -04:00
synchronized (XmppConnection.this.disco) {
return connection.disco.containsKey(server) &&
connection.disco.get(server).features.contains(feature);
}
}
2014-08-31 10:28:21 -04:00
public boolean carbons() {
return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
}
2014-08-31 10:28:21 -04:00
public boolean blocking() {
return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
}
public boolean register() {
return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
}
public boolean sm() {
return streamId != null
|| (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
}
2014-08-31 10:28:21 -04:00
2014-08-26 11:43:44 -04:00
public boolean csi() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
2014-08-26 11:43:44 -04:00
}
2014-08-31 10:28:21 -04:00
public boolean pep() {
2015-10-19 17:03:19 -04:00
synchronized (XmppConnection.this.disco) {
final Pair<String, String> needle = new Pair<>("pubsub", "pep");
Info info = disco.get(account.getServer());
if (info != null && info.identities.contains(needle)) {
return true;
} else {
info = disco.get(account.getJid().toBareJid());
return info != null && info.identities.contains(needle);
}
}
}
2014-08-31 10:28:21 -04:00
public boolean mam() {
if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
return true;
} else {
return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
}
}
public boolean advancedStreamFeaturesLoaded() {
2015-10-19 17:03:19 -04:00
synchronized (XmppConnection.this.disco) {
return disco.containsKey(account.getServer());
}
}
public boolean rosterVersioning() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
}
2014-08-31 10:28:21 -04:00
public void setBlockListRequested(boolean value) {
this.blockListRequested = value;
}
public boolean httpUpload() {
return !Config.DISABLE_HTTP_UPLOAD && findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
}
}
private IqGenerator getIqGenerator() {
return mXmppConnectionService.getIqGenerator();
}
}