Merge pull request #665 from SamWhited/issue71

Add SCRAM-SHA1 support
This commit is contained in:
Daniel Gultsch 2014-11-15 15:34:50 +01:00
commit 4c504dea7a
8 changed files with 722 additions and 374 deletions

View File

@ -13,60 +13,69 @@ import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.TagWriter; import eu.siacs.conversations.xml.TagWriter;
public class DigestMd5 extends SaslMechanism { public class DigestMd5 extends SaslMechanism {
public DigestMd5(final TagWriter tagWriter, final Account account, final SecureRandom rng) { public DigestMd5(final TagWriter tagWriter, final Account account, final SecureRandom rng) {
super(tagWriter, account, rng); super(tagWriter, account, rng);
} }
@Override public static String getMechanism() {
public String getMechanism() { return "DIGEST-MD5";
return "DIGEST-MD5"; }
}
@Override private State state = State.INITIAL;
public String getResponse(final String challenge) {
final String encodedResponse;
try {
final String[] challengeParts = new String(Base64.decode(challenge,
Base64.DEFAULT)).split(",");
String nonce = "";
for (int i = 0; i < challengeParts.length; ++i) {
String[] parts = challengeParts[i].split("=");
if (parts[0].equals("nonce")) {
nonce = parts[1].replace("\"", "");
} else if (parts[0].equals("rspauth")) {
return "";
}
}
final String digestUri = "xmpp/" + account.getServer();
final String nonceCount = "00000001";
final String x = account.getUsername() + ":" + account.getServer() + ":"
+ account.getPassword();
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] y = md.digest(x.getBytes(Charset.defaultCharset()));
final String cNonce = new BigInteger(100, rng).toString(32);
final byte[] a1 = CryptoHelper.concatenateByteArrays(y,
(":" + nonce + ":" + cNonce).getBytes(Charset
.defaultCharset()));
final String a2 = "AUTHENTICATE:" + digestUri;
final String ha1 = CryptoHelper.bytesToHex(md.digest(a1));
final String ha2 = CryptoHelper.bytesToHex(md.digest(a2.getBytes(Charset
.defaultCharset())));
final String kd = ha1 + ":" + nonce + ":" + nonceCount + ":" + cNonce
+ ":auth:" + ha2;
final String response = CryptoHelper.bytesToHex(md.digest(kd.getBytes(Charset
.defaultCharset())));
final String saslString = "username=\"" + account.getUsername()
+ "\",realm=\"" + account.getServer() + "\",nonce=\""
+ nonce + "\",cnonce=\"" + cNonce + "\",nc=" + nonceCount
+ ",qop=auth,digest-uri=\"" + digestUri + "\",response="
+ response + ",charset=utf-8";
encodedResponse = Base64.encodeToString(
saslString.getBytes(Charset.defaultCharset()),
Base64.NO_WRAP);
} catch (final NoSuchAlgorithmException e) {
return "";
}
return encodedResponse; @Override
} public String getResponse(final String challenge) throws AuthenticationException {
switch (state) {
case INITIAL:
state = State.RESPONSE_SENT;
final String encodedResponse;
try {
final Tokenizer tokenizer = new Tokenizer(Base64.decode(challenge, Base64.DEFAULT));
String nonce = "";
for (final String token : tokenizer) {
final String[] parts = token.split("=");
if (parts[0].equals("nonce")) {
nonce = parts[1].replace("\"", "");
} else if (parts[0].equals("rspauth")) {
return "";
}
}
final String digestUri = "xmpp/" + account.getServer();
final String nonceCount = "00000001";
final String x = account.getUsername() + ":" + account.getServer() + ":"
+ account.getPassword();
final MessageDigest md = MessageDigest.getInstance("MD5");
final byte[] y = md.digest(x.getBytes(Charset.defaultCharset()));
final String cNonce = new BigInteger(100, rng).toString(32);
final byte[] a1 = CryptoHelper.concatenateByteArrays(y,
(":" + nonce + ":" + cNonce).getBytes(Charset.defaultCharset()));
final String a2 = "AUTHENTICATE:" + digestUri;
final String ha1 = CryptoHelper.bytesToHex(md.digest(a1));
final String ha2 = CryptoHelper.bytesToHex(md.digest(a2.getBytes(Charset
.defaultCharset())));
final String kd = ha1 + ":" + nonce + ":" + nonceCount + ":" + cNonce
+ ":auth:" + ha2;
final String response = CryptoHelper.bytesToHex(md.digest(kd.getBytes(Charset
.defaultCharset())));
final String saslString = "username=\"" + account.getUsername()
+ "\",realm=\"" + account.getServer() + "\",nonce=\""
+ nonce + "\",cnonce=\"" + cNonce + "\",nc=" + nonceCount
+ ",qop=auth,digest-uri=\"" + digestUri + "\",response="
+ response + ",charset=utf-8";
encodedResponse = Base64.encodeToString(
saslString.getBytes(Charset.defaultCharset()),
Base64.NO_WRAP);
} catch (final NoSuchAlgorithmException e) {
throw new AuthenticationException(e);
}
return encodedResponse;
case RESPONSE_SENT:
state = State.VALID_SERVER_RESPONSE;
break;
default:
throw new InvalidStateException(state);
}
return null;
}
} }

View File

@ -8,18 +8,17 @@ import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.xml.TagWriter; import eu.siacs.conversations.xml.TagWriter;
public class Plain extends SaslMechanism { public class Plain extends SaslMechanism {
public Plain(final TagWriter tagWriter, final Account account) { public Plain(final TagWriter tagWriter, final Account account) {
super(tagWriter, account, null); super(tagWriter, account, null);
} }
@Override public static String getMechanism() {
public String getMechanism() { return "PLAIN";
return "PLAIN"; }
}
@Override @Override
public String getStartAuth() { public String getClientFirstMessage() {
final String sasl = '\u0000' + account.getUsername() + '\u0000' + account.getPassword(); final String sasl = '\u0000' + account.getUsername() + '\u0000' + account.getPassword();
return Base64.encodeToString(sasl.getBytes(Charset.defaultCharset()), Base64.NO_WRAP); return Base64.encodeToString(sasl.getBytes(Charset.defaultCharset()), Base64.NO_WRAP);
} }
} }

View File

