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