1package eu.siacs.conversations.xmpp;
2
3import android.os.Bundle;
4import android.os.Parcelable;
5import android.os.PowerManager;
6import android.os.PowerManager.WakeLock;
7import android.os.SystemClock;
8import android.util.Log;
9import android.util.Pair;
10import android.util.SparseArray;
11
12import org.apache.http.conn.ssl.StrictHostnameVerifier;
13import org.json.JSONException;
14import org.json.JSONObject;
15import org.xmlpull.v1.XmlPullParserException;
16
17import java.io.IOException;
18import java.io.InputStream;
19import java.io.OutputStream;
20import java.math.BigInteger;
21import java.net.ConnectException;
22import java.net.IDN;
23import java.net.InetAddress;
24import java.net.InetSocketAddress;
25import java.net.Socket;
26import java.net.UnknownHostException;
27import java.security.KeyManagementException;
28import java.security.NoSuchAlgorithmException;
29import java.util.ArrayList;
30import java.util.Arrays;
31import java.util.Collection;
32import java.util.HashMap;
33import java.util.Hashtable;
34import java.util.Iterator;
35import java.util.LinkedList;
36import java.util.List;
37import java.util.Map;
38import java.util.Map.Entry;
39
40import javax.net.ssl.HostnameVerifier;
41import javax.net.ssl.SSLContext;
42import javax.net.ssl.SSLSocket;
43import javax.net.ssl.SSLSocketFactory;
44import javax.net.ssl.X509TrustManager;
45
46import eu.siacs.conversations.Config;
47import eu.siacs.conversations.crypto.sasl.DigestMd5;
48import eu.siacs.conversations.crypto.sasl.Plain;
49import eu.siacs.conversations.crypto.sasl.SaslMechanism;
50import eu.siacs.conversations.crypto.sasl.ScramSha1;
51import eu.siacs.conversations.entities.Account;
52import eu.siacs.conversations.generator.IqGenerator;
53import eu.siacs.conversations.services.XmppConnectionService;
54import eu.siacs.conversations.utils.CryptoHelper;
55import eu.siacs.conversations.utils.DNSHelper;
56import eu.siacs.conversations.utils.Xmlns;
57import eu.siacs.conversations.xml.Element;
58import eu.siacs.conversations.xml.Tag;
59import eu.siacs.conversations.xml.TagWriter;
60import eu.siacs.conversations.xml.XmlReader;
61import eu.siacs.conversations.xmpp.jid.InvalidJidException;
62import eu.siacs.conversations.xmpp.jid.Jid;
63import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
64import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
65import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
66import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
67import eu.siacs.conversations.xmpp.stanzas.IqPacket;
68import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
69import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
70import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
71import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
72import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
73import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
74import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
75import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
76
77public class XmppConnection implements Runnable {
78
79 private static final int PACKET_IQ = 0;
80 private static final int PACKET_MESSAGE = 1;
81 private static final int PACKET_PRESENCE = 2;
82 protected Account account;
83 private final WakeLock wakeLock;
84 private Socket socket;
85 private XmlReader tagReader;
86 private TagWriter tagWriter;
87 private final Features features = new Features(this);
88 private boolean shouldBind = true;
89 private boolean shouldAuthenticate = true;
90 private Element streamFeatures;
91 private final HashMap<Jid, Info> disco = new HashMap<>();
92
93 private String streamId = null;
94 private int smVersion = 3;
95 private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
96
97 private int stanzasReceived = 0;
98 private int stanzasSent = 0;
99 private long lastPacketReceived = 0;
100 private long lastPingSent = 0;
101 private long lastConnect = 0;
102 private long lastSessionStarted = 0;
103 private int attempt = 0;
104 private final Map<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
105 private OnPresencePacketReceived presenceListener = null;
106 private OnJinglePacketReceived jingleListener = null;
107 private OnIqPacketReceived unregisteredIqListener = null;
108 private OnMessagePacketReceived messageListener = null;
109 private OnStatusChanged statusListener = null;
110 private OnBindListener bindListener = null;
111 private final ArrayList<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new ArrayList<>();
112 private OnMessageAcknowledged acknowledgedListener = null;
113 private XmppConnectionService mXmppConnectionService = null;
114
115 private SaslMechanism saslMechanism;
116
117 public XmppConnection(final Account account, final XmppConnectionService service) {
118 this.account = account;
119 this.wakeLock = service.getPowerManager().newWakeLock(
120 PowerManager.PARTIAL_WAKE_LOCK, account.getJid().toBareJid().toString());
121 tagWriter = new TagWriter();
122 mXmppConnectionService = service;
123 }
124
125 protected void changeStatus(final Account.State nextStatus) {
126 if (account.getStatus() != nextStatus) {
127 if ((nextStatus == Account.State.OFFLINE)
128 && (account.getStatus() != Account.State.CONNECTING)
129 && (account.getStatus() != Account.State.ONLINE)
130 && (account.getStatus() != Account.State.DISABLED)) {
131 return;
132 }
133 if (nextStatus == Account.State.ONLINE) {
134 this.attempt = 0;
135 }
136 account.setStatus(nextStatus);
137 if (statusListener != null) {
138 statusListener.onStatusChanged(account);
139 }
140 }
141 }
142
143 protected void connect() {
144 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": connecting");
145 features.encryptionEnabled = false;
146 lastConnect = SystemClock.elapsedRealtime();
147 lastPingSent = SystemClock.elapsedRealtime();
148 this.attempt++;
149 try {
150 shouldAuthenticate = shouldBind = !account.isOptionSet(Account.OPTION_REGISTER);
151 tagReader = new XmlReader(wakeLock);
152 tagWriter = new TagWriter();
153 this.changeStatus(Account.State.CONNECTING);
154 if (DNSHelper.isIp(account.getServer().toString())) {
155 socket = new Socket();
156 try {
157 socket.connect(new InetSocketAddress(account.getServer().toString(), 5222), Config.SOCKET_TIMEOUT * 1000);
158 } catch (IOException e) {
159 throw new UnknownHostException();
160 }
161 } else {
162 final Bundle result = DNSHelper.getSRVRecord(account.getServer());
163 if (result == null) {
164 throw new IOException("unhandled exception in DNS resolver");
165 }
166 final ArrayList<Parcelable> values = result.getParcelableArrayList("values");
167 if ("timeout".equals(result.getString("error"))) {
168 throw new IOException("timeout in dns");
169 } else if (values != null) {
170 int i = 0;
171 boolean socketError = true;
172 while (socketError && values.size() > i) {
173 final Bundle namePort = (Bundle) values.get(i);
174 try {
175 String srvRecordServer;
176 try {
177 srvRecordServer = IDN.toASCII(namePort.getString("name"));
178 } catch (final IllegalArgumentException e) {
179 // TODO: Handle me?`
180 srvRecordServer = "";
181 }
182 final int srvRecordPort = namePort.getInt("port");
183 final String srvIpServer = namePort.getString("ip");
184 final InetSocketAddress addr;
185 if (srvIpServer != null) {
186 addr = new InetSocketAddress(srvIpServer, srvRecordPort);
187 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
188 + ": using values from dns " + srvRecordServer
189 + "[" + srvIpServer + "]:" + srvRecordPort);
190 } else {
191 addr = new InetSocketAddress(srvRecordServer, srvRecordPort);
192 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
193 + ": using values from dns "
194 + srvRecordServer + ":" + srvRecordPort);
195 }
196 socket = new Socket();
197 socket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
198 socketError = false;
199 } catch (final Throwable e) {
200 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
201 i++;
202 }
203 }
204 if (socketError) {
205 throw new UnknownHostException();
206 }
207 } else {
208 throw new IOException("unhandled exception in DNS resolver");
209 }
210 }
211 final OutputStream out = socket.getOutputStream();
212 tagWriter.setOutputStream(out);
213 final InputStream in = socket.getInputStream();
214 tagReader.setInputStream(in);
215 tagWriter.beginDocument();
216 sendStartStream();
217 Tag nextTag;
218 while ((nextTag = tagReader.readTag()) != null) {
219 if (nextTag.isStart("stream")) {
220 processStream(nextTag);
221 break;
222 } else {
223 throw new IOException("unknown tag on connect");
224 }
225 }
226 if (socket.isConnected()) {
227 socket.close();
228 }
229 } catch (final IncompatibleServerException e) {
230 this.changeStatus(Account.State.INCOMPATIBLE_SERVER);
231 } catch (final SecurityException e) {
232 this.changeStatus(Account.State.SECURITY_ERROR);
233 } catch (final UnauthorizedException e) {
234 this.changeStatus(Account.State.UNAUTHORIZED);
235 } catch (final UnknownHostException | ConnectException e) {
236 this.changeStatus(Account.State.SERVER_NOT_FOUND);
237 } catch (final IOException | XmlPullParserException | NoSuchAlgorithmException e) {
238 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": " + e.getMessage());
239 this.changeStatus(Account.State.OFFLINE);
240 this.attempt--; //don't count attempt when reconnecting instantly anyway
241 } finally {
242 if (socket != null) {
243 try {
244 socket.close();
245 } catch (IOException e) {
246
247 }
248 }
249 if (wakeLock.isHeld()) {
250 try {
251 wakeLock.release();
252 } catch (final RuntimeException ignored) {
253 }
254 }
255 }
256 }
257
258 @Override
259 public void run() {
260 try {
261 if (socket != null) {
262 socket.close();
263 }
264 } catch (final IOException ignored) {
265
266 }
267 connect();
268 }
269
270 private void processStream(final Tag currentTag) throws XmlPullParserException,
271 IOException, NoSuchAlgorithmException {
272 Tag nextTag = tagReader.readTag();
273
274 while ((nextTag != null) && (!nextTag.isEnd("stream"))) {
275 if (nextTag.isStart("error")) {
276 processStreamError(nextTag);
277 } else if (nextTag.isStart("features")) {
278 processStreamFeatures(nextTag);
279 } else if (nextTag.isStart("proceed")) {
280 switchOverToTls(nextTag);
281 } else if (nextTag.isStart("success")) {
282 final String challenge = tagReader.readElement(nextTag).getContent();
283 try {
284 saslMechanism.getResponse(challenge);
285 } catch (final SaslMechanism.AuthenticationException e) {
286 disconnect(true);
287 Log.e(Config.LOGTAG, String.valueOf(e));
288 }
289 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": logged in");
290 account.setKey(Account.PINNED_MECHANISM_KEY,
291 String.valueOf(saslMechanism.getPriority()));
292 tagReader.reset();
293 sendStartStream();
294 processStream(tagReader.readTag());
295 break;
296 } else if (nextTag.isStart("failure")) {
297 throw new UnauthorizedException();
298 } else if (nextTag.isStart("challenge")) {
299 final String challenge = tagReader.readElement(nextTag).getContent();
300 final Element response = new Element("response");
301 response.setAttribute("xmlns",
302 "urn:ietf:params:xml:ns:xmpp-sasl");
303 try {
304 response.setContent(saslMechanism.getResponse(challenge));
305 } catch (final SaslMechanism.AuthenticationException e) {
306 // TODO: Send auth abort tag.
307 Log.e(Config.LOGTAG, e.toString());
308 }
309 tagWriter.writeElement(response);
310 } else if (nextTag.isStart("enabled")) {
311 final Element enabled = tagReader.readElement(nextTag);
312 if ("true".equals(enabled.getAttribute("resume"))) {
313 this.streamId = enabled.getAttribute("id");
314 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
315 + ": stream managment(" + smVersion
316 + ") enabled (resumable)");
317 } else {
318 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
319 + ": stream managment(" + smVersion + ") enabled");
320 }
321 this.lastSessionStarted = SystemClock.elapsedRealtime();
322 this.stanzasReceived = 0;
323 final RequestPacket r = new RequestPacket(smVersion);
324 tagWriter.writeStanzaAsync(r);
325 } else if (nextTag.isStart("resumed")) {
326 lastPacketReceived = SystemClock.elapsedRealtime();
327 final Element resumed = tagReader.readElement(nextTag);
328 final String h = resumed.getAttribute("h");
329 try {
330 final int serverCount = Integer.parseInt(h);
331 if (serverCount != stanzasSent) {
332 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString()
333 + ": session resumed with lost packages");
334 stanzasSent = serverCount;
335 } else {
336 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": session resumed");
337 }
338 acknowledgeStanzaUpTo(serverCount);
339 ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
340 for(int i = 0; i < this.mStanzaQueue.size(); ++i) {
341 failedStanzas.add(mStanzaQueue.valueAt(i));
342 }
343 mStanzaQueue.clear();
344 Log.d(Config.LOGTAG,"resending "+failedStanzas.size()+" stanzas");
345 for(AbstractAcknowledgeableStanza packet : failedStanzas) {
346 sendPacket(packet);
347 }
348 } catch (final NumberFormatException ignored) {
349 }
350 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
351 changeStatus(Account.State.ONLINE);
352 } else if (nextTag.isStart("r")) {
353 tagReader.readElement(nextTag);
354 if (Config.EXTENDED_SM_LOGGING) {
355 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
356 }
357 final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
358 tagWriter.writeStanzaAsync(ack);
359 } else if (nextTag.isStart("a")) {
360 final Element ack = tagReader.readElement(nextTag);
361 lastPacketReceived = SystemClock.elapsedRealtime();
362 try {
363 final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
364 acknowledgeStanzaUpTo(serverSequence);
365 } catch (NumberFormatException e) {
366 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server send ack without sequence number");
367 }
368 } else if (nextTag.isStart("failed")) {
369 tagReader.readElement(nextTag);
370 Log.d(Config.LOGTAG, account.getJid().toBareJid().toString() + ": resumption failed");
371 streamId = null;
372 if (account.getStatus() != Account.State.ONLINE) {
373 sendBindRequest();
374 }
375 } else if (nextTag.isStart("iq")) {
376 processIq(nextTag);
377 } else if (nextTag.isStart("message")) {
378 processMessage(nextTag);
379 } else if (nextTag.isStart("presence")) {
380 processPresence(nextTag);
381 }
382 nextTag = tagReader.readTag();
383 }
384 if (account.getStatus() == Account.State.ONLINE) {
385 account. setStatus(Account.State.OFFLINE);
386 if (statusListener != null) {
387 statusListener.onStatusChanged(account);
388 }
389 }
390 }
391
392 private void acknowledgeStanzaUpTo(int serverCount) {
393 for (int i = 0; i < mStanzaQueue.size(); ++i) {
394 if (serverCount >= mStanzaQueue.keyAt(i)) {
395 if (Config.EXTENDED_SM_LOGGING) {
396 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
397 }
398 AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
399 if (stanza instanceof MessagePacket && acknowledgedListener != null) {
400 MessagePacket packet = (MessagePacket) stanza;
401 acknowledgedListener.onMessageAcknowledged(account, packet.getId());
402 }
403 mStanzaQueue.removeAt(i);
404 i--;
405 }
406 }
407 }
408
409 private Element processPacket(final Tag currentTag, final int packetType)
410 throws XmlPullParserException, IOException {
411 Element element;
412 switch (packetType) {
413 case PACKET_IQ:
414 element = new IqPacket();
415 break;
416 case PACKET_MESSAGE:
417 element = new MessagePacket();
418 break;
419 case PACKET_PRESENCE:
420 element = new PresencePacket();
421 break;
422 default:
423 return null;
424 }
425 element.setAttributes(currentTag.getAttributes());
426 Tag nextTag = tagReader.readTag();
427 if (nextTag == null) {
428 throw new IOException("interrupted mid tag");
429 }
430 while (!nextTag.isEnd(element.getName())) {
431 if (!nextTag.isNo()) {
432 final Element child = tagReader.readElement(nextTag);
433 final String type = currentTag.getAttribute("type");
434 if (packetType == PACKET_IQ
435 && "jingle".equals(child.getName())
436 && ("set".equalsIgnoreCase(type) || "get"
437 .equalsIgnoreCase(type))) {
438 element = new JinglePacket();
439 element.setAttributes(currentTag.getAttributes());
440 }
441 element.addChild(child);
442 }
443 nextTag = tagReader.readTag();
444 if (nextTag == null) {
445 throw new IOException("interrupted mid tag");
446 }
447 }
448 if (stanzasReceived == Integer.MAX_VALUE) {
449 resetStreamId();
450 throw new IOException("time to restart the session. cant handle >2 billion pcks");
451 }
452 ++stanzasReceived;
453 lastPacketReceived = SystemClock.elapsedRealtime();
454 return element;
455 }
456
457 private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
458 final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
459
460 if (packet.getId() == null) {
461 return; // an iq packet without id is definitely invalid
462 }
463
464 if (packet instanceof JinglePacket) {
465 if (this.jingleListener != null) {
466 this.jingleListener.onJinglePacketReceived(account,(JinglePacket) packet);
467 }
468 } else {
469 synchronized (this.packetCallbacks) {
470 if (packetCallbacks.containsKey(packet.getId())) {
471 final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
472 // Packets to the server should have responses from the server
473 if (packetCallbackDuple.first.toServer(account)) {
474 if (packet.fromServer(account)) {
475 packetCallbackDuple.second.onIqPacketReceived(account, packet);
476 packetCallbacks.remove(packet.getId());
477 } else {
478 Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
479 }
480 } else {
481 if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
482 packetCallbackDuple.second.onIqPacketReceived(account, packet);
483 packetCallbacks.remove(packet.getId());
484 } else {
485 Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
486 }
487 }
488 } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
489 this.unregisteredIqListener.onIqPacketReceived(account, packet);
490 }
491 }
492 }
493 }
494
495 private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
496 final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
497 this.messageListener.onMessagePacketReceived(account, packet);
498 }
499
500 private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
501 PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
502 this.presenceListener.onPresencePacketReceived(account, packet);
503 }
504
505 private void sendStartTLS() throws IOException {
506 final Tag startTLS = Tag.empty("starttls");
507 startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
508 tagWriter.writeTag(startTLS);
509 }
510
511 private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
512 tagReader.readTag();
513 try {
514 final SSLContext sc = SSLContext.getInstance("TLS");
515 sc.init(null,new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},mXmppConnectionService.getRNG());
516 final SSLSocketFactory factory = sc.getSocketFactory();
517 final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
518 final InetAddress address = socket == null ? null : socket.getInetAddress();
519
520 if (factory == null || address == null || verifier == null) {
521 throw new IOException("could not setup ssl");
522 }
523
524 final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
525
526 if (sslSocket == null) {
527 throw new IOException("could not initialize ssl socket");
528 }
529
530 final String[] supportProtocols;
531 final Collection<String> supportedProtocols = new LinkedList<>(
532 Arrays.asList(sslSocket.getSupportedProtocols()));
533 supportedProtocols.remove("SSLv3");
534 supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
535
536 sslSocket.setEnabledProtocols(supportProtocols);
537
538 final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
539 sslSocket.getSupportedCipherSuites());
540 //Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
541 if (cipherSuites.length > 0) {
542 sslSocket.setEnabledCipherSuites(cipherSuites);
543 }
544
545 if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
546 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
547 throw new SecurityException();
548 }
549 tagReader.setInputStream(sslSocket.getInputStream());
550 tagWriter.setOutputStream(sslSocket.getOutputStream());
551 sendStartStream();
552 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
553 features.encryptionEnabled = true;
554 processStream(tagReader.readTag());
555 sslSocket.close();
556 } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
557 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
558 throw new SecurityException();
559 }
560 }
561
562 private void processStreamFeatures(final Tag currentTag)
563 throws XmlPullParserException, IOException {
564 this.streamFeatures = tagReader.readElement(currentTag);
565 if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
566 sendStartTLS();
567 } else if (this.streamFeatures.hasChild("register")
568 && account.isOptionSet(Account.OPTION_REGISTER)
569 && features.encryptionEnabled) {
570 sendRegistryRequest();
571 } else if (!this.streamFeatures.hasChild("register")
572 && account.isOptionSet(Account.OPTION_REGISTER)) {
573 changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
574 disconnect(true);
575 } else if (this.streamFeatures.hasChild("mechanisms")
576 && shouldAuthenticate && features.encryptionEnabled) {
577 final List<String> mechanisms = extractMechanisms(streamFeatures
578 .findChild("mechanisms"));
579 final Element auth = new Element("auth");
580 auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
581 if (mechanisms.contains("SCRAM-SHA-1")) {
582 saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
583 } else if (mechanisms.contains("PLAIN")) {
584 saslMechanism = new Plain(tagWriter, account);
585 } else if (mechanisms.contains("DIGEST-MD5")) {
586 saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
587 }
588 if (saslMechanism != null) {
589 final JSONObject keys = account.getKeys();
590 try {
591 if (keys.has(Account.PINNED_MECHANISM_KEY) &&
592 keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
593 Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
594 " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
595 ") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
596 "). Possible downgrade attack?");
597 throw new SecurityException();
598 }
599 } catch (final JSONException e) {
600 Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
601 }
602 Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
603 auth.setAttribute("mechanism", saslMechanism.getMechanism());
604 if (!saslMechanism.getClientFirstMessage().isEmpty()) {
605 auth.setContent(saslMechanism.getClientFirstMessage());
606 }
607 tagWriter.writeElement(auth);
608 } else {
609 throw new IncompatibleServerException();
610 }
611 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:"
612 + smVersion)
613 && streamId != null) {
614 if (Config.EXTENDED_SM_LOGGING) {
615 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": resuming after stanza #"+stanzasReceived);
616 }
617 final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
618 this.tagWriter.writeStanzaAsync(resume);
619 } else if (this.streamFeatures.hasChild("bind") && shouldBind) {
620 sendBindRequest();
621 } else {
622 disconnect(true);
623 changeStatus(Account.State.INCOMPATIBLE_SERVER);
624 }
625 }
626
627 private List<String> extractMechanisms(final Element stream) {
628 final ArrayList<String> mechanisms = new ArrayList<>(stream
629 .getChildren().size());
630 for (final Element child : stream.getChildren()) {
631 mechanisms.add(child.getContent());
632 }
633 return mechanisms;
634 }
635
636 private void sendRegistryRequest() {
637 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
638 register.query("jabber:iq:register");
639 register.setTo(account.getServer());
640 sendIqPacket(register, new OnIqPacketReceived() {
641
642 @Override
643 public void onIqPacketReceived(final Account account, final IqPacket packet) {
644 final Element instructions = packet.query().findChild("instructions");
645 if (packet.query().hasChild("username")
646 && (packet.query().hasChild("password"))) {
647 final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
648 final Element username = new Element("username").setContent(account.getUsername());
649 final Element password = new Element("password").setContent(account.getPassword());
650 register.query("jabber:iq:register").addChild(username);
651 register.query().addChild(password);
652 sendIqPacket(register, new OnIqPacketReceived() {
653
654 @Override
655 public void onIqPacketReceived(final Account account, final IqPacket packet) {
656 if (packet.getType() == IqPacket.TYPE.RESULT) {
657 account.setOption(Account.OPTION_REGISTER,
658 false);
659 changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
660 } else if (packet.hasChild("error")
661 && (packet.findChild("error")
662 .hasChild("conflict"))) {
663 changeStatus(Account.State.REGISTRATION_CONFLICT);
664 } else {
665 changeStatus(Account.State.REGISTRATION_FAILED);
666 Log.d(Config.LOGTAG, packet.toString());
667 }
668 disconnect(true);
669 }
670 });
671 } else {
672 changeStatus(Account.State.REGISTRATION_FAILED);
673 disconnect(true);
674 Log.d(Config.LOGTAG, account.getJid().toBareJid()
675 + ": could not register. instructions are"
676 + (instructions != null ? instructions.getContent() : ""));
677 }
678 }
679 });
680 }
681
682 private void sendBindRequest() {
683 while(!mXmppConnectionService.areMessagesInitialized()) {
684 try {
685 Thread.sleep(500);
686 } catch (final InterruptedException ignored) {
687 }
688 }
689 clearIqCallbacks();
690 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
691 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
692 .addChild("resource").setContent(account.getResource());
693 this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
694 @Override
695 public void onIqPacketReceived(final Account account, final IqPacket packet) {
696 final Element bind = packet.findChild("bind");
697 if (bind != null) {
698 final Element jid = bind.findChild("jid");
699 if (jid != null && jid.getContent() != null) {
700 try {
701 account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
702 } catch (final InvalidJidException e) {
703 // TODO: Handle the case where an external JID is technically invalid?
704 }
705 if (streamFeatures.hasChild("session")) {
706 sendStartSession();
707 } else {
708 sendPostBindInitialization();
709 }
710 } else {
711 disconnect(true);
712 }
713 } else {
714 disconnect(true);
715 }
716 }
717 });
718 }
719
720 private void clearIqCallbacks() {
721 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing iq iq callbacks");
722 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR);
723 synchronized (this.packetCallbacks) {
724 Iterator<Entry<String, Pair<IqPacket, OnIqPacketReceived>>> iterator = this.packetCallbacks.entrySet().iterator();
725 while (iterator.hasNext()) {
726 Entry<String, Pair<IqPacket, OnIqPacketReceived>> entry = iterator.next();
727 entry.getValue().second.onIqPacketReceived(account, failurePacket);
728 iterator.remove();
729 }
730 }
731 }
732
733 private void sendStartSession() {
734 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
735 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
736 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
737 @Override
738 public void onIqPacketReceived(Account account, IqPacket packet) {
739 if (packet.getType() == IqPacket.TYPE.RESULT) {
740 sendPostBindInitialization();
741 } else {
742 disconnect(true);
743 }
744 }
745 });
746 }
747
748 private void sendPostBindInitialization() {
749 smVersion = 0;
750 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
751 smVersion = 3;
752 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
753 smVersion = 2;
754 }
755 if (smVersion != 0) {
756 final EnablePacket enable = new EnablePacket(smVersion);
757 tagWriter.writeStanzaAsync(enable);
758 stanzasSent = 0;
759 mStanzaQueue.clear();
760 }
761 features.carbonsEnabled = false;
762 features.blockListRequested = false;
763 disco.clear();
764 sendServiceDiscoveryInfo(account.getServer());
765 sendServiceDiscoveryInfo(account.getJid().toBareJid());
766 sendServiceDiscoveryItems(account.getServer());
767 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": online with resource " + account.getResource());
768 changeStatus(Account.State.ONLINE);
769 if (bindListener != null) {
770 bindListener.onBind(account);
771 }
772 }
773
774 private void sendServiceDiscoveryInfo(final Jid jid) {
775 if (disco.containsKey(jid)) {
776 if (account.getServer().equals(jid)) {
777 enableAdvancedStreamFeatures();
778 }
779 } else {
780 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
781 iq.setTo(jid);
782 iq.query("http://jabber.org/protocol/disco#info");
783 this.sendIqPacket(iq, new OnIqPacketReceived() {
784
785 @Override
786 public void onIqPacketReceived(final Account account, final IqPacket packet) {
787 final List<Element> elements = packet.query().getChildren();
788 final Info info = new Info();
789 for (final Element element : elements) {
790 if (element.getName().equals("identity")) {
791 String type = element.getAttribute("type");
792 String category = element.getAttribute("category");
793 if (type != null && category != null) {
794 info.identities.add(new Pair<>(category,type));
795 }
796 } else if (element.getName().equals("feature")) {
797 info.features.add(element.getAttribute("var"));
798 }
799 }
800 disco.put(jid, info);
801
802 if (account.getServer().equals(jid)) {
803 enableAdvancedStreamFeatures();
804 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
805 listener.onAdvancedStreamFeaturesAvailable(account);
806 }
807 }
808 }
809 });
810 }
811 }
812
813 private void enableAdvancedStreamFeatures() {
814 if (getFeatures().carbons() && !features.carbonsEnabled) {
815 sendEnableCarbons();
816 }
817 if (getFeatures().blocking() && !features.blockListRequested) {
818 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": Requesting block list");
819 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
820 }
821 }
822
823 private void sendServiceDiscoveryItems(final Jid server) {
824 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
825 iq.setTo(server.toDomainJid());
826 iq.query("http://jabber.org/protocol/disco#items");
827 this.sendIqPacket(iq, new OnIqPacketReceived() {
828
829 @Override
830 public void onIqPacketReceived(final Account account, final IqPacket packet) {
831 final List<Element> elements = packet.query().getChildren();
832 for (final Element element : elements) {
833 if (element.getName().equals("item")) {
834 final Jid jid = element.getAttributeAsJid("jid");
835 if (jid != null && !jid.equals(account.getServer())) {
836 sendServiceDiscoveryInfo(jid);
837 }
838 }
839 }
840 }
841 });
842 }
843
844 private void sendEnableCarbons() {
845 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
846 iq.addChild("enable", "urn:xmpp:carbons:2");
847 this.sendIqPacket(iq, new OnIqPacketReceived() {
848
849 @Override
850 public void onIqPacketReceived(final Account account, final IqPacket packet) {
851 if (!packet.hasChild("error")) {
852 Log.d(Config.LOGTAG, account.getJid().toBareJid()
853 + ": successfully enabled carbons");
854 features.carbonsEnabled = true;
855 } else {
856 Log.d(Config.LOGTAG, account.getJid().toBareJid()
857 + ": error enableing carbons " + packet.toString());
858 }
859 }
860 });
861 }
862
863 private void processStreamError(final Tag currentTag)
864 throws XmlPullParserException, IOException {
865 final Element streamError = tagReader.readElement(currentTag);
866 if (streamError != null && streamError.hasChild("conflict")) {
867 final String resource = account.getResource().split("\\.")[0];
868 account.setResource(resource + "." + nextRandomId());
869 Log.d(Config.LOGTAG,
870 account.getJid().toBareJid() + ": switching resource due to conflict ("
871 + account.getResource() + ")");
872 }
873 }
874
875 private void sendStartStream() throws IOException {
876 final Tag stream = Tag.start("stream:stream");
877 stream.setAttribute("from", account.getJid().toBareJid().toString());
878 stream.setAttribute("to", account.getServer().toString());
879 stream.setAttribute("version", "1.0");
880 stream.setAttribute("xml:lang", "en");
881 stream.setAttribute("xmlns", "jabber:client");
882 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
883 tagWriter.writeTag(stream);
884 }
885
886 private String nextRandomId() {
887 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
888 }
889
890 public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
891 packet.setFrom(account.getJid());
892 this.sendUnmodifiedIqPacket(packet, callback);
893
894 }
895
896 private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
897 if (packet.getId() == null) {
898 final String id = nextRandomId();
899 packet.setAttribute("id", id);
900 }
901 if (callback != null) {
902 synchronized (this.packetCallbacks) {
903 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
904 }
905 }
906 this.sendPacket(packet);
907 }
908
909 public void sendMessagePacket(final MessagePacket packet) {
910 this.sendPacket(packet);
911 }
912
913 public void sendPresencePacket(final PresencePacket packet) {
914 this.sendPacket(packet);
915 }
916
917 private synchronized void sendPacket(final AbstractStanza packet) {
918 if (stanzasSent == Integer.MAX_VALUE) {
919 resetStreamId();
920 disconnect(true);
921 return;
922 }
923 final String name = packet.getName();
924 tagWriter.writeStanzaAsync(packet);
925 if (packet instanceof AbstractAcknowledgeableStanza) {
926 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
927 ++stanzasSent;
928 this.mStanzaQueue.put(stanzasSent, stanza);
929 if (stanza instanceof MessagePacket && stanza.getId() != null && this.streamId != null) {
930 if (Config.EXTENDED_SM_LOGGING) {
931 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
932 }
933 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
934 }
935 }
936 }
937
938 public void sendPing() {
939 if (streamFeatures.hasChild("sm")) {
940 tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
941 } else {
942 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
943 iq.setFrom(account.getJid());
944 iq.addChild("ping", "urn:xmpp:ping");
945 this.sendIqPacket(iq, null);
946 }
947 this.lastPingSent = SystemClock.elapsedRealtime();
948 }
949
950 public void setOnMessagePacketReceivedListener(
951 final OnMessagePacketReceived listener) {
952 this.messageListener = listener;
953 }
954
955 public void setOnUnregisteredIqPacketReceivedListener(
956 final OnIqPacketReceived listener) {
957 this.unregisteredIqListener = listener;
958 }
959
960 public void setOnPresencePacketReceivedListener(
961 final OnPresencePacketReceived listener) {
962 this.presenceListener = listener;
963 }
964
965 public void setOnJinglePacketReceivedListener(
966 final OnJinglePacketReceived listener) {
967 this.jingleListener = listener;
968 }
969
970 public void setOnStatusChangedListener(final OnStatusChanged listener) {
971 this.statusListener = listener;
972 }
973
974 public void setOnBindListener(final OnBindListener listener) {
975 this.bindListener = listener;
976 }
977
978 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
979 this.acknowledgedListener = listener;
980 }
981
982 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
983 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
984 this.advancedStreamFeaturesLoadedListeners.add(listener);
985 }
986 }
987
988 public void disconnect(final boolean force) {
989 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
990 try {
991 if (force) {
992 socket.close();
993 return;
994 }
995 new Thread(new Runnable() {
996
997 @Override
998 public void run() {
999 if (tagWriter.isActive()) {
1000 tagWriter.finish();
1001 try {
1002 while (!tagWriter.finished() && socket.isConnected()) {
1003 Log.d(Config.LOGTAG, "not yet finished");
1004 Thread.sleep(100);
1005 }
1006 tagWriter.writeTag(Tag.end("stream:stream"));
1007 socket.close();
1008 } catch (final IOException e) {
1009 Log.d(Config.LOGTAG,
1010 "io exception during disconnect");
1011 } catch (final InterruptedException e) {
1012 Log.d(Config.LOGTAG, "interrupted");
1013 }
1014 }
1015 }
1016 }).start();
1017 } catch (final IOException e) {
1018 Log.d(Config.LOGTAG, "io exception during disconnect");
1019 }
1020 }
1021
1022 public void resetStreamId() {
1023 this.streamId = null;
1024 }
1025
1026 public List<Jid> findDiscoItemsByFeature(final String feature) {
1027 final List<Jid> items = new ArrayList<>();
1028 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1029 if (cursor.getValue().features.contains(feature)) {
1030 items.add(cursor.getKey());
1031 }
1032 }
1033 return items;
1034 }
1035
1036 public Jid findDiscoItemByFeature(final String feature) {
1037 final List<Jid> items = findDiscoItemsByFeature(feature);
1038 if (items.size() >= 1) {
1039 return items.get(0);
1040 }
1041 return null;
1042 }
1043
1044 public void r() {
1045 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1046 }
1047
1048 public String getMucServer() {
1049 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1050 final Info value = cursor.getValue();
1051 if (value.features.contains("http://jabber.org/protocol/muc")
1052 && !value.features.contains("jabber:iq:gateway")
1053 && !value.identities.contains(new Pair<>("conference","irc"))) {
1054 return cursor.getKey().toString();
1055 }
1056 }
1057 return null;
1058 }
1059
1060 public int getTimeToNextAttempt() {
1061 final int interval = (int) (25 * Math.pow(1.5, attempt));
1062 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1063 return interval - secondsSinceLast;
1064 }
1065
1066 public int getAttempt() {
1067 return this.attempt;
1068 }
1069
1070 public Features getFeatures() {
1071 return this.features;
1072 }
1073
1074 public long getLastSessionEstablished() {
1075 final long diff;
1076 if (this.lastSessionStarted == 0) {
1077 diff = SystemClock.elapsedRealtime() - this.lastConnect;
1078 } else {
1079 diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1080 }
1081 return System.currentTimeMillis() - diff;
1082 }
1083
1084 public long getLastConnect() {
1085 return this.lastConnect;
1086 }
1087
1088 public long getLastPingSent() {
1089 return this.lastPingSent;
1090 }
1091
1092 public long getLastPacketReceived() {
1093 return this.lastPacketReceived;
1094 }
1095
1096 public void sendActive() {
1097 this.sendPacket(new ActivePacket());
1098 }
1099
1100 public void sendInactive() {
1101 this.sendPacket(new InactivePacket());
1102 }
1103
1104 public void resetAttemptCount() {
1105 this.attempt = 0;
1106 this.lastConnect = 0;
1107 }
1108
1109 private class Info {
1110 public final ArrayList<String> features = new ArrayList<>();
1111 public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1112 }
1113
1114 private class UnauthorizedException extends IOException {
1115
1116 }
1117
1118 private class SecurityException extends IOException {
1119
1120 }
1121
1122 private class IncompatibleServerException extends IOException {
1123
1124 }
1125
1126 public class Features {
1127 XmppConnection connection;
1128 private boolean carbonsEnabled = false;
1129 private boolean encryptionEnabled = false;
1130 private boolean blockListRequested = false;
1131
1132 public Features(final XmppConnection connection) {
1133 this.connection = connection;
1134 }
1135
1136 private boolean hasDiscoFeature(final Jid server, final String feature) {
1137 return connection.disco.containsKey(server) &&
1138 connection.disco.get(server).features.contains(feature);
1139 }
1140
1141 public boolean carbons() {
1142 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1143 }
1144
1145 public boolean blocking() {
1146 return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1147 }
1148
1149 public boolean register() {
1150 return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1151 }
1152
1153 public boolean sm() {
1154 return streamId != null
1155 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1156 }
1157
1158 public boolean csi() {
1159 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1160 }
1161
1162 public boolean pep() {
1163 final Pair<String,String> needle = new Pair<>("pubsub","pep");
1164 Info info = disco.get(account.getServer());
1165 if (info != null && info.identities.contains(needle)) {
1166 return true;
1167 } else {
1168 info = disco.get(account.getJid().toBareJid());
1169 return info != null && info.identities.contains(needle);
1170 }
1171 }
1172
1173 public boolean mam() {
1174 if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1175 return true;
1176 } else {
1177 return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1178 }
1179 }
1180
1181 public boolean advancedStreamFeaturesLoaded() {
1182 return disco.containsKey(account.getServer());
1183 }
1184
1185 public boolean rosterVersioning() {
1186 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1187 }
1188
1189 public void setBlockListRequested(boolean value) {
1190 this.blockListRequested = value;
1191 }
1192
1193 public boolean httpUpload() {
1194 return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1195 }
1196 }
1197
1198 private IqGenerator getIqGenerator() {
1199 return mXmppConnectionService.getIqGenerator();
1200 }
1201}