@ -7,21 +7,47 @@ import eu.siacs.conversations.xml.TagWriter;
public abstract class SaslMechanism { public abstract class SaslMechanism {
final protected TagWriter tagWriter; final protected TagWriter tagWriter;
final protected Account account; final protected Account account;
final protected SecureRandom rng; final protected SecureRandom rng;
public SaslMechanism(final TagWriter tagWriter, final Account account, final SecureRandom rng) { protected static enum State {
this.tagWriter = tagWriter; INITIAL,
this.account = account; AUTH_TEXT_SENT,
this.rng = rng; RESPONSE_SENT,
} VALID_SERVER_RESPONSE,
}
public abstract String getMechanism(); public static class AuthenticationException extends Exception {
public String getStartAuth() { public AuthenticationException(final String message) {
return ""; super(message);
} }
public String getResponse(final String challenge) {
return ""; public AuthenticationException(final Exception inner) {
} super(inner);
}
}
public static class InvalidStateException extends AuthenticationException {
public InvalidStateException(final String message) {
super(message);
}
public InvalidStateException(final State state) {
this("Invalid state: " + state.toString());
}
}
public SaslMechanism(final TagWriter tagWriter, final Account account, final SecureRandom rng) {
this.tagWriter = tagWriter;
this.account = account;
this.rng = rng;
}
public String getClientFirstMessage() {
return "";
}
public String getResponse(final String challenge) throws AuthenticationException {
return "";
}
} }

View File

@ -0,0 +1,189 @@
package eu.siacs.conversations.crypto.sasl;
import android.util.Base64;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.macs.HMac;
import org.bouncycastle.crypto.params.KeyParameter;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.SecureRandom;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.xml.TagWriter;
public class ScramSha1 extends SaslMechanism {
// TODO: When channel binding (SCRAM-SHA1-PLUS) is supported in future, generalize this to indicate support and/or usage.
final private static String GS2_HEADER = "n,,";
private String clientFirstMessageBare;
private byte[] serverFirstMessage;
final private String clientNonce;
private byte[] serverSignature = null;
private static HMac HMAC;
private static Digest DIGEST;
private static final byte[] CLIENT_KEY_BYTES = "Client Key".getBytes();
private static final byte[] SERVER_KEY_BYTES = "Server Key".getBytes();
static {
DIGEST = new SHA1Digest();
HMAC = new HMac(new SHA1Digest());
}
private State state = State.INITIAL;
public ScramSha1(final TagWriter tagWriter, final Account account, final SecureRandom rng) {
super(tagWriter, account, rng);
// This nonce should be different for each authentication attempt.
clientNonce = new BigInteger(100, this.rng).toString(32);
clientFirstMessageBare = "";
}
public static String getMechanism() {
return "SCRAM-SHA-1";
}
@Override
public String getClientFirstMessage() {
if (clientFirstMessageBare.isEmpty() && state == State.INITIAL) {
clientFirstMessageBare = "n=" + CryptoHelper.saslPrep(account.getUsername()) +
",r=" + this.clientNonce;
state = State.AUTH_TEXT_SENT;
}
return Base64.encodeToString(
(GS2_HEADER + clientFirstMessageBare).getBytes(Charset.defaultCharset()),
Base64.NO_WRAP);
}
@Override
public String getResponse(final String challenge) throws AuthenticationException {
switch (state) {
case AUTH_TEXT_SENT:
serverFirstMessage = Base64.decode(challenge, Base64.DEFAULT);
final Tokenizer tokenizer = new Tokenizer(serverFirstMessage);
String nonce = "";
int iterationCount = -1;
String salt = "";
for (final String token : tokenizer) {
if (token.charAt(1) == '=') {
switch (token.charAt(0)) {
case 'i':
try {
iterationCount = Integer.parseInt(token.substring(2));
} catch (final NumberFormatException e) {
throw new AuthenticationException(e);
}
break;
case 's':
salt = token.substring(2);
break;
case 'r':
nonce = token.substring(2);
break;
case 'm':
/*
* RFC 5802:
* m: This attribute is reserved for future extensibility. In this
* version of SCRAM, its presence in a client or a server message
* MUST cause authentication failure when the attribute is parsed by
* the other end.
*/
throw new AuthenticationException("Server sent reserved token: `m'");
}
}
}
if (iterationCount < 0) {
throw new AuthenticationException("Server did not send iteration count");
}
if (nonce.isEmpty() || !nonce.startsWith(clientNonce)) {
throw new AuthenticationException("Server nonce does not contain client nonce: " + nonce);
}
if (salt.isEmpty()) {
throw new AuthenticationException("Server sent empty salt");
}
final String clientFinalMessageWithoutProof = "c=" + Base64.encodeToString(
GS2_HEADER.getBytes(), Base64.NO_WRAP) + ",r=" + nonce;
final byte[] authMessage = (clientFirstMessageBare + ',' + new String(serverFirstMessage) + ','
+ clientFinalMessageWithoutProof).getBytes();
// TODO: In future, cache the clientKey and serverKey and re-use them on re-auth.
final byte[] saltedPassword, clientSignature, serverKey, clientKey;
try {
saltedPassword = hi(CryptoHelper.saslPrep(account.getPassword()).getBytes(),
Base64.decode(salt, Base64.DEFAULT), iterationCount);
serverKey = hmac(saltedPassword, SERVER_KEY_BYTES);
serverSignature = hmac(serverKey, authMessage);
clientKey = hmac(saltedPassword, CLIENT_KEY_BYTES);
final byte[] storedKey = digest(clientKey);
clientSignature = hmac(storedKey, authMessage);
} catch (final InvalidKeyException e) {
throw new AuthenticationException(e);
}
final byte[] clientProof = new byte[clientKey.length];
for (int i = 0; i < clientProof.length; i++) {
clientProof[i] = (byte) (clientKey[i] ^ clientSignature[i]);
}
final String clientFinalMessage = clientFinalMessageWithoutProof + ",p=" +
Base64.encodeToString(clientProof, Base64.NO_WRAP);
state = State.RESPONSE_SENT;
return Base64.encodeToString(clientFinalMessage.getBytes(), Base64.NO_WRAP);
case RESPONSE_SENT:
final String clientCalculatedServerFinalMessage = "v=" +
Base64.encodeToString(serverSignature, Base64.NO_WRAP);
if (!clientCalculatedServerFinalMessage.equals(new String(Base64.decode(challenge, Base64.DEFAULT)))) {
throw new AuthenticationException("Server final message does not match calculated final message");
}
state = State.VALID_SERVER_RESPONSE;
return "";
default:
throw new InvalidStateException(state);
}
}
public static synchronized byte[] hmac(final byte[] key, final byte[] input)
throws InvalidKeyException {
HMAC.init(new KeyParameter(key));
HMAC.update(input, 0, input.length);
final byte[] out = new byte[HMAC.getMacSize()];
HMAC.doFinal(out, 0);
return out;
}
public static synchronized byte[] digest(byte[] bytes) {
DIGEST.reset();
DIGEST.update(bytes, 0, bytes.length);
final byte[] out = new byte[DIGEST.getDigestSize()];
DIGEST.doFinal(out, 0);
return out;
}
/*
* Hi() is, essentially, PBKDF2 [RFC2898] with HMAC() as the
* pseudorandom function (PRF) and with dkLen == output length of
* HMAC() == output length of H().
*/
private static synchronized byte[] hi(final byte[] key, final byte[] salt, final int iterations)
throws InvalidKeyException {
byte[] u = hmac(key, CryptoHelper.concatenateByteArrays(salt, CryptoHelper.ONE));
byte[] out = u.clone();
for (int i = 1; i < iterations; i++) {
u = hmac(key, u);
for (int j = 0; j < u.length; j++) {
out[j] ^= u[j];
}
}
return out;
}
}

