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 sendStartSession();
929 } else {
930 sendPostBindInitialization();
931 }
932 return;
933 } catch (final InvalidJidException e) {
934 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server reported invalid jid ("+jid.getContent()+") on bind");
935 }
936 } else {
937 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
938 }
939 } else {
940 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
941 }
942 forceCloseSocket();
943 changeStatus(Account.State.BIND_FAILURE);
944 }
945 });
946 }
947
948 private void clearIqCallbacks() {
949 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
950 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
951 synchronized (this.packetCallbacks) {
952 if (this.packetCallbacks.size() == 0) {
953 return;
954 }
955 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
956 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
957 while (iterator.hasNext()) {
958 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
959 callbacks.add(entry.second);
960 iterator.remove();
961 }
962 }
963 for(OnIqPacketReceived callback : callbacks) {
964 callback.onIqPacketReceived(account,failurePacket);
965 }
966 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
967 }
968
969 public void sendDiscoTimeout() {
970 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR); //don't use timeout
971 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
972 synchronized (this.mPendingServiceDiscoveriesIds) {
973 for(String id : mPendingServiceDiscoveriesIds) {
974 synchronized (this.packetCallbacks) {
975 Pair<IqPacket, OnIqPacketReceived> pair = this.packetCallbacks.remove(id);
976 if (pair != null) {
977 callbacks.add(pair.second);
978 }
979 }
980 }
981 this.mPendingServiceDiscoveriesIds.clear();
982 }
983 if (callbacks.size() > 0) {
984 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending disco timeout");
985 resetStreamId(); //we don't want to live with this for ever
986 }
987 for(OnIqPacketReceived callback : callbacks) {
988 callback.onIqPacketReceived(account,failurePacket);
989 }
990 }
991
992 private void sendStartSession() {
993 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
994 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
995 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
996 @Override
997 public void onIqPacketReceived(Account account, IqPacket packet) {
998 if (packet.getType() == IqPacket.TYPE.RESULT) {
999 sendPostBindInitialization();
1000 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1001 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
1002 disconnect(true);
1003 }
1004 }
1005 });
1006 }
1007
1008 private void sendPostBindInitialization() {
1009 smVersion = 0;
1010 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1011 smVersion = 3;
1012 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1013 smVersion = 2;
1014 }
1015 if (smVersion != 0) {
1016 final EnablePacket enable = new EnablePacket(smVersion);
1017 tagWriter.writeStanzaAsync(enable);
1018 stanzasSent = 0;
1019 mStanzaQueue.clear();
1020 }
1021 features.carbonsEnabled = false;
1022 features.blockListRequested = false;
1023 synchronized (this.disco) {
1024 this.disco.clear();
1025 }
1026 mPendingServiceDiscoveries.set(0);
1027 mIsServiceItemsDiscoveryPending.set(true);
1028 mWaitForDisco = mServerIdentity != Identity.NIMBUZZ;
1029 lastDiscoStarted = SystemClock.elapsedRealtime();
1030 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1031 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1032 Element caps = streamFeatures.findChild("c");
1033 final String hash = caps == null ? null : caps.getAttribute("hash");
1034 final String ver = caps == null ? null : caps.getAttribute("ver");
1035 ServiceDiscoveryResult discoveryResult = null;
1036 if (hash != null && ver != null) {
1037 discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1038 }
1039 if (discoveryResult == null) {
1040 sendServiceDiscoveryInfo(account.getServer());
1041 } else {
1042 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server caps came from cache");
1043 disco.put(account.getServer(), discoveryResult);
1044 }
1045 sendServiceDiscoveryInfo(account.getJid().toBareJid());
1046 sendServiceDiscoveryItems(account.getServer());
1047 if (!mWaitForDisco) {
1048 finalizeBind();
1049 }
1050 this.lastSessionStarted = SystemClock.elapsedRealtime();
1051 }
1052
1053 private void sendServiceDiscoveryInfo(final Jid jid) {
1054 mPendingServiceDiscoveries.incrementAndGet();
1055 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1056 iq.setTo(jid);
1057 iq.query("http://jabber.org/protocol/disco#info");
1058 String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1059
1060 @Override
1061 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1062 if (packet.getType() == IqPacket.TYPE.RESULT) {
1063 boolean advancedStreamFeaturesLoaded;
1064 synchronized (XmppConnection.this.disco) {
1065 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1066 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1067 if (mServerIdentity == Identity.UNKNOWN && id.getType().equals("im") &&
1068 id.getCategory().equals("server") && id.getName() != null &&
1069 jid.equals(account.getServer())) {
1070 switch (id.getName()) {
1071 case "Prosody":
1072 mServerIdentity = Identity.PROSODY;
1073 break;
1074 case "ejabberd":
1075 mServerIdentity = Identity.EJABBERD;
1076 break;
1077 case "Slack-XMPP":
1078 mServerIdentity = Identity.SLACK;
1079 break;
1080 }
1081 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server name: " + id.getName());
1082 }
1083 }
1084 if (jid.equals(account.getServer())) {
1085 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1086 }
1087 disco.put(jid, result);
1088 advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1089 && disco.containsKey(account.getJid().toBareJid());
1090 }
1091 if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1092 enableAdvancedStreamFeatures();
1093 }
1094 } else {
1095 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1096 }
1097 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1098 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1099 && !mIsServiceItemsDiscoveryPending.get()
1100 && mWaitForDisco) {
1101 finalizeBind();
1102 }
1103 }
1104 }
1105 });
1106 synchronized (this.mPendingServiceDiscoveriesIds) {
1107 this.mPendingServiceDiscoveriesIds.add(id);
1108 }
1109 }
1110
1111 private void finalizeBind() {
1112 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1113 if (bindListener != null) {
1114 bindListener.onBind(account);
1115 }
1116 changeStatus(Account.State.ONLINE);
1117 }
1118
1119 private void enableAdvancedStreamFeatures() {
1120 if (getFeatures().carbons() && !features.carbonsEnabled) {
1121 sendEnableCarbons();
1122 }
1123 if (getFeatures().blocking() && !features.blockListRequested) {
1124 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1125 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1126 }
1127 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1128 listener.onAdvancedStreamFeaturesAvailable(account);
1129 }
1130 }
1131
1132 private void sendServiceDiscoveryItems(final Jid server) {
1133 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1134 iq.setTo(server.toDomainJid());
1135 iq.query("http://jabber.org/protocol/disco#items");
1136 String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1137
1138 @Override
1139 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1140 if (packet.getType() == IqPacket.TYPE.RESULT) {
1141 final List<Element> elements = packet.query().getChildren();
1142 for (final Element element : elements) {
1143 if (element.getName().equals("item")) {
1144 final Jid jid = element.getAttributeAsJid("jid");
1145 if (jid != null && !jid.equals(account.getServer())) {
1146 sendServiceDiscoveryInfo(jid);
1147 }
1148 }
1149 }
1150 } else {
1151 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1152 }
1153 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1154 mIsServiceItemsDiscoveryPending.set(false);
1155 if (mPendingServiceDiscoveries.get() == 0 && mWaitForDisco) {
1156 finalizeBind();
1157 }
1158 }
1159 }
1160 });
1161 synchronized (this.mPendingServiceDiscoveriesIds) {
1162 this.mPendingServiceDiscoveriesIds.add(id);
1163 }
1164 }
1165
1166 private void sendEnableCarbons() {
1167 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1168 iq.addChild("enable", "urn:xmpp:carbons:2");
1169 this.sendIqPacket(iq, new OnIqPacketReceived() {
1170
1171 @Override
1172 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1173 if (!packet.hasChild("error")) {
1174 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1175 + ": successfully enabled carbons");
1176 features.carbonsEnabled = true;
1177 } else {
1178 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1179 + ": error enableing carbons " + packet.toString());
1180 }
1181 }
1182 });
1183 }
1184
1185 private void processStreamError(final Tag currentTag)
1186 throws XmlPullParserException, IOException {
1187 final Element streamError = tagReader.readElement(currentTag);
1188 if (streamError == null) {
1189 return;
1190 }
1191 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1192 if (streamError.hasChild("conflict")) {
1193 final String resource = account.getResource().split("\\.")[0];
1194 account.setResource(resource + "." + nextRandomId());
1195 Log.d(Config.LOGTAG,
1196 account.getJid().toBareJid() + ": switching resource due to conflict ("
1197 + account.getResource() + ")");
1198 } else if (streamError.hasChild("host-unknown")) {
1199 changeStatus(Account.State.HOST_UNKNOWN);
1200 }
1201 forceCloseSocket();
1202 }
1203
1204 private void sendStartStream() throws IOException {
1205 final Tag stream = Tag.start("stream:stream");
1206 stream.setAttribute("to", account.getServer().toString());
1207 stream.setAttribute("version", "1.0");
1208 stream.setAttribute("xml:lang", "en");
1209 stream.setAttribute("xmlns", "jabber:client");
1210 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1211 tagWriter.writeTag(stream);
1212 }
1213
1214 private String nextRandomId() {
1215 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1216 }
1217
1218 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1219 packet.setFrom(account.getJid());
1220 return this.sendUnmodifiedIqPacket(packet, callback);
1221 }
1222
1223 private synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1224 if (packet.getId() == null) {
1225 final String id = nextRandomId();
1226 packet.setAttribute("id", id);
1227 }
1228 if (callback != null) {
1229 synchronized (this.packetCallbacks) {
1230 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1231 }
1232 }
1233 this.sendPacket(packet);
1234 return packet.getId();
1235 }
1236
1237 public void sendMessagePacket(final MessagePacket packet) {
1238 this.sendPacket(packet);
1239 }
1240
1241 public void sendPresencePacket(final PresencePacket packet) {
1242 this.sendPacket(packet);
1243 }
1244
1245 private synchronized void sendPacket(final AbstractStanza packet) {
1246 if (stanzasSent == Integer.MAX_VALUE) {
1247 resetStreamId();
1248 disconnect(true);
1249 return;
1250 }
1251 tagWriter.writeStanzaAsync(packet);
1252 if (packet instanceof AbstractAcknowledgeableStanza) {
1253 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1254 ++stanzasSent;
1255 this.mStanzaQueue.put(stanzasSent, stanza);
1256 if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1257 if (Config.EXTENDED_SM_LOGGING) {
1258 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1259 }
1260 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1261 }
1262 }
1263 }
1264
1265 public void sendPing() {
1266 if (!r()) {
1267 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1268 iq.setFrom(account.getJid());
1269 iq.addChild("ping", "urn:xmpp:ping");
1270 this.sendIqPacket(iq, null);
1271 }
1272 this.lastPingSent = SystemClock.elapsedRealtime();
1273 }
1274
1275 public void setOnMessagePacketReceivedListener(
1276 final OnMessagePacketReceived listener) {
1277 this.messageListener = listener;
1278 }
1279
1280 public void setOnUnregisteredIqPacketReceivedListener(
1281 final OnIqPacketReceived listener) {
1282 this.unregisteredIqListener = listener;
1283 }
1284
1285 public void setOnPresencePacketReceivedListener(
1286 final OnPresencePacketReceived listener) {
1287 this.presenceListener = listener;
1288 }
1289
1290 public void setOnJinglePacketReceivedListener(
1291 final OnJinglePacketReceived listener) {
1292 this.jingleListener = listener;
1293 }
1294
1295 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1296 this.statusListener = listener;
1297 }
1298
1299 public void setOnBindListener(final OnBindListener listener) {
1300 this.bindListener = listener;
1301 }
1302
1303 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1304 this.acknowledgedListener = listener;
1305 }
1306
1307 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1308 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1309 this.advancedStreamFeaturesLoadedListeners.add(listener);
1310 }
1311 }
1312
1313 public void waitForPush() {
1314 if (tagWriter.isActive()) {
1315 tagWriter.finish();
1316 new Thread(new Runnable() {
1317 @Override
1318 public void run() {
1319 try {
1320 while(!tagWriter.finished()) {
1321 Thread.sleep(10);
1322 }
1323 socket.close();
1324 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closed tcp without closing stream");
1325 } catch (IOException | InterruptedException e) {
1326 return;
1327 }
1328 }
1329 }).start();
1330 } else {
1331 forceCloseSocket();
1332 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closed tcp without closing stream (no waiting)");
1333 }
1334 }
1335
1336 private void forceCloseSocket() {
1337 if (socket != null) {
1338 try {
1339 socket.close();
1340 } catch (IOException e) {
1341 e.printStackTrace();
1342 }
1343 }
1344 }
1345
1346 public void interrupt() {
1347 Thread.currentThread().interrupt();
1348 }
1349
1350 public void disconnect(final boolean force) {
1351 interrupt();
1352 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1353 if (force) {
1354 forceCloseSocket();
1355 return;
1356 } else {
1357 if (tagWriter.isActive()) {
1358 tagWriter.finish();
1359 try {
1360 int i = 0;
1361 boolean warned = false;
1362 while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1363 if (!warned) {
1364 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1365 warned = true;
1366 }
1367 Thread.sleep(200);
1368 i++;
1369 }
1370 if (warned) {
1371 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1372 }
1373 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1374 tagWriter.writeTag(Tag.end("stream:stream"));
1375 } catch (final IOException e) {
1376 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1377 } catch (final InterruptedException e) {
1378 Log.d(Config.LOGTAG, "interrupted");
1379 }
1380 }
1381 }
1382 }
1383
1384 public void resetStreamId() {
1385 this.streamId = null;
1386 }
1387
1388 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1389 synchronized (this.disco) {
1390 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1391 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1392 if (cursor.getValue().getFeatures().contains(feature)) {
1393 items.add(cursor);
1394 }
1395 }
1396 return items;
1397 }
1398 }
1399
1400 public Jid findDiscoItemByFeature(final String feature) {
1401 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1402 if (items.size() >= 1) {
1403 return items.get(0).getKey();
1404 }
1405 return null;
1406 }
1407
1408 public boolean r() {
1409 if (getFeatures().sm()) {
1410 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1411 return true;
1412 } else {
1413 return false;
1414 }
1415 }
1416
1417 public String getMucServer() {
1418 synchronized (this.disco) {
1419 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1420 final ServiceDiscoveryResult value = cursor.getValue();
1421 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1422 && !value.getFeatures().contains("jabber:iq:gateway")
1423 && !value.hasIdentity("conference", "irc")) {
1424 return cursor.getKey().toString();
1425 }
1426 }
1427 }
1428 return null;
1429 }
1430
1431 public int getTimeToNextAttempt() {
1432 final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1433 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1434 return interval - secondsSinceLast;
1435 }
1436
1437 public int getAttempt() {
1438 return this.attempt;
1439 }
1440
1441 public Features getFeatures() {
1442 return this.features;
1443 }
1444
1445 public long getLastSessionEstablished() {
1446 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1447 return System.currentTimeMillis() - diff;
1448 }
1449
1450 public long getLastConnect() {
1451 return this.lastConnect;
1452 }
1453
1454 public long getLastPingSent() {
1455 return this.lastPingSent;
1456 }
1457
1458 public long getLastDiscoStarted() {
1459 return this.lastDiscoStarted;
1460 }
1461 public long getLastPacketReceived() {
1462 return this.lastPacketReceived;
1463 }
1464
1465 public void sendActive() {
1466 this.sendPacket(new ActivePacket());
1467 }
1468
1469 public void sendInactive() {
1470 this.sendPacket(new InactivePacket());
1471 }
1472
1473 public void resetAttemptCount() {
1474 this.attempt = 0;
1475 this.lastConnect = 0;
1476 }
1477
1478 public void setInteractive(boolean interactive) {
1479 this.mInteractive = interactive;
1480 }
1481
1482 public Identity getServerIdentity() {
1483 return mServerIdentity;
1484 }
1485
1486 private class UnauthorizedException extends IOException {
1487
1488 }
1489
1490 private class SecurityException extends IOException {
1491
1492 }
1493
1494 private class IncompatibleServerException extends IOException {
1495
1496 }
1497
1498 public enum Identity {
1499 FACEBOOK,
1500 SLACK,
1501 EJABBERD,
1502 PROSODY,
1503 NIMBUZZ,
1504 UNKNOWN
1505 }
1506
1507 public class Features {
1508 XmppConnection connection;
1509 private boolean carbonsEnabled = false;
1510 private boolean encryptionEnabled = false;
1511 private boolean blockListRequested = false;
1512
1513 public Features(final XmppConnection connection) {
1514 this.connection = connection;
1515 }
1516
1517 private boolean hasDiscoFeature(final Jid server, final String feature) {
1518 synchronized (XmppConnection.this.disco) {
1519 return connection.disco.containsKey(server) &&
1520 connection.disco.get(server).getFeatures().contains(feature);
1521 }
1522 }
1523
1524 public boolean carbons() {
1525 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1526 }
1527
1528 public boolean blocking() {
1529 return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1530 }
1531
1532 public boolean register() {
1533 return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1534 }
1535
1536 public boolean sm() {
1537 return streamId != null
1538 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1539 }
1540
1541 public boolean csi() {
1542 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1543 }
1544
1545 public boolean pep() {
1546 synchronized (XmppConnection.this.disco) {
1547 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1548 return info != null && info.hasIdentity("pubsub", "pep");
1549 }
1550 }
1551
1552 public boolean pepPersistent() {
1553 synchronized (XmppConnection.this.disco) {
1554 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1555 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1556 }
1557 }
1558
1559 public boolean mam() {
1560 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")
1561 || hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1562 }
1563
1564 public boolean push() {
1565 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1566 || hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1567 }
1568
1569 public boolean rosterVersioning() {
1570 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1571 }
1572
1573 public void setBlockListRequested(boolean value) {
1574 this.blockListRequested = value;
1575 }
1576
1577 public boolean httpUpload(long filesize) {
1578 if (Config.DISABLE_HTTP_UPLOAD) {
1579 return false;
1580 } else {
1581 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1582 if (items.size() > 0) {
1583 try {
1584 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1585 if(filesize <= maxsize) {
1586 return true;
1587 } else {
1588 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": http upload is not available for files with size "+filesize+" (max is "+maxsize+")");
1589 return false;
1590 }
1591 } catch (Exception e) {
1592 return true;
1593 }
1594 } else {
1595 return false;
1596 }
1597 }
1598 }
1599
1600 public long getMaxHttpUploadSize() {
1601 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1602 if (items.size() > 0) {
1603 try {
1604 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1605 } catch (Exception e) {
1606 return -1;
1607 }
1608 } else {
1609 return -1;
1610 }
1611 }
1612 }
1613
1614 private IqGenerator getIqGenerator() {
1615 return mXmppConnectionService.getIqGenerator();
1616 }
1617}