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