View File

@ -0,0 +1,76 @@
package eu.siacs.conversations.crypto.sasl;
import android.util.Base64;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
/**
* A tokenizer for GS2 header strings
*/
public final class Tokenizer implements Iterator<String>, Iterable<String> {
private final List<String> parts;
private int index;
public Tokenizer(final byte[] challenge) {
final String challengeString = new String(challenge);
parts = new ArrayList<>(Arrays.asList(challengeString.split(",")));
index = 0;
}
/**
* Returns true if there is at least one more element, false otherwise.
*
* @see #next
*/
@Override
public boolean hasNext() {
return parts.size() != index + 1;
}
/**
* Returns the next object and advances the iterator.
*
* @return the next object.
* @throws java.util.NoSuchElementException if there are no more elements.
* @see #hasNext
*/
@Override
public String next() {
if (hasNext()) {
return parts.get(index++);
} else {
throw new NoSuchElementException("No such element. Size is: " + parts.size());
}
}
/**
* Removes the last object returned by {@code next} from the collection.
* This method can only be called once between each call to {@code next}.
*
* @throws UnsupportedOperationException if removing is not supported by the collection being
* iterated.
* @throws IllegalStateException if {@code next} has not been called, or {@code remove} has
* already been called after the last call to {@code next}.
*/
@Override
public void remove() {
if(index <= 0) {
throw new IllegalStateException("You can't delete an element before first next() method call");
}
parts.remove(--index);
}
/**
* Returns an {@link java.util.Iterator} for the elements in this object.
*
* @return An {@code Iterator} instance.
*/
@Override
public Iterator<String> iterator() {
return parts.iterator();
}
}

View File

@ -1,13 +1,14 @@
package eu.siacs.conversations.utils; package eu.siacs.conversations.utils;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.text.Normalizer;
public class CryptoHelper { public class CryptoHelper {
public static final String FILETRANSFER = "?FILETRANSFERv1:"; public static final String FILETRANSFER = "?FILETRANSFERv1:";
final protected static char[] hexArray = "0123456789abcdef".toCharArray(); final protected static char[] hexArray = "0123456789abcdef".toCharArray();
final protected static char[] vowels = "aeiou".toCharArray(); final protected static char[] vowels = "aeiou".toCharArray();
final protected static char[] consonants = "bcdfghjklmnpqrstvwxyz" final protected static char[] consonants = "bcdfghjklmnpqrstvwxyz".toCharArray();
.toCharArray(); final public static byte[] ONE = new byte[] { 0, 0, 0, 1 };
public static String bytesToHex(byte[] bytes) { public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2]; char[] hexChars = new char[bytes.length * 2];
@ -51,4 +52,30 @@ public class CryptoHelper {
} }
return builder.toString(); return builder.toString();
} }
/**
* Escapes usernames or passwords for SASL.
*/
public static String saslEscape(final String s) {
final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ',':
sb.append("=2C");
break;
case '=':
sb.append("=3D");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
public static String saslPrep(final String s) {
return saslEscape(Normalizer.normalize(s, Normalizer.Form.NFKC));
}
} }

View File

