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