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