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