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