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