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