@ -42,6 +42,7 @@ import eu.siacs.conversations.Config;
import eu.siacs.conversations.crypto.sasl.DigestMd5; import eu.siacs.conversations.crypto.sasl.DigestMd5;
import eu.siacs.conversations.crypto.sasl.Plain; import eu.siacs.conversations.crypto.sasl.Plain;
import eu.siacs.conversations.crypto.sasl.SaslMechanism; import eu.siacs.conversations.crypto.sasl.SaslMechanism;
import eu.siacs.conversations.crypto.sasl.ScramSha1;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.services.XmppConnectionService; import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.DNSHelper; import eu.siacs.conversations.utils.DNSHelper;
@ -106,12 +107,12 @@ public class XmppConnection implements Runnable {
private OnMessageAcknowledged acknowledgedListener = null; private OnMessageAcknowledged acknowledgedListener = null;
private XmppConnectionService mXmppConnectionService = null; private XmppConnectionService mXmppConnectionService = null;
private SaslMechanism saslMechanism; private SaslMechanism saslMechanism;
public XmppConnection(Account account, XmppConnectionService service) { public XmppConnection(Account account, XmppConnectionService service) {
this.account = account; this.account = account;
this.wakeLock = service.getPowerManager().newWakeLock( this.wakeLock = service.getPowerManager().newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString()); PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
tagWriter = new TagWriter(); tagWriter = new TagWriter();
mXmppConnectionService = service; mXmppConnectionService = service;
applicationContext = service.getApplicationContext(); applicationContext = service.getApplicationContext();
@ -124,7 +125,7 @@ public class XmppConnection implements Runnable {
&& (account.getStatus() != Account.STATUS_ONLINE) && (account.getStatus() != Account.STATUS_ONLINE)
&& (account.getStatus() != Account.STATUS_DISABLED)) { && (account.getStatus() != Account.STATUS_DISABLED)) {
return; return;
} }
if (nextStatus == Account.STATUS_ONLINE) { if (nextStatus == Account.STATUS_ONLINE) {
this.attempt = 0; this.attempt = 0;
} }
@ -144,7 +145,7 @@ public class XmppConnection implements Runnable {
this.attempt++; this.attempt++;
try { try {
shouldAuthenticate = shouldBind = !account shouldAuthenticate = shouldBind = !account
.isOptionSet(Account.OPTION_REGISTER); .isOptionSet(Account.OPTION_REGISTER);
tagReader = new XmlReader(wakeLock); tagReader = new XmlReader(wakeLock);
tagWriter = new TagWriter(); tagWriter = new TagWriter();
packetCallbacks.clear(); packetCallbacks.clear();
@ -162,12 +163,12 @@ public class XmppConnection implements Runnable {
Bundle namePort = (Bundle) values.get(i); Bundle namePort = (Bundle) values.get(i);
try { try {
String srvRecordServer; String srvRecordServer;
try { try {
srvRecordServer=IDN.toASCII(namePort.getString("name")); srvRecordServer=IDN.toASCII(namePort.getString("name"));
} catch (final IllegalArgumentException e) { } catch (final IllegalArgumentException e) {
// TODO: Handle me?` // TODO: Handle me?`
srvRecordServer = ""; srvRecordServer = "";
} }
int srvRecordPort = namePort.getInt("port"); int srvRecordPort = namePort.getInt("port");
String srvIpServer = namePort.getString("ipv4"); String srvIpServer = namePort.getString("ipv4");
InetSocketAddress addr; InetSocketAddress addr;
@ -240,7 +241,7 @@ public class XmppConnection implements Runnable {
} catch (final RuntimeException ignored) { } catch (final RuntimeException ignored) {
} }
} }
} catch (final IOException | XmlPullParserException e) { } catch (final IOException | XmlPullParserException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage()); Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.STATUS_OFFLINE); this.changeStatus(Account.STATUS_OFFLINE);
if (wakeLock.isHeld()) { if (wakeLock.isHeld()) {
@ -249,7 +250,7 @@ public class XmppConnection implements Runnable {
} catch (final RuntimeException ignored) { } catch (final RuntimeException ignored) {
} }
} }
} catch (NoSuchAlgorithmException e) { } catch (NoSuchAlgorithmException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage()); Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
this.changeStatus(Account.STATUS_OFFLINE); this.changeStatus(Account.STATUS_OFFLINE);
Log.d(Config.LOGTAG, "compression exception " + e.getMessage()); Log.d(Config.LOGTAG, "compression exception " + e.getMessage());
@ -259,9 +260,9 @@ public class XmppConnection implements Runnable {
} catch (final RuntimeException ignored) { } catch (final RuntimeException ignored) {
} }
} }
} }
} }
@Override @Override
public void run() { public void run() {
@ -269,115 +270,127 @@ public class XmppConnection implements Runnable {
} }
private void processStream(final Tag currentTag) throws XmlPullParserException, private void processStream(final Tag currentTag) throws XmlPullParserException,
IOException, NoSuchAlgorithmException { IOException, NoSuchAlgorithmException {
Tag nextTag = tagReader.readTag(); Tag nextTag = tagReader.readTag();
while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
if (nextTag.isStart("error")) { while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
processStreamError(nextTag); if (nextTag.isStart("error")) {
} else if (nextTag.isStart("features")) { processStreamError(nextTag);
processStreamFeatures(nextTag); } else if (nextTag.isStart("features")) {
} else if (nextTag.isStart("proceed")) { processStreamFeatures(nextTag);
switchOverToTls(nextTag); } else if (nextTag.isStart("proceed")) {
} else if (nextTag.isStart("compressed")) { switchOverToTls(nextTag);
switchOverToZLib(nextTag); } else if (nextTag.isStart("compressed")) {
} else if (nextTag.isStart("success")) { switchOverToZLib(nextTag);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in"); } else if (nextTag.isStart("success")) {
tagReader.readTag(); final String challenge = tagReader.readElement(nextTag).getContent();
tagReader.reset(); try {
sendStartStream(); saslMechanism.getResponse(challenge);
processStream(tagReader.readTag()); } catch (final SaslMechanism.AuthenticationException e) {
break; disconnect(true);
} else if (nextTag.isStart("failure")) { Log.e(Config.LOGTAG, String.valueOf(e));
tagReader.readElement(nextTag); }
changeStatus(Account.STATUS_UNAUTHORIZED); Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
} else if (nextTag.isStart("challenge")) { tagReader.reset();
final String challenge = tagReader.readElement(nextTag).getContent(); sendStartStream();
final Element response = new Element("response"); processStream(tagReader.readTag());
response.setAttribute("xmlns", break;
"urn:ietf:params:xml:ns:xmpp-sasl"); } else if (nextTag.isStart("failure")) {
response.setContent(saslMechanism.getResponse(challenge)); tagReader.readElement(nextTag);
tagWriter.writeElement(response); changeStatus(Account.STATUS_UNAUTHORIZED);
} else if (nextTag.isStart("enabled")) { } else if (nextTag.isStart("challenge")) {
Element enabled = tagReader.readElement(nextTag); final String challenge = tagReader.readElement(nextTag).getContent();
if ("true".equals(enabled.getAttribute("resume"))) { final Element response = new Element("response");
this.streamId = enabled.getAttribute("id"); response.setAttribute("xmlns",
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() "urn:ietf:params:xml:ns:xmpp-sasl");
+ ": stream managment(" + smVersion try {
+ ") enabled (resumable)"); response.setContent(saslMechanism.getResponse(challenge));
} else { } catch (final SaslMechanism.AuthenticationException e) {
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() // TODO: Send auth abort tag.
+ ": stream managment(" + smVersion + ") enabled"); Log.e(Config.LOGTAG, e.toString());
} }
this.lastSessionStarted = SystemClock.elapsedRealtime(); tagWriter.writeElement(response);
this.stanzasReceived = 0; } else if (nextTag.isStart("enabled")) {
RequestPacket r = new RequestPacket(smVersion); Element enabled = tagReader.readElement(nextTag);
tagWriter.writeStanzaAsync(r); if ("true".equals(enabled.getAttribute("resume"))) {
} else if (nextTag.isStart("resumed")) { this.streamId = enabled.getAttribute("id");
lastPaketReceived = SystemClock.elapsedRealtime(); Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
Element resumed = tagReader.readElement(nextTag); + ": stream managment(" + smVersion
String h = resumed.getAttribute("h"); + ") enabled (resumable)");
try { } else {
int serverCount = Integer.parseInt(h); Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
if (serverCount != stanzasSent) { + ": stream managment(" + smVersion + ") enabled");
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() }
+ ": session resumed with lost packages"); this.lastSessionStarted = SystemClock.elapsedRealtime();
stanzasSent = serverCount; this.stanzasReceived = 0;
} else { RequestPacket r = new RequestPacket(smVersion);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() tagWriter.writeStanzaAsync(r);
+ ": session resumed"); } else if (nextTag.isStart("resumed")) {
} lastPaketReceived = SystemClock.elapsedRealtime();
if (acknowledgedListener != null) { Element resumed = tagReader.readElement(nextTag);
for (int i = 0; i < messageReceipts.size(); ++i) { String h = resumed.getAttribute("h");
if (serverCount >= messageReceipts.keyAt(i)) { try {
acknowledgedListener.onMessageAcknowledged( int serverCount = Integer.parseInt(h);
account, messageReceipts.valueAt(i)); 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");
}
if (acknowledgedListener != null) {
for (int i = 0; i < messageReceipts.size(); ++i) {
if (serverCount >= messageReceipts.keyAt(i)) {
acknowledgedListener.onMessageAcknowledged(
account, messageReceipts.valueAt(i));
}
}
}
messageReceipts.clear();
} catch (final NumberFormatException ignored) {
}
sendInitialPing();
} else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag);
AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) {
Element ack = tagReader.readElement(nextTag);
lastPaketReceived = SystemClock.elapsedRealtime();
int serverSequence = Integer.parseInt(ack.getAttribute("h"));
String msgId = this.messageReceipts.get(serverSequence);
if (msgId != null) {
if (this.acknowledgedListener != null) {
this.acknowledgedListener.onMessageAcknowledged(
account, msgId);
}
this.messageReceipts.remove(serverSequence);
}
} else if (nextTag.isStart("failed")) {
tagReader.readElement(nextTag);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
streamId = null;
if (account.getStatus() != Account.STATUS_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();
}
if (account.getStatus() == Account.STATUS_ONLINE) {
account. setStatus(Account.STATUS_OFFLINE);
if (statusListener != null) {
statusListener.onStatusChanged(account);
} }
} }
}
messageReceipts.clear();
} catch (final NumberFormatException ignored) {
}
sendInitialPing();
} else if (nextTag.isStart("r")) {
tagReader.readElement(nextTag);
AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
tagWriter.writeStanzaAsync(ack);
} else if (nextTag.isStart("a")) {
Element ack = tagReader.readElement(nextTag);
lastPaketReceived = SystemClock.elapsedRealtime();
int serverSequence = Integer.parseInt(ack.getAttribute("h"));
String msgId = this.messageReceipts.get(serverSequence);
if (msgId != null) {
if (this.acknowledgedListener != null) {
this.acknowledgedListener.onMessageAcknowledged(
account, msgId);
}
this.messageReceipts.remove(serverSequence);
}
} else if (nextTag.isStart("failed")) {
tagReader.readElement(nextTag);
Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
streamId = null;
if (account.getStatus() != Account.STATUS_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();
}
if (account.getStatus() == Account.STATUS_ONLINE) {
account. setStatus(Account.STATUS_OFFLINE);
if (statusListener != null) {
statusListener.onStatusChanged(account);
}
}
} }
private void sendInitialPing() { private void sendInitialPing() {
@ -397,7 +410,7 @@ public class XmppConnection implements Runnable {
} }
private Element processPacket(Tag currentTag, int packetType) private Element processPacket(Tag currentTag, int packetType)
throws XmlPullParserException, IOException { throws XmlPullParserException, IOException {
Element element; Element element;
switch (packetType) { switch (packetType) {
case PACKET_IQ: case PACKET_IQ:
@ -424,10 +437,10 @@ public class XmppConnection implements Runnable {
if (packetType == PACKET_IQ if (packetType == PACKET_IQ
&& "jingle".equals(child.getName()) && "jingle".equals(child.getName())
&& ("set".equalsIgnoreCase(type) || "get" && ("set".equalsIgnoreCase(type) || "get"
.equalsIgnoreCase(type))) { .equalsIgnoreCase(type))) {
element = new JinglePacket(); element = new JinglePacket();
element.setAttributes(currentTag.getAttributes()); element.setAttributes(currentTag.getAttributes());
} }
element.addChild(child); element.addChild(child);
} }
nextTag = tagReader.readTag(); nextTag = tagReader.readTag();
@ -441,64 +454,64 @@ public class XmppConnection implements Runnable {
} }
private void processIq(Tag currentTag) throws XmlPullParserException, private void processIq(Tag currentTag) throws XmlPullParserException,
IOException { IOException {
IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ); IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
if (packet.getId() == null) { if (packet.getId() == null) {
return; // an iq packet without id is definitely invalid return; // an iq packet without id is definitely invalid
} }
if (packet instanceof JinglePacket) { if (packet instanceof JinglePacket) {
if (this.jingleListener != null) { if (this.jingleListener != null) {
this.jingleListener.onJinglePacketReceived(account, this.jingleListener.onJinglePacketReceived(account,
(JinglePacket) packet); (JinglePacket) packet);
} }
} else { } else {
if (packetCallbacks.containsKey(packet.getId())) { if (packetCallbacks.containsKey(packet.getId())) {
if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) { if (packetCallbacks.get(packet.getId()) instanceof OnIqPacketReceived) {
((OnIqPacketReceived) packetCallbacks.get(packet.getId())) ((OnIqPacketReceived) packetCallbacks.get(packet.getId()))
.onIqPacketReceived(account, packet); .onIqPacketReceived(account, packet);
} }
packetCallbacks.remove(packet.getId()); packetCallbacks.remove(packet.getId());
} else if ((packet.getType() == IqPacket.TYPE_GET || packet } else if ((packet.getType() == IqPacket.TYPE_GET || packet
.getType() == IqPacket.TYPE_SET) .getType() == IqPacket.TYPE_SET)
&& this.unregisteredIqListener != null) { && this.unregisteredIqListener != null) {
this.unregisteredIqListener.onIqPacketReceived(account, packet); this.unregisteredIqListener.onIqPacketReceived(account, packet);
} }
} }
} }
private void processMessage(Tag currentTag) throws XmlPullParserException, private void processMessage(Tag currentTag) throws XmlPullParserException,
IOException { IOException {
MessagePacket packet = (MessagePacket) processPacket(currentTag, MessagePacket packet = (MessagePacket) processPacket(currentTag,
PACKET_MESSAGE); PACKET_MESSAGE);
String id = packet.getAttribute("id"); String id = packet.getAttribute("id");
if ((id != null) && (packetCallbacks.containsKey(id))) { if ((id != null) && (packetCallbacks.containsKey(id))) {
if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) { if (packetCallbacks.get(id) instanceof OnMessagePacketReceived) {
((OnMessagePacketReceived) packetCallbacks.get(id)) ((OnMessagePacketReceived) packetCallbacks.get(id))
.onMessagePacketReceived(account, packet); .onMessagePacketReceived(account, packet);
} }
packetCallbacks.remove(id); packetCallbacks.remove(id);
} else if (this.messageListener != null) { } else if (this.messageListener != null) {
this.messageListener.onMessagePacketReceived(account, packet); this.messageListener.onMessagePacketReceived(account, packet);
} }
} }
private void processPresence(Tag currentTag) throws XmlPullParserException, private void processPresence(Tag currentTag) throws XmlPullParserException,
IOException { IOException {
PresencePacket packet = (PresencePacket) processPacket(currentTag, PresencePacket packet = (PresencePacket) processPacket(currentTag,
PACKET_PRESENCE); PACKET_PRESENCE);
String id = packet.getAttribute("id"); String id = packet.getAttribute("id");
if ((id != null) && (packetCallbacks.containsKey(id))) { if ((id != null) && (packetCallbacks.containsKey(id))) {
if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) { if (packetCallbacks.get(id) instanceof OnPresencePacketReceived) {
((OnPresencePacketReceived) packetCallbacks.get(id)) ((OnPresencePacketReceived) packetCallbacks.get(id))
.onPresencePacketReceived(account, packet); .onPresencePacketReceived(account, packet);
} }
packetCallbacks.remove(id); packetCallbacks.remove(id);
} else if (this.presenceListener != null) { } else if (this.presenceListener != null) {
this.presenceListener.onPresencePacketReceived(account, packet); this.presenceListener.onPresencePacketReceived(account, packet);
} }
} }
private void sendCompressionZlib() throws IOException { private void sendCompressionZlib() throws IOException {
@ -509,18 +522,18 @@ public class XmppConnection implements Runnable {
} }
private void switchOverToZLib(final Tag currentTag) private void switchOverToZLib(final Tag currentTag)
throws XmlPullParserException, IOException, throws XmlPullParserException, IOException,
NoSuchAlgorithmException { NoSuchAlgorithmException {
tagReader.readTag(); // read tag close tagReader.readTag(); // read tag close
tagWriter.setOutputStream(new ZLibOutputStream(tagWriter tagWriter.setOutputStream(new ZLibOutputStream(tagWriter
.getOutputStream())); .getOutputStream()));
tagReader tagReader
.setInputStream(new ZLibInputStream(tagReader.getInputStream())); .setInputStream(new ZLibInputStream(tagReader.getInputStream()));
sendStartStream(); sendStartStream();
Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": compression enabled"); Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": compression enabled");
usingCompression = true; usingCompression = true;
processStream(tagReader.readTag()); processStream(tagReader.readTag());
} }
private void sendStartTLS() throws IOException { private void sendStartTLS() throws IOException {
@ -531,7 +544,7 @@ public class XmppConnection implements Runnable {
private SharedPreferences getPreferences() { private SharedPreferences getPreferences() {
return PreferenceManager return PreferenceManager
.getDefaultSharedPreferences(applicationContext); .getDefaultSharedPreferences(applicationContext);
} }
private boolean enableLegacySSL() { private boolean enableLegacySSL() {
@ -539,64 +552,64 @@ public class XmppConnection implements Runnable {
} }
private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, private void switchOverToTls(final Tag currentTag) throws XmlPullParserException,
IOException { IOException {
tagReader.readTag(); tagReader.readTag();
try { try {
SSLContext sc = SSLContext.getInstance("TLS"); SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, sc.init(null,
new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()}, new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},
mXmppConnectionService.getRNG()); mXmppConnectionService.getRNG());
SSLSocketFactory factory = sc.getSocketFactory(); SSLSocketFactory factory = sc.getSocketFactory();
if (factory == null) { if (factory == null) {
throw new IOException("SSLSocketFactory was null"); throw new IOException("SSLSocketFactory was null");
} }
final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier()); final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
if (socket == null) { if (socket == null) {
throw new IOException("socket was null"); throw new IOException("socket was null");
} }
final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket, final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,
socket.getInetAddress().getHostAddress(), socket.getPort(), socket.getInetAddress().getHostAddress(), socket.getPort(),
true); true);
// Support all protocols except legacy SSL. // Support all protocols except legacy SSL.
// The min SDK version prevents us having to worry about SSLv2. In // The min SDK version prevents us having to worry about SSLv2. In
// future, this may be true of SSLv3 as well. // future, this may be true of SSLv3 as well.
final String[] supportProtocols; final String[] supportProtocols;
if (enableLegacySSL()) { if (enableLegacySSL()) {
supportProtocols = sslSocket.getSupportedProtocols(); supportProtocols = sslSocket.getSupportedProtocols();
} else { } else {
final List<String> supportedProtocols = new LinkedList<>( final List<String> supportedProtocols = new LinkedList<>(
Arrays.asList(sslSocket.getSupportedProtocols())); Arrays.asList(sslSocket.getSupportedProtocols()));
supportedProtocols.remove("SSLv3"); supportedProtocols.remove("SSLv3");
supportProtocols = new String[supportedProtocols.size()]; supportProtocols = new String[supportedProtocols.size()];
supportedProtocols.toArray(supportProtocols); supportedProtocols.toArray(supportProtocols);
} }
sslSocket.setEnabledProtocols(supportProtocols); sslSocket.setEnabledProtocols(supportProtocols);
if (verifier != null if (verifier != null
&& !verifier.verify(account.getServer().getDomainpart(), && !verifier.verify(account.getServer().getDomainpart(),
sslSocket.getSession())) { sslSocket.getSession())) {
sslSocket.close(); sslSocket.close();
throw new IOException("host mismatch in TLS connection"); throw new IOException("host mismatch in TLS connection");
} }
tagReader.setInputStream(sslSocket.getInputStream()); tagReader.setInputStream(sslSocket.getInputStream());
tagWriter.setOutputStream(sslSocket.getOutputStream()); tagWriter.setOutputStream(sslSocket.getOutputStream());
sendStartStream(); sendStartStream();
Log.d(Config.LOGTAG, account.getJid().toBareJid() Log.d(Config.LOGTAG, account.getJid().toBareJid()
+ ": TLS connection established"); + ": TLS connection established");
usingEncryption = true; usingEncryption = true;
processStream(tagReader.readTag()); processStream(tagReader.readTag());
sslSocket.close(); sslSocket.close();
} catch (final NoSuchAlgorithmException | KeyManagementException e1) { } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
e1.printStackTrace(); e1.printStackTrace();
} }
} }
private void processStreamFeatures(Tag currentTag) private void processStreamFeatures(Tag currentTag)
throws XmlPullParserException, IOException { throws XmlPullParserException, IOException {
this.streamFeatures = tagReader.readElement(currentTag); this.streamFeatures = tagReader.readElement(currentTag);
if (this.streamFeatures.hasChild("starttls") && !usingEncryption) { if (this.streamFeatures.hasChild("starttls") && !usingEncryption) {
sendStartTLS(); sendStartTLS();
@ -614,18 +627,27 @@ public class XmppConnection implements Runnable {
&& shouldAuthenticate && usingEncryption) { && shouldAuthenticate && usingEncryption) {
final List<String> mechanisms = extractMechanisms(streamFeatures final List<String> mechanisms = extractMechanisms(streamFeatures
.findChild("mechanisms")); .findChild("mechanisms"));
final Element auth = new Element("auth"); final Element auth = new Element("auth");
auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl"); auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
if (mechanisms.contains("DIGEST-MD5")) { if (mechanisms.contains(ScramSha1.getMechanism())) {
saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG()); saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
} else if (mechanisms.contains("PLAIN")) { Log.d(Config.LOGTAG, "Authenticating with " + ScramSha1.getMechanism());
saslMechanism = new Plain(tagWriter, account); auth.setAttribute("mechanism", ScramSha1.getMechanism());
auth.setContent(((Plain)saslMechanism).getStartAuth()); } else if (mechanisms.contains(DigestMd5.getMechanism())) {
Log.d(Config.LOGTAG, "Authenticating with " + DigestMd5.getMechanism());
saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
auth.setAttribute("mechanism", DigestMd5.getMechanism());
} else if (mechanisms.contains(Plain.getMechanism())) {
Log.d(Config.LOGTAG, "Authenticating with " + Plain.getMechanism());
saslMechanism = new Plain(tagWriter, account);
auth.setAttribute("mechanism", Plain.getMechanism());
}
if (!saslMechanism.getClientFirstMessage().isEmpty()) {
auth.setContent(saslMechanism.getClientFirstMessage());
} }
auth.setAttribute("mechanism", saslMechanism.getMechanism());
tagWriter.writeElement(auth); tagWriter.writeElement(auth);
} else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
+ smVersion) + smVersion)
&& streamId != null) { && streamId != null) {
ResumePacket resume = new ResumePacket(this.streamId, ResumePacket resume = new ResumePacket(this.streamId,
stanzasReceived, smVersion); stanzasReceived, smVersion);
@ -641,7 +663,7 @@ public class XmppConnection implements Runnable {
private boolean compressionAvailable() { private boolean compressionAvailable() {
if (!this.streamFeatures.hasChild("compression", if (!this.streamFeatures.hasChild("compression",
"http://jabber.org/features/compress")) "http://jabber.org/features/compress"))
return false; return false;
if (!ZLibOutputStream.SUPPORTED) if (!ZLibOutputStream.SUPPORTED)
return false; return false;
@ -683,23 +705,23 @@ public class XmppConnection implements Runnable {
&& (packet.query().hasChild("password"))) { && (packet.query().hasChild("password"))) {
IqPacket register = new IqPacket(IqPacket.TYPE_SET); IqPacket register = new IqPacket(IqPacket.TYPE_SET);
Element username = new Element("username") Element username = new Element("username")
.setContent(account.getUsername()); .setContent(account.getUsername());
Element password = new Element("password") Element password = new Element("password")
.setContent(account.getPassword()); .setContent(account.getPassword());
register.query("jabber:iq:register").addChild(username); register.query("jabber:iq:register").addChild(username);
register.query().addChild(password); register.query().addChild(password);
sendIqPacket(register, new OnIqPacketReceived() { sendIqPacket(register, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, public void onIqPacketReceived(Account account,
IqPacket packet) { IqPacket packet) {
if (packet.getType() == IqPacket.TYPE_RESULT) { if (packet.getType() == IqPacket.TYPE_RESULT) {
account.setOption(Account.OPTION_REGISTER, account.setOption(Account.OPTION_REGISTER,
false); false);
changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL); changeStatus(Account.STATUS_REGISTRATION_SUCCESSFULL);
} else if (packet.hasChild("error") } else if (packet.hasChild("error")
&& (packet.findChild("error") && (packet.findChild("error")
.hasChild("conflict"))) { .hasChild("conflict"))) {
changeStatus(Account.STATUS_REGISTRATION_CONFLICT); changeStatus(Account.STATUS_REGISTRATION_CONFLICT);
} else { } else {
changeStatus(Account.STATUS_REGISTRATION_FAILED); changeStatus(Account.STATUS_REGISTRATION_FAILED);
@ -722,7 +744,7 @@ public class XmppConnection implements Runnable {
private void sendBindRequest() throws IOException { private void sendBindRequest() throws IOException {
IqPacket iq = new IqPacket(IqPacket.TYPE_SET); IqPacket iq = new IqPacket(IqPacket.TYPE_SET);
iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind") iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
.addChild("resource").setContent(account.getResource()); .addChild("resource").setContent(account.getResource());
this.sendUnboundIqPacket(iq, new OnIqPacketReceived() { this.sendUnboundIqPacket(iq, new OnIqPacketReceived() {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
@ -730,19 +752,19 @@ public class XmppConnection implements Runnable {
if (bind != null) { if (bind != null) {
final Element jid = bind.findChild("jid"); final Element jid = bind.findChild("jid");
if (jid != null && jid.getContent() != null) { if (jid != null && jid.getContent() != null) {
try { try {
account.setResource(Jid.fromString(jid.getContent()).getResourcepart()); account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
} catch (final InvalidJidException e) { } catch (final InvalidJidException e) {
// TODO: Handle the case where an external JID is technically invalid? // TODO: Handle the case where an external JID is technically invalid?
} }
if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) { if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
smVersion = 3; smVersion = 3;
EnablePacket enable = new EnablePacket(smVersion); EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable); tagWriter.writeStanzaAsync(enable);
stanzasSent = 0; stanzasSent = 0;
messageReceipts.clear(); messageReceipts.clear();
} else if (streamFeatures.hasChild("sm", } else if (streamFeatures.hasChild("sm",
"urn:xmpp:sm:2")) { "urn:xmpp:sm:2")) {
smVersion = 2; smVersion = 2;
EnablePacket enable = new EnablePacket(smVersion); EnablePacket enable = new EnablePacket(smVersion);
tagWriter.writeStanzaAsync(enable); tagWriter.writeStanzaAsync(enable);
@ -783,11 +805,11 @@ public class XmppConnection implements Runnable {
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
final List<Element> elements = packet.query().getChildren(); final List<Element> elements = packet.query().getChildren();
final List<String> features = new ArrayList<>(); final List<String> features = new ArrayList<>();
for (Element element : elements) { for (Element element : elements) {
if (element.getName().equals("feature")) { if (element.getName().equals("feature")) {
features.add(element.getAttribute("var")); features.add(element.getAttribute("var"));
} }
} }
disco.put(server.toDomainJid().toString(), features); disco.put(server.toDomainJid().toString(), features);
if (account.getServer().equals(server.toDomainJid())) { if (account.getServer().equals(server.toDomainJid())) {
@ -812,16 +834,16 @@ public class XmppConnection implements Runnable {
@Override @Override
public void onIqPacketReceived(Account account, IqPacket packet) { public void onIqPacketReceived(Account account, IqPacket packet) {
List<Element> elements = packet.query().getChildren(); List<Element> elements = packet.query().getChildren();
for (Element element : elements) { for (Element element : elements) {
if (element.getName().equals("item")) { if (element.getName().equals("item")) {
final String jid = element.getAttribute("jid"); final String jid = element.getAttribute("jid");
try { try {
sendServiceDiscoveryInfo(Jid.fromString(jid).toDomainJid()); sendServiceDiscoveryInfo(Jid.fromString(jid).toDomainJid());
} catch (final InvalidJidException ignored) { } catch (final InvalidJidException ignored) {
// TODO: Handle the case where an external JID is technically invalid? // TODO: Handle the case where an external JID is technically invalid?
} }
} }
} }
} }
}); });
} }
@ -845,14 +867,14 @@ public class XmppConnection implements Runnable {
} }
private void processStreamError(Tag currentTag) private void processStreamError(Tag currentTag)
throws XmlPullParserException, IOException { throws XmlPullParserException, IOException {
Element streamError = tagReader.readElement(currentTag); Element streamError = tagReader.readElement(currentTag);
if (streamError != null && streamError.hasChild("conflict")) { if (streamError != null && streamError.hasChild("conflict")) {
final String resource = account.getResource().split("\\.")[0]; final String resource = account.getResource().split("\\.")[0];
account.setResource(resource + "." + nextRandomId()); account.setResource(resource + "." + nextRandomId());
Log.d(Config.LOGTAG, Log.d(Config.LOGTAG,
account.getJid().toBareJid() + ": switching resource due to conflict (" account.getJid().toBareJid() + ": switching resource due to conflict ("
+ account.getResource() + ")"); + account.getResource() + ")");
} }
} }
@ -897,11 +919,11 @@ public class XmppConnection implements Runnable {
} }
private synchronized void sendPacket(final AbstractStanza packet, private synchronized void sendPacket(final AbstractStanza packet,
PacketReceived callback) { PacketReceived callback) {
if (packet.getName().equals("iq") || packet.getName().equals("message") if (packet.getName().equals("iq") || packet.getName().equals("message")
|| packet.getName().equals("presence")) { || packet.getName().equals("presence")) {
++stanzasSent; ++stanzasSent;
} }
tagWriter.writeStanzaAsync(packet); tagWriter.writeStanzaAsync(packet);
if (packet instanceof MessagePacket && packet.getId() != null if (packet instanceof MessagePacket && packet.getId() != null
&& this.streamId != null) { && this.streamId != null) {
@ -909,7 +931,7 @@ public class XmppConnection implements Runnable {
+ stanzasSent); + stanzasSent);
this.messageReceipts.put(stanzasSent, packet.getId()); this.messageReceipts.put(stanzasSent, packet.getId());
tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion)); tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
} }
if (callback != null) { if (callback != null) {
if (packet.getId() == null) { if (packet.getId() == null) {
packet.setId(nextRandomId()); packet.setId(nextRandomId());
@ -933,22 +955,22 @@ public class XmppConnection implements Runnable {
public void setOnMessagePacketReceivedListener( public void setOnMessagePacketReceivedListener(
OnMessagePacketReceived listener) { OnMessagePacketReceived listener) {
this.messageListener = listener; this.messageListener = listener;
} }
public void setOnUnregisteredIqPacketReceivedListener( public void setOnUnregisteredIqPacketReceivedListener(
OnIqPacketReceived listener) { OnIqPacketReceived listener) {
this.unregisteredIqListener = listener; this.unregisteredIqListener = listener;
} }
public void setOnPresencePacketReceivedListener( public void setOnPresencePacketReceivedListener(
OnPresencePacketReceived listener) { OnPresencePacketReceived listener) {
this.presenceListener = listener; this.presenceListener = listener;
} }
public void setOnJinglePacketReceivedListener( public void setOnJinglePacketReceivedListener(
OnJinglePacketReceived listener) { OnJinglePacketReceived listener) {
this.jingleListener = listener; this.jingleListener = listener;
} }
public void setOnStatusChangedListener(OnStatusChanged listener) { public void setOnStatusChangedListener(OnStatusChanged listener) {
this.statusListener = listener; this.statusListener = listener;
@ -1074,9 +1096,9 @@ public class XmppConnection implements Runnable {
} }
private boolean hasDiscoFeature(final Jid server, final String feature) { private boolean hasDiscoFeature(final Jid server, final String feature) {
return connection.disco.containsKey(server.toDomainJid().toString()) && return connection.disco.containsKey(server.toDomainJid().toString()) &&
connection.disco.get(server.toDomainJid().toString()).contains(feature); connection.disco.get(server.toDomainJid().toString()).contains(feature);
} }
public boolean carbons() { public boolean carbons() {
return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2"); return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
@ -1087,7 +1109,7 @@ public class XmppConnection implements Runnable {
} }
public boolean csi() { public boolean csi() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0"); return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
} }
public boolean pubsub() { public boolean pubsub() {
@ -1100,12 +1122,12 @@ public class XmppConnection implements Runnable {
} }
public boolean rosterVersioning() { public boolean rosterVersioning() {
return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver"); return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
} }
public boolean streamhost() { public boolean streamhost() {
return connection return connection
.findDiscoItemByFeature("http://jabber.org/protocol/bytestreams") != null; .findDiscoItemByFeature("http://jabber.org/protocol/bytestreams") != null;
} }
public boolean compression() { public boolean compression() {

View File

@ -117,7 +117,7 @@ public final class Jid {
finaljid = finaljid + dp; finaljid = finaljid + dp;
} }
// Remove trailling "." before storing the domain part. // Remove trailing "." before storing the domain part.
if (dp.endsWith(".")) { if (dp.endsWith(".")) {
try { try {
domainpart = IDN.toASCII(dp.substring(0, dp.length() - 1), IDN.USE_STD3_ASCII_RULES); domainpart = IDN.toASCII(dp.substring(0, dp.length() - 1), IDN.USE_STD3_ASCII_RULES);