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