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