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