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 OnIqPacketReceived callback = null;
476 synchronized (this.packetCallbacks) {
477 if (packetCallbacks.containsKey(packet.getId())) {
478 final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
479 // Packets to the server should have responses from the server
480 if (packetCallbackDuple.first.toServer(account)) {
481 if (packet.fromServer(account)) {
482 callback = packetCallbackDuple.second;
483 packetCallbacks.remove(packet.getId());
484 } else {
485 Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
486 }
487 } else {
488 if (packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
489 callback = packetCallbackDuple.second;
490 packetCallbacks.remove(packet.getId());
491 } else {
492 Log.e(Config.LOGTAG, account.getJid().toBareJid().toString() + ": ignoring spoofed iq packet");
493 }
494 }
495 } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
496 callback = this.unregisteredIqListener;
497 }
498 }
499 if (callback != null) {
500 callback.onIqPacketReceived(account,packet);
501 }
502 }
503 }
504
505 private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
506 final MessagePacket packet = (MessagePacket) processPacket(currentTag,PACKET_MESSAGE);
507 this.messageListener.onMessagePacketReceived(account, packet);
508 }
509
510 private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
511 PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
512 this.presenceListener.onPresencePacketReceived(account, packet);
513 }
514
515 private void sendStartTLS() throws IOException {
516 final Tag startTLS = Tag.empty("starttls");
517 startTLS.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-tls");
518 tagWriter.writeTag(startTLS);
519 }
520
521 private void switchOverToTls(final Tag currentTag) throws XmlPullParserException, IOException {
522 tagReader.readTag();
523 try {
524 final SSLContext sc = SSLContext.getInstance("TLS");
525 sc.init(null,new X509TrustManager[]{this.mXmppConnectionService.getMemorizingTrustManager()},mXmppConnectionService.getRNG());
526 final SSLSocketFactory factory = sc.getSocketFactory();
527 final HostnameVerifier verifier = this.mXmppConnectionService.getMemorizingTrustManager().wrapHostnameVerifier(new StrictHostnameVerifier());
528 final InetAddress address = socket == null ? null : socket.getInetAddress();
529
530 if (factory == null || address == null || verifier == null) {
531 throw new IOException("could not setup ssl");
532 }
533
534 final SSLSocket sslSocket = (SSLSocket) factory.createSocket(socket,address.getHostAddress(), socket.getPort(),true);
535
536 if (sslSocket == null) {
537 throw new IOException("could not initialize ssl socket");
538 }
539
540 final String[] supportProtocols;
541 final Collection<String> supportedProtocols = new LinkedList<>(
542 Arrays.asList(sslSocket.getSupportedProtocols()));
543 supportedProtocols.remove("SSLv3");
544 supportProtocols = supportedProtocols.toArray(new String[supportedProtocols.size()]);
545
546 sslSocket.setEnabledProtocols(supportProtocols);
547
548 final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
549 sslSocket.getSupportedCipherSuites());
550 //Log.d(Config.LOGTAG, "Using ciphers: " + Arrays.toString(cipherSuites));
551 if (cipherSuites.length > 0) {
552 sslSocket.setEnabledCipherSuites(cipherSuites);
553 }
554
555 if (!verifier.verify(account.getServer().getDomainpart(),sslSocket.getSession())) {
556 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
557 throw new SecurityException();
558 }
559 tagReader.setInputStream(sslSocket.getInputStream());
560 tagWriter.setOutputStream(sslSocket.getOutputStream());
561 sendStartStream();
562 Log.d(Config.LOGTAG, account.getJid().toBareJid()+ ": TLS connection established");
563 features.encryptionEnabled = true;
564 processStream(tagReader.readTag());
565 sslSocket.close();
566 } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
567 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": TLS certificate verification failed");
568 throw new SecurityException();
569 }
570 }
571
572 private void processStreamFeatures(final Tag currentTag)
573 throws XmlPullParserException, IOException {
574 this.streamFeatures = tagReader.readElement(currentTag);
575 if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
576 sendStartTLS();
577 } else if (this.streamFeatures.hasChild("register")
578 && account.isOptionSet(Account.OPTION_REGISTER)
579 && features.encryptionEnabled) {
580 sendRegistryRequest();
581 } else if (!this.streamFeatures.hasChild("register")
582 && account.isOptionSet(Account.OPTION_REGISTER)) {
583 changeStatus(Account.State.REGISTRATION_NOT_SUPPORTED);
584 disconnect(true);
585 } else if (this.streamFeatures.hasChild("mechanisms")
586 && shouldAuthenticate && features.encryptionEnabled) {
587 final List<String> mechanisms = extractMechanisms(streamFeatures
588 .findChild("mechanisms"));
589 final Element auth = new Element("auth");
590 auth.setAttribute("xmlns", "urn:ietf:params:xml:ns:xmpp-sasl");
591 if (mechanisms.contains("SCRAM-SHA-1")) {
592 saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
593 } else if (mechanisms.contains("PLAIN")) {
594 saslMechanism = new Plain(tagWriter, account);
595 } else if (mechanisms.contains("DIGEST-MD5")) {
596 saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
597 }
598 if (saslMechanism != null) {
599 final JSONObject keys = account.getKeys();
600 try {
601 if (keys.has(Account.PINNED_MECHANISM_KEY) &&
602 keys.getInt(Account.PINNED_MECHANISM_KEY) > saslMechanism.getPriority()) {
603 Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
604 " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
605 ") than pinned priority (" + keys.getInt(Account.PINNED_MECHANISM_KEY) +
606 "). Possible downgrade attack?");
607 throw new SecurityException();
608 }
609 } catch (final JSONException e) {
610 Log.d(Config.LOGTAG, "Parse error while checking pinned auth mechanism");
611 }
612 Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
613 auth.setAttribute("mechanism", saslMechanism.getMechanism());
614 if (!saslMechanism.getClientFirstMessage().isEmpty()) {
615 auth.setContent(saslMechanism.getClientFirstMessage());
616 }
617 tagWriter.writeElement(auth);
618 } else {
619 throw new IncompatibleServerException();
620 }
621 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && 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 (needsBinding) {
628 if (this.streamFeatures.hasChild("bind")) {
629 sendBindRequest();
630 } else {
631 throw new IncompatibleServerException();
632 }
633 }
634 }
635
636 private List<String> extractMechanisms(final Element stream) {
637 final ArrayList<String> mechanisms = new ArrayList<>(stream
638 .getChildren().size());
639 for (final Element child : stream.getChildren()) {
640 mechanisms.add(child.getContent());
641 }
642 return mechanisms;
643 }
644
645 private void sendRegistryRequest() {
646 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
647 register.query("jabber:iq:register");
648 register.setTo(account.getServer());
649 sendIqPacket(register, new OnIqPacketReceived() {
650
651 @Override
652 public void onIqPacketReceived(final Account account, final IqPacket packet) {
653 if (packet.getType() == IqPacket.TYPE.RESULT
654 && packet.query().hasChild("username")
655 && (packet.query().hasChild("password"))) {
656 final IqPacket register = new IqPacket(IqPacket.TYPE.SET);
657 final Element username = new Element("username").setContent(account.getUsername());
658 final Element password = new Element("password").setContent(account.getPassword());
659 register.query("jabber:iq:register").addChild(username);
660 register.query().addChild(password);
661 sendIqPacket(register, new OnIqPacketReceived() {
662
663 @Override
664 public void onIqPacketReceived(final Account account, final IqPacket packet) {
665 if (packet.getType() == IqPacket.TYPE.RESULT) {
666 account.setOption(Account.OPTION_REGISTER,
667 false);
668 changeStatus(Account.State.REGISTRATION_SUCCESSFUL);
669 } else if (packet.hasChild("error")
670 && (packet.findChild("error")
671 .hasChild("conflict"))) {
672 changeStatus(Account.State.REGISTRATION_CONFLICT);
673 } else {
674 changeStatus(Account.State.REGISTRATION_FAILED);
675 Log.d(Config.LOGTAG, packet.toString());
676 }
677 disconnect(true);
678 }
679 });
680 } else {
681 final Element instructions = packet.query().findChild("instructions");
682 changeStatus(Account.State.REGISTRATION_FAILED);
683 disconnect(true);
684 Log.d(Config.LOGTAG, account.getJid().toBareJid()
685 + ": could not register. instructions are"
686 + (instructions != null ? instructions.getContent() : ""));
687 }
688 }
689 });
690 }
691
692 private void sendBindRequest() {
693 while(!mXmppConnectionService.areMessagesInitialized()) {
694 try {
695 Thread.sleep(500);
696 } catch (final InterruptedException ignored) {
697 }
698 }
699 needsBinding = false;
700 clearIqCallbacks();
701 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
702 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
703 .addChild("resource").setContent(account.getResource());
704 this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
705 @Override
706 public void onIqPacketReceived(final Account account, final IqPacket packet) {
707 final Element bind = packet.findChild("bind");
708 if (bind != null) {
709 final Element jid = bind.findChild("jid");
710 if (jid != null && jid.getContent() != null) {
711 try {
712 account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
713 } catch (final InvalidJidException e) {
714 // TODO: Handle the case where an external JID is technically invalid?
715 }
716 if (streamFeatures.hasChild("session")) {
717 sendStartSession();
718 } else {
719 sendPostBindInitialization();
720 }
721 } else {
722 Log.d(Config.LOGTAG,account.getJid()+": disconnecting because of bind failure");
723 disconnect(true);
724 }
725 } else {
726 Log.d(Config.LOGTAG,account.getJid()+": disconnecting because of bind failure");
727 disconnect(true);
728 }
729 }
730 });
731 }
732
733 private void clearIqCallbacks() {
734 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
735 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
736 synchronized (this.packetCallbacks) {
737 if (this.packetCallbacks.size() == 0) {
738 return;
739 }
740 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
741 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
742 while (iterator.hasNext()) {
743 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
744 callbacks.add(entry.second);
745 iterator.remove();
746 }
747 }
748 for(OnIqPacketReceived callback : callbacks) {
749 callback.onIqPacketReceived(account,failurePacket);
750 }
751 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": done clearing iq callbacks. "+this.packetCallbacks.size()+" left");
752 }
753
754 private void sendStartSession() {
755 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
756 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
757 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
758 @Override
759 public void onIqPacketReceived(Account account, IqPacket packet) {
760 if (packet.getType() == IqPacket.TYPE.RESULT) {
761 sendPostBindInitialization();
762 } else {
763 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
764 disconnect(true);
765 }
766 }
767 });
768 }
769
770 private void sendPostBindInitialization() {
771 smVersion = 0;
772 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
773 smVersion = 3;
774 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
775 smVersion = 2;
776 }
777 if (smVersion != 0) {
778 final EnablePacket enable = new EnablePacket(smVersion);
779 tagWriter.writeStanzaAsync(enable);
780 stanzasSent = 0;
781 mStanzaQueue.clear();
782 }
783 features.carbonsEnabled = false;
784 features.blockListRequested = false;
785 disco.clear();
786 sendServiceDiscoveryInfo(account.getServer());
787 sendServiceDiscoveryInfo(account.getJid().toBareJid());
788 sendServiceDiscoveryItems(account.getServer());
789 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
790 this.lastSessionStarted = SystemClock.elapsedRealtime();
791 changeStatus(Account.State.ONLINE);
792 if (bindListener != null) {
793 bindListener.onBind(account);
794 }
795 }
796
797 private void sendServiceDiscoveryInfo(final Jid jid) {
798 if (disco.containsKey(jid)) {
799 if (account.getServer().equals(jid)) {
800 enableAdvancedStreamFeatures();
801 }
802 } else {
803 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
804 iq.setTo(jid);
805 iq.query("http://jabber.org/protocol/disco#info");
806 this.sendIqPacket(iq, new OnIqPacketReceived() {
807
808 @Override
809 public void onIqPacketReceived(final Account account, final IqPacket packet) {
810 if (packet.getType() == IqPacket.TYPE.RESULT) {
811 final List<Element> elements = packet.query().getChildren();
812 final Info info = new Info();
813 for (final Element element : elements) {
814 if (element.getName().equals("identity")) {
815 String type = element.getAttribute("type");
816 String category = element.getAttribute("category");
817 if (type != null && category != null) {
818 info.identities.add(new Pair<>(category, type));
819 }
820 } else if (element.getName().equals("feature")) {
821 info.features.add(element.getAttribute("var"));
822 }
823 }
824 disco.put(jid, info);
825 if (account.getServer().equals(jid)) {
826 enableAdvancedStreamFeatures();
827 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
828 listener.onAdvancedStreamFeaturesAvailable(account);
829 }
830 }
831 } else {
832 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco info for "+jid.toString());
833 }
834 }
835 });
836 }
837 }
838
839 private void enableAdvancedStreamFeatures() {
840 if (getFeatures().carbons() && !features.carbonsEnabled) {
841 sendEnableCarbons();
842 }
843 if (getFeatures().blocking() && !features.blockListRequested) {
844 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": Requesting block list");
845 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
846 }
847 }
848
849 private void sendServiceDiscoveryItems(final Jid server) {
850 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
851 iq.setTo(server.toDomainJid());
852 iq.query("http://jabber.org/protocol/disco#items");
853 this.sendIqPacket(iq, new OnIqPacketReceived() {
854
855 @Override
856 public void onIqPacketReceived(final Account account, final IqPacket packet) {
857 if (packet.getType() == IqPacket.TYPE.RESULT) {
858 final List<Element> elements = packet.query().getChildren();
859 for (final Element element : elements) {
860 if (element.getName().equals("item")) {
861 final Jid jid = element.getAttributeAsJid("jid");
862 if (jid != null && !jid.equals(account.getServer())) {
863 sendServiceDiscoveryInfo(jid);
864 }
865 }
866 }
867 } else {
868 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": could not query disco items of "+server);
869 }
870 }
871 });
872 }
873
874 private void sendEnableCarbons() {
875 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
876 iq.addChild("enable", "urn:xmpp:carbons:2");
877 this.sendIqPacket(iq, new OnIqPacketReceived() {
878
879 @Override
880 public void onIqPacketReceived(final Account account, final IqPacket packet) {
881 if (!packet.hasChild("error")) {
882 Log.d(Config.LOGTAG, account.getJid().toBareJid()
883 + ": successfully enabled carbons");
884 features.carbonsEnabled = true;
885 } else {
886 Log.d(Config.LOGTAG, account.getJid().toBareJid()
887 + ": error enableing carbons " + packet.toString());
888 }
889 }
890 });
891 }
892
893 private void processStreamError(final Tag currentTag)
894 throws XmlPullParserException, IOException {
895 final Element streamError = tagReader.readElement(currentTag);
896 if (streamError != null && streamError.hasChild("conflict")) {
897 final String resource = account.getResource().split("\\.")[0];
898 account.setResource(resource + "." + nextRandomId());
899 Log.d(Config.LOGTAG,
900 account.getJid().toBareJid() + ": switching resource due to conflict ("
901 + account.getResource() + ")");
902 } else if (streamError != null) {
903 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
904 }
905 }
906
907 private void sendStartStream() throws IOException {
908 final Tag stream = Tag.start("stream:stream");
909 stream.setAttribute("from", account.getJid().toBareJid().toString());
910 stream.setAttribute("to", account.getServer().toString());
911 stream.setAttribute("version", "1.0");
912 stream.setAttribute("xml:lang", "en");
913 stream.setAttribute("xmlns", "jabber:client");
914 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
915 tagWriter.writeTag(stream);
916 }
917
918 private String nextRandomId() {
919 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
920 }
921
922 public void sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
923 packet.setFrom(account.getJid());
924 this.sendUnmodifiedIqPacket(packet, callback);
925
926 }
927
928 private synchronized void sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
929 if (packet.getId() == null) {
930 final String id = nextRandomId();
931 packet.setAttribute("id", id);
932 }
933 if (callback != null) {
934 synchronized (this.packetCallbacks) {
935 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
936 }
937 }
938 this.sendPacket(packet);
939 }
940
941 public void sendMessagePacket(final MessagePacket packet) {
942 this.sendPacket(packet);
943 }
944
945 public void sendPresencePacket(final PresencePacket packet) {
946 this.sendPacket(packet);
947 }
948
949 private synchronized void sendPacket(final AbstractStanza packet) {
950 if (stanzasSent == Integer.MAX_VALUE) {
951 resetStreamId();
952 disconnect(true);
953 return;
954 }
955 final String name = packet.getName();
956 tagWriter.writeStanzaAsync(packet);
957 if (packet instanceof AbstractAcknowledgeableStanza) {
958 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
959 ++stanzasSent;
960 this.mStanzaQueue.put(stanzasSent, stanza);
961 if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
962 if (Config.EXTENDED_SM_LOGGING) {
963 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
964 }
965 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
966 }
967 }
968 }
969
970 public void sendPing() {
971 if (streamFeatures.hasChild("sm")) {
972 tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
973 } else {
974 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
975 iq.setFrom(account.getJid());
976 iq.addChild("ping", "urn:xmpp:ping");
977 this.sendIqPacket(iq, null);
978 }
979 this.lastPingSent = SystemClock.elapsedRealtime();
980 }
981
982 public void setOnMessagePacketReceivedListener(
983 final OnMessagePacketReceived listener) {
984 this.messageListener = listener;
985 }
986
987 public void setOnUnregisteredIqPacketReceivedListener(
988 final OnIqPacketReceived listener) {
989 this.unregisteredIqListener = listener;
990 }
991
992 public void setOnPresencePacketReceivedListener(
993 final OnPresencePacketReceived listener) {
994 this.presenceListener = listener;
995 }
996
997 public void setOnJinglePacketReceivedListener(
998 final OnJinglePacketReceived listener) {
999 this.jingleListener = listener;
1000 }
1001
1002 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1003 this.statusListener = listener;
1004 }
1005
1006 public void setOnBindListener(final OnBindListener listener) {
1007 this.bindListener = listener;
1008 }
1009
1010 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1011 this.acknowledgedListener = listener;
1012 }
1013
1014 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1015 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1016 this.advancedStreamFeaturesLoadedListeners.add(listener);
1017 }
1018 }
1019
1020 public void disconnect(final boolean force) {
1021 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting");
1022 try {
1023 if (force) {
1024 socket.close();
1025 return;
1026 }
1027 new Thread(new Runnable() {
1028
1029 @Override
1030 public void run() {
1031 if (tagWriter.isActive()) {
1032 tagWriter.finish();
1033 try {
1034 while (!tagWriter.finished() && socket.isConnected()) {
1035 Log.d(Config.LOGTAG, "not yet finished");
1036 Thread.sleep(100);
1037 }
1038 tagWriter.writeTag(Tag.end("stream:stream"));
1039 socket.close();
1040 } catch (final IOException e) {
1041 Log.d(Config.LOGTAG,
1042 "io exception during disconnect");
1043 } catch (final InterruptedException e) {
1044 Log.d(Config.LOGTAG, "interrupted");
1045 }
1046 }
1047 }
1048 }).start();
1049 } catch (final IOException e) {
1050 Log.d(Config.LOGTAG, "io exception during disconnect");
1051 }
1052 }
1053
1054 public void resetStreamId() {
1055 this.streamId = null;
1056 }
1057
1058 public List<Jid> findDiscoItemsByFeature(final String feature) {
1059 final List<Jid> items = new ArrayList<>();
1060 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1061 if (cursor.getValue().features.contains(feature)) {
1062 items.add(cursor.getKey());
1063 }
1064 }
1065 return items;
1066 }
1067
1068 public Jid findDiscoItemByFeature(final String feature) {
1069 final List<Jid> items = findDiscoItemsByFeature(feature);
1070 if (items.size() >= 1) {
1071 return items.get(0);
1072 }
1073 return null;
1074 }
1075
1076 public void r() {
1077 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1078 }
1079
1080 public String getMucServer() {
1081 for (final Entry<Jid, Info> cursor : disco.entrySet()) {
1082 final Info value = cursor.getValue();
1083 if (value.features.contains("http://jabber.org/protocol/muc")
1084 && !value.features.contains("jabber:iq:gateway")
1085 && !value.identities.contains(new Pair<>("conference","irc"))) {
1086 return cursor.getKey().toString();
1087 }
1088 }
1089 return null;
1090 }
1091
1092 public int getTimeToNextAttempt() {
1093 final int interval = (int) (25 * Math.pow(1.5, attempt));
1094 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1095 return interval - secondsSinceLast;
1096 }
1097
1098 public int getAttempt() {
1099 return this.attempt;
1100 }
1101
1102 public Features getFeatures() {
1103 return this.features;
1104 }
1105
1106 public long getLastSessionEstablished() {
1107 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1108 return System.currentTimeMillis() - diff;
1109 }
1110
1111 public long getLastConnect() {
1112 return this.lastConnect;
1113 }
1114
1115 public long getLastPingSent() {
1116 return this.lastPingSent;
1117 }
1118
1119 public long getLastPacketReceived() {
1120 return this.lastPacketReceived;
1121 }
1122
1123 public void sendActive() {
1124 this.sendPacket(new ActivePacket());
1125 }
1126
1127 public void sendInactive() {
1128 this.sendPacket(new InactivePacket());
1129 }
1130
1131 public void resetAttemptCount() {
1132 this.attempt = 0;
1133 this.lastConnect = 0;
1134 }
1135
1136 private class Info {
1137 public final ArrayList<String> features = new ArrayList<>();
1138 public final ArrayList<Pair<String,String>> identities = new ArrayList<>();
1139 }
1140
1141 private class UnauthorizedException extends IOException {
1142
1143 }
1144
1145 private class SecurityException extends IOException {
1146
1147 }
1148
1149 private class IncompatibleServerException extends IOException {
1150
1151 }
1152
1153 public class Features {
1154 XmppConnection connection;
1155 private boolean carbonsEnabled = false;
1156 private boolean encryptionEnabled = false;
1157 private boolean blockListRequested = false;
1158
1159 public Features(final XmppConnection connection) {
1160 this.connection = connection;
1161 }
1162
1163 private boolean hasDiscoFeature(final Jid server, final String feature) {
1164 return connection.disco.containsKey(server) &&
1165 connection.disco.get(server).features.contains(feature);
1166 }
1167
1168 public boolean carbons() {
1169 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1170 }
1171
1172 public boolean blocking() {
1173 return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1174 }
1175
1176 public boolean register() {
1177 return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1178 }
1179
1180 public boolean sm() {
1181 return streamId != null
1182 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1183 }
1184
1185 public boolean csi() {
1186 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1187 }
1188
1189 public boolean pep() {
1190 final Pair<String,String> needle = new Pair<>("pubsub","pep");
1191 Info info = disco.get(account.getServer());
1192 if (info != null && info.identities.contains(needle)) {
1193 return true;
1194 } else {
1195 info = disco.get(account.getJid().toBareJid());
1196 return info != null && info.identities.contains(needle);
1197 }
1198 }
1199
1200 public boolean mam() {
1201 if (hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")) {
1202 return true;
1203 } else {
1204 return hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1205 }
1206 }
1207
1208 public boolean advancedStreamFeaturesLoaded() {
1209 return disco.containsKey(account.getServer());
1210 }
1211
1212 public boolean rosterVersioning() {
1213 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1214 }
1215
1216 public void setBlockListRequested(boolean value) {
1217 this.blockListRequested = value;
1218 }
1219
1220 public boolean httpUpload() {
1221 return findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD).size() > 0;
1222 }
1223 }
1224
1225 private IqGenerator getIqGenerator() {
1226 return mXmppConnectionService.getIqGenerator();
1227 }
1228}