1package eu.siacs.conversations.xmpp;
2
3import android.content.Context;
4import android.graphics.Bitmap;
5import android.graphics.BitmapFactory;
6import android.os.SystemClock;
7import android.security.KeyChain;
8import android.support.annotation.NonNull;
9import android.util.Base64;
10import android.util.Log;
11import android.util.Pair;
12import android.util.SparseArray;
13
14import org.xmlpull.v1.XmlPullParserException;
15
16import java.io.ByteArrayInputStream;
17import java.io.IOException;
18import java.io.InputStream;
19import java.net.ConnectException;
20import java.net.IDN;
21import java.net.InetAddress;
22import java.net.InetSocketAddress;
23import java.net.MalformedURLException;
24import java.net.Socket;
25import java.net.URL;
26import java.net.UnknownHostException;
27import java.security.KeyManagementException;
28import java.security.NoSuchAlgorithmException;
29import java.security.Principal;
30import java.security.PrivateKey;
31import java.security.cert.X509Certificate;
32import java.util.ArrayList;
33import java.util.Arrays;
34import java.util.Collections;
35import java.util.HashMap;
36import java.util.HashSet;
37import java.util.Hashtable;
38import java.util.Iterator;
39import java.util.List;
40import java.util.Map.Entry;
41import java.util.Set;
42import java.util.concurrent.CountDownLatch;
43import java.util.concurrent.TimeUnit;
44import java.util.concurrent.atomic.AtomicBoolean;
45import java.util.concurrent.atomic.AtomicInteger;
46import java.util.regex.Matcher;
47
48import javax.net.ssl.KeyManager;
49import javax.net.ssl.SSLContext;
50import javax.net.ssl.SSLSocket;
51import javax.net.ssl.SSLSocketFactory;
52import javax.net.ssl.X509KeyManager;
53import javax.net.ssl.X509TrustManager;
54
55import eu.siacs.conversations.Config;
56import eu.siacs.conversations.R;
57import eu.siacs.conversations.crypto.DomainHostnameVerifier;
58import eu.siacs.conversations.crypto.XmppDomainVerifier;
59import eu.siacs.conversations.crypto.axolotl.AxolotlService;
60import eu.siacs.conversations.crypto.sasl.Anonymous;
61import eu.siacs.conversations.crypto.sasl.DigestMd5;
62import eu.siacs.conversations.crypto.sasl.External;
63import eu.siacs.conversations.crypto.sasl.Plain;
64import eu.siacs.conversations.crypto.sasl.SaslMechanism;
65import eu.siacs.conversations.crypto.sasl.ScramSha1;
66import eu.siacs.conversations.crypto.sasl.ScramSha256;
67import eu.siacs.conversations.entities.Account;
68import eu.siacs.conversations.entities.Message;
69import eu.siacs.conversations.entities.ServiceDiscoveryResult;
70import eu.siacs.conversations.generator.IqGenerator;
71import eu.siacs.conversations.persistance.FileBackend;
72import eu.siacs.conversations.services.MemorizingTrustManager;
73import eu.siacs.conversations.services.MessageArchiveService;
74import eu.siacs.conversations.services.NotificationService;
75import eu.siacs.conversations.services.XmppConnectionService;
76import eu.siacs.conversations.utils.CryptoHelper;
77import eu.siacs.conversations.utils.Patterns;
78import eu.siacs.conversations.utils.Resolver;
79import eu.siacs.conversations.utils.SSLSocketHelper;
80import eu.siacs.conversations.utils.SocksSocketFactory;
81import eu.siacs.conversations.xml.Element;
82import eu.siacs.conversations.xml.Namespace;
83import eu.siacs.conversations.xml.Tag;
84import eu.siacs.conversations.xml.TagWriter;
85import eu.siacs.conversations.xml.XmlReader;
86import eu.siacs.conversations.xmpp.forms.Data;
87import eu.siacs.conversations.xmpp.forms.Field;
88import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
89import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
90import eu.siacs.conversations.xmpp.stanzas.AbstractAcknowledgeableStanza;
91import eu.siacs.conversations.xmpp.stanzas.AbstractStanza;
92import eu.siacs.conversations.xmpp.stanzas.IqPacket;
93import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
94import eu.siacs.conversations.xmpp.stanzas.PresencePacket;
95import eu.siacs.conversations.xmpp.stanzas.csi.ActivePacket;
96import eu.siacs.conversations.xmpp.stanzas.csi.InactivePacket;
97import eu.siacs.conversations.xmpp.stanzas.streammgmt.AckPacket;
98import eu.siacs.conversations.xmpp.stanzas.streammgmt.EnablePacket;
99import eu.siacs.conversations.xmpp.stanzas.streammgmt.RequestPacket;
100import eu.siacs.conversations.xmpp.stanzas.streammgmt.ResumePacket;
101import rocks.xmpp.addr.Jid;
102
103public class XmppConnection implements Runnable {
104
105 private static final int PACKET_IQ = 0;
106 private static final int PACKET_MESSAGE = 1;
107 private static final int PACKET_PRESENCE = 2;
108 public final OnIqPacketReceived registrationResponseListener = new OnIqPacketReceived() {
109 @Override
110 public void onIqPacketReceived(Account account, IqPacket packet) {
111 if (packet.getType() == IqPacket.TYPE.RESULT) {
112 account.setOption(Account.OPTION_REGISTER, false);
113 throw new StateChangingError(Account.State.REGISTRATION_SUCCESSFUL);
114 } else {
115 final List<String> PASSWORD_TOO_WEAK_MSGS = Arrays.asList(
116 "The password is too weak",
117 "Please use a longer password.");
118 Element error = packet.findChild("error");
119 Account.State state = Account.State.REGISTRATION_FAILED;
120 if (error != null) {
121 if (error.hasChild("conflict")) {
122 state = Account.State.REGISTRATION_CONFLICT;
123 } else if (error.hasChild("resource-constraint")
124 && "wait".equals(error.getAttribute("type"))) {
125 state = Account.State.REGISTRATION_PLEASE_WAIT;
126 } else if (error.hasChild("not-acceptable")
127 && PASSWORD_TOO_WEAK_MSGS.contains(error.findChildContent("text"))) {
128 state = Account.State.REGISTRATION_PASSWORD_TOO_WEAK;
129 }
130 }
131 throw new StateChangingError(state);
132 }
133 }
134 };
135 protected final Account account;
136 private final Features features = new Features(this);
137 private final HashMap<Jid, ServiceDiscoveryResult> disco = new HashMap<>();
138 private final SparseArray<AbstractAcknowledgeableStanza> mStanzaQueue = new SparseArray<>();
139 private final Hashtable<String, Pair<IqPacket, OnIqPacketReceived>> packetCallbacks = new Hashtable<>();
140 private final Set<OnAdvancedStreamFeaturesLoaded> advancedStreamFeaturesLoadedListeners = new HashSet<>();
141 private final XmppConnectionService mXmppConnectionService;
142 private Socket socket;
143 private XmlReader tagReader;
144 private TagWriter tagWriter = new TagWriter();
145 private boolean shouldAuthenticate = true;
146 private boolean inSmacksSession = false;
147 private boolean isBound = false;
148 private Element streamFeatures;
149 private String streamId = null;
150 private int smVersion = 3;
151 private int stanzasReceived = 0;
152 private int stanzasSent = 0;
153 private long lastPacketReceived = 0;
154 private long lastPingSent = 0;
155 private long lastConnect = 0;
156 private long lastSessionStarted = 0;
157 private long lastDiscoStarted = 0;
158 private boolean isMamPreferenceAlways = false;
159 private AtomicInteger mPendingServiceDiscoveries = new AtomicInteger(0);
160 private AtomicBoolean mWaitForDisco = new AtomicBoolean(true);
161 private AtomicBoolean mWaitingForSmCatchup = new AtomicBoolean(false);
162 private AtomicInteger mSmCatchupMessageCounter = new AtomicInteger(0);
163 private boolean mInteractive = false;
164 private int attempt = 0;
165 private OnPresencePacketReceived presenceListener = null;
166 private OnJinglePacketReceived jingleListener = null;
167 private OnIqPacketReceived unregisteredIqListener = null;
168 private OnMessagePacketReceived messageListener = null;
169 private OnStatusChanged statusListener = null;
170 private OnBindListener bindListener = null;
171 private OnMessageAcknowledged acknowledgedListener = null;
172 private SaslMechanism saslMechanism;
173 private URL redirectionUrl = null;
174 private String verifiedHostname = null;
175 private volatile Thread mThread;
176 private CountDownLatch mStreamCountDownLatch;
177
178
179 public XmppConnection(final Account account, final XmppConnectionService service) {
180 this.account = account;
181 this.mXmppConnectionService = service;
182 }
183
184 private static void fixResource(Context context, Account account) {
185 String resource = account.getResource();
186 int fixedPartLength = context.getString(R.string.app_name).length() + 1; //include the trailing dot
187 int randomPartLength = 4; // 3 bytes
188 if (resource != null && resource.length() > fixedPartLength + randomPartLength) {
189 if (validBase64(resource.substring(fixedPartLength, fixedPartLength + randomPartLength))) {
190 account.setResource(resource.substring(0, fixedPartLength + randomPartLength));
191 }
192 }
193 }
194
195 private static boolean validBase64(String input) {
196 try {
197 return Base64.decode(input, Base64.URL_SAFE).length == 3;
198 } catch (Throwable throwable) {
199 return false;
200 }
201 }
202
203 private void changeStatus(final Account.State nextStatus) {
204 synchronized (this) {
205 if (Thread.currentThread().isInterrupted()) {
206 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not changing status to " + nextStatus + " because thread was interrupted");
207 return;
208 }
209 if (account.getStatus() != nextStatus) {
210 if ((nextStatus == Account.State.OFFLINE)
211 && (account.getStatus() != Account.State.CONNECTING)
212 && (account.getStatus() != Account.State.ONLINE)
213 && (account.getStatus() != Account.State.DISABLED)) {
214 return;
215 }
216 if (nextStatus == Account.State.ONLINE) {
217 this.attempt = 0;
218 }
219 account.setStatus(nextStatus);
220 } else {
221 return;
222 }
223 }
224 if (statusListener != null) {
225 statusListener.onStatusChanged(account);
226 }
227 }
228
229 public void prepareNewConnection() {
230 this.lastConnect = SystemClock.elapsedRealtime();
231 this.lastPingSent = SystemClock.elapsedRealtime();
232 this.lastDiscoStarted = Long.MAX_VALUE;
233 this.mWaitingForSmCatchup.set(false);
234 this.changeStatus(Account.State.CONNECTING);
235 }
236
237 public boolean isWaitingForSmCatchup() {
238 return mWaitingForSmCatchup.get();
239 }
240
241 public void incrementSmCatchupMessageCounter() {
242 this.mSmCatchupMessageCounter.incrementAndGet();
243 }
244
245 protected void connect() {
246 if (mXmppConnectionService.areMessagesInitialized()) {
247 mXmppConnectionService.resetSendingToWaiting(account);
248 }
249 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": connecting");
250 features.encryptionEnabled = false;
251 inSmacksSession = false;
252 isBound = false;
253 this.attempt++;
254 this.verifiedHostname = null; //will be set if user entered hostname is being used or hostname was verified with dnssec
255 try {
256 Socket localSocket;
257 shouldAuthenticate = !account.isOptionSet(Account.OPTION_REGISTER);
258 this.changeStatus(Account.State.CONNECTING);
259 final boolean useTor = mXmppConnectionService.useTorToConnect() || account.isOnion();
260 final boolean extended = mXmppConnectionService.showExtendedConnectionOptions();
261 if (useTor) {
262 String destination;
263 if (account.getHostname().isEmpty()) {
264 destination = account.getServer();
265 } else {
266 destination = account.getHostname();
267 this.verifiedHostname = destination;
268 }
269 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": connect to " + destination + " via Tor");
270 localSocket = SocksSocketFactory.createSocketOverTor(destination, account.getPort());
271 try {
272 startXmpp(localSocket);
273 } catch (InterruptedException e) {
274 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
275 return;
276 } catch (Exception e) {
277 throw new IOException(e.getMessage());
278 }
279 } else {
280 final String domain = account.getJid().getDomain();
281 final List<Resolver.Result> results;
282 final boolean hardcoded = extended && !account.getHostname().isEmpty();
283 if (hardcoded) {
284 results = Resolver.fromHardCoded(account.getHostname(), account.getPort());
285 } else {
286 results = Resolver.resolve(domain);
287 }
288 if (Thread.currentThread().isInterrupted()) {
289 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
290 return;
291 }
292 if (results.size() == 0) {
293 Log.e(Config.LOGTAG,account.getJid().asBareJid()+": Resolver results were empty");
294 return;
295 }
296 final Resolver.Result storedBackupResult;
297 if (hardcoded) {
298 storedBackupResult = null;
299 } else {
300 storedBackupResult = mXmppConnectionService.databaseBackend.findResolverResult(domain);
301 if (storedBackupResult != null && !results.contains(storedBackupResult)) {
302 results.add(storedBackupResult);
303 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": loaded backup resolver result from db: " + storedBackupResult);
304 }
305 }
306 for (Iterator<Resolver.Result> iterator = results.iterator(); iterator.hasNext(); ) {
307 final Resolver.Result result = iterator.next();
308 if (Thread.currentThread().isInterrupted()) {
309 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Thread was interrupted");
310 return;
311 }
312 try {
313 // if tls is true, encryption is implied and must not be started
314 features.encryptionEnabled = result.isDirectTls();
315 verifiedHostname = result.isAuthenticated() ? result.getHostname().toString() : null;
316 Log.d(Config.LOGTAG,"verified hostname "+verifiedHostname);
317 final InetSocketAddress addr;
318 if (result.getIp() != null) {
319 addr = new InetSocketAddress(result.getIp(), result.getPort());
320 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
321 + ": using values from resolver " + (result.getHostname() == null ? "" : result.getHostname().toString()
322 + "/") + result.getIp().getHostAddress() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
323 } else {
324 addr = new InetSocketAddress(IDN.toASCII(result.getHostname().toString()), result.getPort());
325 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
326 + ": using values from resolver "
327 + result.getHostname().toString() + ":" + result.getPort() + " tls: " + features.encryptionEnabled);
328 }
329
330 if (!features.encryptionEnabled) {
331 localSocket = new Socket();
332 localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
333 } else {
334 final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
335 localSocket = tlsFactoryVerifier.factory.createSocket();
336
337 if (localSocket == null) {
338 throw new IOException("could not initialize ssl socket");
339 }
340
341 SSLSocketHelper.setSecurity((SSLSocket) localSocket);
342 SSLSocketHelper.setHostname((SSLSocket) localSocket, account.getServer());
343 SSLSocketHelper.setApplicationProtocol((SSLSocket) localSocket, "xmpp-client");
344
345 localSocket.connect(addr, Config.SOCKET_TIMEOUT * 1000);
346
347 if (!tlsFactoryVerifier.verifier.verify(account.getServer(), verifiedHostname, ((SSLSocket) localSocket).getSession())) {
348 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
349 if (!iterator.hasNext()) {
350 throw new StateChangingException(Account.State.TLS_ERROR);
351 }
352 }
353 }
354 localSocket.setSoTimeout(Config.SOCKET_TIMEOUT * 1000);
355 if (startXmpp(localSocket)) {
356 localSocket.setSoTimeout(0); //reset to 0; once the connection is established we don’t want this
357 if (!hardcoded && !result.equals(storedBackupResult)) {
358 mXmppConnectionService.databaseBackend.saveResolverResult(domain, result);
359 }
360 break; // successfully connected to server that speaks xmpp
361 } else {
362 localSocket.close();
363 if (!iterator.hasNext()) {
364 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
365 }
366 }
367 } catch (final StateChangingException e) {
368 throw e;
369 } catch (InterruptedException e) {
370 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": thread was interrupted before beginning stream");
371 return;
372 } catch (final Throwable e) {
373 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage() + "(" + e.getClass().getName() + ")");
374 if (!iterator.hasNext()) {
375 throw new UnknownHostException();
376 }
377 }
378 }
379 }
380 processStream();
381 } catch (final SecurityException e) {
382 this.changeStatus(Account.State.MISSING_INTERNET_PERMISSION);
383 } catch (final StateChangingException e) {
384 this.changeStatus(e.state);
385 } catch (final UnknownHostException | ConnectException e) {
386 this.changeStatus(Account.State.SERVER_NOT_FOUND);
387 } catch (final SocksSocketFactory.SocksProxyNotFoundException e) {
388 this.changeStatus(Account.State.TOR_NOT_AVAILABLE);
389 } catch (final IOException | XmlPullParserException e) {
390 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": " + e.getMessage());
391 this.changeStatus(Account.State.OFFLINE);
392 this.attempt = Math.max(0, this.attempt - 1);
393 } finally {
394 if (!Thread.currentThread().isInterrupted()) {
395 forceCloseSocket();
396 } else {
397 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not force closing socket because thread was interrupted");
398 }
399 }
400 }
401
402 /**
403 * Starts xmpp protocol, call after connecting to socket
404 *
405 * @return true if server returns with valid xmpp, false otherwise
406 */
407 private boolean startXmpp(Socket socket) throws Exception {
408 if (Thread.currentThread().isInterrupted()) {
409 throw new InterruptedException();
410 }
411 this.socket = socket;
412 tagReader = new XmlReader();
413 if (tagWriter != null) {
414 tagWriter.forceClose();
415 }
416 tagWriter = new TagWriter();
417 tagWriter.setOutputStream(socket.getOutputStream());
418 tagReader.setInputStream(socket.getInputStream());
419 tagWriter.beginDocument();
420 sendStartStream();
421 final Tag tag = tagReader.readTag();
422 if (Thread.currentThread().isInterrupted()) {
423 throw new InterruptedException();
424 }
425 if (socket instanceof SSLSocket) {
426 SSLSocketHelper.log(account, (SSLSocket) socket);
427 }
428 return tag != null && tag.isStart("stream");
429 }
430
431 private TlsFactoryVerifier getTlsFactoryVerifier() throws NoSuchAlgorithmException, KeyManagementException, IOException {
432 final SSLContext sc = SSLSocketHelper.getSSLContext();
433 MemorizingTrustManager trustManager = this.mXmppConnectionService.getMemorizingTrustManager();
434 KeyManager[] keyManager;
435 if (account.getPrivateKeyAlias() != null && account.getPassword().isEmpty()) {
436 keyManager = new KeyManager[]{new MyKeyManager()};
437 } else {
438 keyManager = null;
439 }
440 String domain = account.getJid().getDomain();
441 sc.init(keyManager, new X509TrustManager[]{mInteractive ? trustManager.getInteractive(domain) : trustManager.getNonInteractive(domain)}, mXmppConnectionService.getRNG());
442 final SSLSocketFactory factory = sc.getSocketFactory();
443 final DomainHostnameVerifier verifier = trustManager.wrapHostnameVerifier(new XmppDomainVerifier(), mInteractive);
444 return new TlsFactoryVerifier(factory, verifier);
445 }
446
447 @Override
448 public void run() {
449 synchronized (this) {
450 this.mThread = Thread.currentThread();
451 if (this.mThread.isInterrupted()) {
452 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": aborting connect because thread was interrupted");
453 return;
454 }
455 forceCloseSocket();
456 }
457 connect();
458 }
459
460 private void processStream() throws XmlPullParserException, IOException {
461 final CountDownLatch streamCountDownLatch = new CountDownLatch(1);
462 this.mStreamCountDownLatch = streamCountDownLatch;
463 Tag nextTag = tagReader.readTag();
464 while (nextTag != null && !nextTag.isEnd("stream")) {
465 if (nextTag.isStart("error")) {
466 processStreamError(nextTag);
467 } else if (nextTag.isStart("features")) {
468 processStreamFeatures(nextTag);
469 } else if (nextTag.isStart("proceed")) {
470 switchOverToTls();
471 } else if (nextTag.isStart("success")) {
472 final String challenge = tagReader.readElement(nextTag).getContent();
473 try {
474 saslMechanism.getResponse(challenge);
475 } catch (final SaslMechanism.AuthenticationException e) {
476 Log.e(Config.LOGTAG, String.valueOf(e));
477 throw new StateChangingException(Account.State.UNAUTHORIZED);
478 }
479 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": logged in");
480 account.setKey(Account.PINNED_MECHANISM_KEY,
481 String.valueOf(saslMechanism.getPriority()));
482 tagReader.reset();
483 sendStartStream();
484 final Tag tag = tagReader.readTag();
485 if (tag != null && tag.isStart("stream")) {
486 processStream();
487 } else {
488 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
489 }
490 break;
491 } else if (nextTag.isStart("failure")) {
492 final Element failure = tagReader.readElement(nextTag);
493 if (Namespace.SASL.equals(failure.getNamespace())) {
494 final String text = failure.findChildContent("text");
495 if (failure.hasChild("account-disabled") && text != null) {
496 Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(text);
497 if (matcher.find()) {
498 try {
499 URL url = new URL(text.substring(matcher.start(), matcher.end()));
500 if (url.getProtocol().equals("https")) {
501 this.redirectionUrl = url;
502 throw new StateChangingException(Account.State.PAYMENT_REQUIRED);
503 }
504 } catch (MalformedURLException e) {
505 throw new StateChangingException(Account.State.UNAUTHORIZED);
506 }
507 }
508 }
509 throw new StateChangingException(Account.State.UNAUTHORIZED);
510 } else if (Namespace.TLS.equals(failure.getNamespace())) {
511 throw new StateChangingException(Account.State.TLS_ERROR);
512 } else {
513 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
514 }
515 } else if (nextTag.isStart("challenge")) {
516 final String challenge = tagReader.readElement(nextTag).getContent();
517 final Element response = new Element("response", Namespace.SASL);
518 try {
519 response.setContent(saslMechanism.getResponse(challenge));
520 } catch (final SaslMechanism.AuthenticationException e) {
521 // TODO: Send auth abort tag.
522 Log.e(Config.LOGTAG, e.toString());
523 }
524 tagWriter.writeElement(response);
525 } else if (nextTag.isStart("enabled")) {
526 final Element enabled = tagReader.readElement(nextTag);
527 if ("true".equals(enabled.getAttribute("resume"))) {
528 this.streamId = enabled.getAttribute("id");
529 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
530 + ": stream management(" + smVersion
531 + ") enabled (resumable)");
532 } else {
533 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
534 + ": stream management(" + smVersion + ") enabled");
535 }
536 this.stanzasReceived = 0;
537 this.inSmacksSession = true;
538 final RequestPacket r = new RequestPacket(smVersion);
539 tagWriter.writeStanzaAsync(r);
540 } else if (nextTag.isStart("resumed")) {
541 this.inSmacksSession = true;
542 this.isBound = true;
543 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
544 lastPacketReceived = SystemClock.elapsedRealtime();
545 final Element resumed = tagReader.readElement(nextTag);
546 final String h = resumed.getAttribute("h");
547 try {
548 ArrayList<AbstractAcknowledgeableStanza> failedStanzas = new ArrayList<>();
549 final boolean acknowledgedMessages;
550 synchronized (this.mStanzaQueue) {
551 final int serverCount = Integer.parseInt(h);
552 if (serverCount < stanzasSent) {
553 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString()
554 + ": session resumed with lost packages");
555 stanzasSent = serverCount;
556 } else {
557 Log.d(Config.LOGTAG, account.getJid().asBareJid().toString() + ": session resumed");
558 }
559 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
560 for (int i = 0; i < this.mStanzaQueue.size(); ++i) {
561 failedStanzas.add(mStanzaQueue.valueAt(i));
562 }
563 mStanzaQueue.clear();
564 }
565 if (acknowledgedMessages) {
566 mXmppConnectionService.updateConversationUi();
567 }
568 Log.d(Config.LOGTAG, "resending " + failedStanzas.size() + " stanzas");
569 for (AbstractAcknowledgeableStanza packet : failedStanzas) {
570 if (packet instanceof MessagePacket) {
571 MessagePacket message = (MessagePacket) packet;
572 mXmppConnectionService.markMessage(account,
573 message.getTo().asBareJid(),
574 message.getId(),
575 Message.STATUS_UNSEND);
576 }
577 sendPacket(packet);
578 }
579 } catch (final NumberFormatException ignored) {
580 }
581 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
582 changeStatus(Account.State.ONLINE);
583 } else if (nextTag.isStart("r")) {
584 tagReader.readElement(nextTag);
585 if (Config.EXTENDED_SM_LOGGING) {
586 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": acknowledging stanza #" + this.stanzasReceived);
587 }
588 final AckPacket ack = new AckPacket(this.stanzasReceived, smVersion);
589 tagWriter.writeStanzaAsync(ack);
590 } else if (nextTag.isStart("a")) {
591 boolean accountUiNeedsRefresh = false;
592 synchronized (NotificationService.CATCHUP_LOCK) {
593 if (mWaitingForSmCatchup.compareAndSet(true, false)) {
594 int count = mSmCatchupMessageCounter.get();
595 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": SM catchup complete (" + count + ")");
596 accountUiNeedsRefresh = true;
597 if (count > 0) {
598 mXmppConnectionService.getNotificationService().finishBacklog(true, account);
599 }
600 }
601 }
602 if (accountUiNeedsRefresh) {
603 mXmppConnectionService.updateAccountUi();
604 }
605 final Element ack = tagReader.readElement(nextTag);
606 lastPacketReceived = SystemClock.elapsedRealtime();
607 try {
608 final boolean acknowledgedMessages;
609 synchronized (this.mStanzaQueue) {
610 final int serverSequence = Integer.parseInt(ack.getAttribute("h"));
611 acknowledgedMessages = acknowledgeStanzaUpTo(serverSequence);
612 }
613 if (acknowledgedMessages) {
614 mXmppConnectionService.updateConversationUi();
615 }
616 } catch (NumberFormatException | NullPointerException e) {
617 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server send ack without sequence number");
618 }
619 } else if (nextTag.isStart("failed")) {
620 Element failed = tagReader.readElement(nextTag);
621 try {
622 final int serverCount = Integer.parseInt(failed.getAttribute("h"));
623 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed but server acknowledged stanza #" + serverCount);
624 final boolean acknowledgedMessages;
625 synchronized (this.mStanzaQueue) {
626 acknowledgedMessages = acknowledgeStanzaUpTo(serverCount);
627 }
628 if (acknowledgedMessages) {
629 mXmppConnectionService.updateConversationUi();
630 }
631 } catch (NumberFormatException | NullPointerException e) {
632 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resumption failed");
633 }
634 resetStreamId();
635 sendBindRequest();
636 } else if (nextTag.isStart("iq")) {
637 processIq(nextTag);
638 } else if (nextTag.isStart("message")) {
639 processMessage(nextTag);
640 } else if (nextTag.isStart("presence")) {
641 processPresence(nextTag);
642 }
643 nextTag = tagReader.readTag();
644 }
645 if (nextTag != null && nextTag.isEnd("stream")) {
646 streamCountDownLatch.countDown();
647 }
648 }
649
650 private boolean acknowledgeStanzaUpTo(int serverCount) {
651 if (serverCount > stanzasSent) {
652 Log.e(Config.LOGTAG, "server acknowledged more stanzas than we sent. serverCount=" + serverCount + ", ourCount=" + stanzasSent);
653 }
654 boolean acknowledgedMessages = false;
655 for (int i = 0; i < mStanzaQueue.size(); ++i) {
656 if (serverCount >= mStanzaQueue.keyAt(i)) {
657 if (Config.EXTENDED_SM_LOGGING) {
658 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server acknowledged stanza #" + mStanzaQueue.keyAt(i));
659 }
660 AbstractAcknowledgeableStanza stanza = mStanzaQueue.valueAt(i);
661 if (stanza instanceof MessagePacket && acknowledgedListener != null) {
662 MessagePacket packet = (MessagePacket) stanza;
663 acknowledgedMessages |= acknowledgedListener.onMessageAcknowledged(account, packet.getId());
664 }
665 mStanzaQueue.removeAt(i);
666 i--;
667 }
668 }
669 return acknowledgedMessages;
670 }
671
672 private @NonNull
673 Element processPacket(final Tag currentTag, final int packetType) throws XmlPullParserException, IOException {
674 Element element;
675 switch (packetType) {
676 case PACKET_IQ:
677 element = new IqPacket();
678 break;
679 case PACKET_MESSAGE:
680 element = new MessagePacket();
681 break;
682 case PACKET_PRESENCE:
683 element = new PresencePacket();
684 break;
685 default:
686 throw new AssertionError("Should never encounter invalid type");
687 }
688 element.setAttributes(currentTag.getAttributes());
689 Tag nextTag = tagReader.readTag();
690 if (nextTag == null) {
691 throw new IOException("interrupted mid tag");
692 }
693 while (!nextTag.isEnd(element.getName())) {
694 if (!nextTag.isNo()) {
695 final Element child = tagReader.readElement(nextTag);
696 final String type = currentTag.getAttribute("type");
697 if (packetType == PACKET_IQ
698 && "jingle".equals(child.getName())
699 && ("set".equalsIgnoreCase(type) || "get"
700 .equalsIgnoreCase(type))) {
701 element = new JinglePacket();
702 element.setAttributes(currentTag.getAttributes());
703 }
704 element.addChild(child);
705 }
706 nextTag = tagReader.readTag();
707 if (nextTag == null) {
708 throw new IOException("interrupted mid tag");
709 }
710 }
711 if (stanzasReceived == Integer.MAX_VALUE) {
712 resetStreamId();
713 throw new IOException("time to restart the session. cant handle >2 billion pcks");
714 }
715 if (inSmacksSession) {
716 ++stanzasReceived;
717 } else if (features.sm()) {
718 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": not counting stanza(" + element.getClass().getSimpleName() + "). Not in smacks session.");
719 }
720 lastPacketReceived = SystemClock.elapsedRealtime();
721 if (Config.BACKGROUND_STANZA_LOGGING && mXmppConnectionService.checkListeners()) {
722 Log.d(Config.LOGTAG, "[background stanza] " + element);
723 }
724 return element;
725 }
726
727 private void processIq(final Tag currentTag) throws XmlPullParserException, IOException {
728 final IqPacket packet = (IqPacket) processPacket(currentTag, PACKET_IQ);
729 if (!packet.valid()) {
730 Log.e(Config.LOGTAG, "encountered invalid iq from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
731 return;
732 }
733 if (packet instanceof JinglePacket) {
734 if (this.jingleListener != null) {
735 this.jingleListener.onJinglePacketReceived(account, (JinglePacket) packet);
736 }
737 } else {
738 OnIqPacketReceived callback = null;
739 synchronized (this.packetCallbacks) {
740 if (packetCallbacks.containsKey(packet.getId())) {
741 final Pair<IqPacket, OnIqPacketReceived> packetCallbackDuple = packetCallbacks.get(packet.getId());
742 // Packets to the server should have responses from the server
743 if (packetCallbackDuple.first.toServer(account)) {
744 if (packet.fromServer(account)) {
745 callback = packetCallbackDuple.second;
746 packetCallbacks.remove(packet.getId());
747 } else {
748 Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
749 }
750 } else {
751 if (packet.getFrom() != null && packet.getFrom().equals(packetCallbackDuple.first.getTo())) {
752 callback = packetCallbackDuple.second;
753 packetCallbacks.remove(packet.getId());
754 } else {
755 Log.e(Config.LOGTAG, account.getJid().asBareJid().toString() + ": ignoring spoofed iq packet");
756 }
757 }
758 } else if (packet.getType() == IqPacket.TYPE.GET || packet.getType() == IqPacket.TYPE.SET) {
759 callback = this.unregisteredIqListener;
760 }
761 }
762 if (callback != null) {
763 try {
764 callback.onIqPacketReceived(account, packet);
765 } catch (StateChangingError error) {
766 throw new StateChangingException(error.state);
767 }
768 }
769 }
770 }
771
772 private void processMessage(final Tag currentTag) throws XmlPullParserException, IOException {
773 final MessagePacket packet = (MessagePacket) processPacket(currentTag, PACKET_MESSAGE);
774 if (!packet.valid()) {
775 Log.e(Config.LOGTAG, "encountered invalid message from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
776 return;
777 }
778 this.messageListener.onMessagePacketReceived(account, packet);
779 }
780
781 private void processPresence(final Tag currentTag) throws XmlPullParserException, IOException {
782 PresencePacket packet = (PresencePacket) processPacket(currentTag, PACKET_PRESENCE);
783 if (!packet.valid()) {
784 Log.e(Config.LOGTAG, "encountered invalid presence from='" + packet.getFrom() + "' to='" + packet.getTo() + "'");
785 return;
786 }
787 this.presenceListener.onPresencePacketReceived(account, packet);
788 }
789
790 private void sendStartTLS() throws IOException {
791 final Tag startTLS = Tag.empty("starttls");
792 startTLS.setAttribute("xmlns", Namespace.TLS);
793 tagWriter.writeTag(startTLS);
794 }
795
796 private void switchOverToTls() throws XmlPullParserException, IOException {
797 tagReader.readTag();
798 try {
799 final TlsFactoryVerifier tlsFactoryVerifier = getTlsFactoryVerifier();
800 final InetAddress address = socket == null ? null : socket.getInetAddress();
801
802 if (address == null) {
803 throw new IOException("could not setup ssl");
804 }
805
806 final SSLSocket sslSocket = (SSLSocket) tlsFactoryVerifier.factory.createSocket(socket, address.getHostAddress(), socket.getPort(), true);
807
808
809 if (sslSocket == null) {
810 throw new IOException("could not initialize ssl socket");
811 }
812
813 SSLSocketHelper.setSecurity(sslSocket);
814 SSLSocketHelper.setHostname(sslSocket, account.getServer());
815 SSLSocketHelper.setApplicationProtocol(sslSocket, "xmpp-client");
816
817 if (!tlsFactoryVerifier.verifier.verify(account.getServer(), this.verifiedHostname, sslSocket.getSession())) {
818 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
819 throw new StateChangingException(Account.State.TLS_ERROR);
820 }
821 tagReader.setInputStream(sslSocket.getInputStream());
822 tagWriter.setOutputStream(sslSocket.getOutputStream());
823 sendStartStream();
824 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS connection established");
825 features.encryptionEnabled = true;
826 final Tag tag = tagReader.readTag();
827 if (tag != null && tag.isStart("stream")) {
828 SSLSocketHelper.log(account, sslSocket);
829 processStream();
830 } else {
831 throw new StateChangingException(Account.State.STREAM_OPENING_ERROR);
832 }
833 sslSocket.close();
834 } catch (final NoSuchAlgorithmException | KeyManagementException e1) {
835 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": TLS certificate verification failed");
836 throw new StateChangingException(Account.State.TLS_ERROR);
837 }
838 }
839
840 private void processStreamFeatures(final Tag currentTag) throws XmlPullParserException, IOException {
841 this.streamFeatures = tagReader.readElement(currentTag);
842 final boolean isSecure = features.encryptionEnabled || Config.ALLOW_NON_TLS_CONNECTIONS;
843 final boolean needsBinding = !isBound && !account.isOptionSet(Account.OPTION_REGISTER);
844 if (this.streamFeatures.hasChild("starttls") && !features.encryptionEnabled) {
845 sendStartTLS();
846 } else if (this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
847 if (isSecure) {
848 sendRegistryRequest();
849 } else {
850 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
851 }
852 } else if (!this.streamFeatures.hasChild("register") && account.isOptionSet(Account.OPTION_REGISTER)) {
853 throw new StateChangingException(Account.State.REGISTRATION_NOT_SUPPORTED);
854 } else if (this.streamFeatures.hasChild("mechanisms") && shouldAuthenticate && isSecure) {
855 authenticate();
856 } else if (this.streamFeatures.hasChild("sm", "urn:xmpp:sm:" + smVersion) && streamId != null) {
857 if (Config.EXTENDED_SM_LOGGING) {
858 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": resuming after stanza #" + stanzasReceived);
859 }
860 final ResumePacket resume = new ResumePacket(this.streamId, stanzasReceived, smVersion);
861 this.mSmCatchupMessageCounter.set(0);
862 this.mWaitingForSmCatchup.set(true);
863 this.tagWriter.writeStanzaAsync(resume);
864 } else if (needsBinding) {
865 if (this.streamFeatures.hasChild("bind") && isSecure) {
866 sendBindRequest();
867 } else {
868 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
869 }
870 }
871 }
872
873 private void authenticate() throws IOException {
874 final List<String> mechanisms = extractMechanisms(streamFeatures
875 .findChild("mechanisms"));
876 final Element auth = new Element("auth", Namespace.SASL);
877 if (mechanisms.contains("EXTERNAL") && account.getPrivateKeyAlias() != null) {
878 saslMechanism = new External(tagWriter, account, mXmppConnectionService.getRNG());
879 } else if (mechanisms.contains("SCRAM-SHA-256")) {
880 saslMechanism = new ScramSha256(tagWriter, account, mXmppConnectionService.getRNG());
881 } else if (mechanisms.contains("SCRAM-SHA-1")) {
882 saslMechanism = new ScramSha1(tagWriter, account, mXmppConnectionService.getRNG());
883 } else if (mechanisms.contains("PLAIN") && !account.getJid().getDomain().equals("nimbuzz.com")) {
884 saslMechanism = new Plain(tagWriter, account);
885 } else if (mechanisms.contains("DIGEST-MD5")) {
886 saslMechanism = new DigestMd5(tagWriter, account, mXmppConnectionService.getRNG());
887 } else if (mechanisms.contains("ANONYMOUS")) {
888 saslMechanism = new Anonymous(tagWriter, account, mXmppConnectionService.getRNG());
889 }
890 if (saslMechanism != null) {
891 final int pinnedMechanism = account.getKeyAsInt(Account.PINNED_MECHANISM_KEY, -1);
892 if (pinnedMechanism > saslMechanism.getPriority()) {
893 Log.e(Config.LOGTAG, "Auth failed. Authentication mechanism " + saslMechanism.getMechanism() +
894 " has lower priority (" + String.valueOf(saslMechanism.getPriority()) +
895 ") than pinned priority (" + pinnedMechanism +
896 "). Possible downgrade attack?");
897 throw new StateChangingException(Account.State.DOWNGRADE_ATTACK);
898 }
899 Log.d(Config.LOGTAG, account.getJid().toString() + ": Authenticating with " + saslMechanism.getMechanism());
900 auth.setAttribute("mechanism", saslMechanism.getMechanism());
901 if (!saslMechanism.getClientFirstMessage().isEmpty()) {
902 auth.setContent(saslMechanism.getClientFirstMessage());
903 }
904 tagWriter.writeElement(auth);
905 } else {
906 throw new StateChangingException(Account.State.INCOMPATIBLE_SERVER);
907 }
908 }
909
910 private List<String> extractMechanisms(final Element stream) {
911 final ArrayList<String> mechanisms = new ArrayList<>(stream
912 .getChildren().size());
913 for (final Element child : stream.getChildren()) {
914 mechanisms.add(child.getContent());
915 }
916 return mechanisms;
917 }
918
919 private void sendRegistryRequest() {
920 final IqPacket register = new IqPacket(IqPacket.TYPE.GET);
921 register.query("jabber:iq:register");
922 register.setTo(Jid.of(account.getServer()));
923 sendUnmodifiedIqPacket(register, (account, packet) -> {
924 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
925 return;
926 }
927 if (packet.getType() == IqPacket.TYPE.ERROR) {
928 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
929 }
930 final Element query = packet.query("jabber:iq:register");
931 if (query.hasChild("username") && (query.hasChild("password"))) {
932 final IqPacket register1 = new IqPacket(IqPacket.TYPE.SET);
933 final Element username = new Element("username").setContent(account.getUsername());
934 final Element password = new Element("password").setContent(account.getPassword());
935 register1.query("jabber:iq:register").addChild(username);
936 register1.query().addChild(password);
937 register1.setFrom(account.getJid().asBareJid());
938 sendUnmodifiedIqPacket(register1, registrationResponseListener, true);
939 } else if (query.hasChild("x", Namespace.DATA)) {
940 final Data data = Data.parse(query.findChild("x", Namespace.DATA));
941 final Element blob = query.findChild("data", "urn:xmpp:bob");
942 final String id = packet.getId();
943 InputStream is;
944 if (blob != null) {
945 try {
946 final String base64Blob = blob.getContent();
947 final byte[] strBlob = Base64.decode(base64Blob, Base64.DEFAULT);
948 is = new ByteArrayInputStream(strBlob);
949 } catch (Exception e) {
950 is = null;
951 }
952 } else {
953 try {
954 Field field = data.getFieldByName("url");
955 URL url = field != null && field.getValue() != null ? new URL(field.getValue()) : null;
956 is = url != null ? url.openStream() : null;
957 } catch (IOException e) {
958 is = null;
959 }
960 }
961
962 if (is != null) {
963 Bitmap captcha = BitmapFactory.decodeStream(is);
964 try {
965 if (mXmppConnectionService.displayCaptchaRequest(account, id, data, captcha)) {
966 return;
967 }
968 } catch (Exception e) {
969 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
970 }
971 }
972 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
973 } else if (query.hasChild("instructions") || query.hasChild("x", Namespace.OOB)) {
974 final String instructions = query.findChildContent("instructions");
975 final Element oob = query.findChild("x", Namespace.OOB);
976 final String url = oob == null ? null : oob.findChildContent("url");
977 if (url != null) {
978 setAccountCreationFailed(url);
979 } else if (instructions != null) {
980 Matcher matcher = Patterns.AUTOLINK_WEB_URL.matcher(instructions);
981 if (matcher.find()) {
982 setAccountCreationFailed(instructions.substring(matcher.start(), matcher.end()));
983 }
984 }
985 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
986 }
987 }, true);
988 }
989
990 private void setAccountCreationFailed(String url) {
991 if (url != null) {
992 try {
993 this.redirectionUrl = new URL(url);
994 if (this.redirectionUrl.getProtocol().equals("https")) {
995 throw new StateChangingError(Account.State.REGISTRATION_WEB);
996 }
997 } catch (MalformedURLException e) {
998 //fall through
999 }
1000 }
1001 throw new StateChangingError(Account.State.REGISTRATION_FAILED);
1002 }
1003
1004 public URL getRedirectionUrl() {
1005 return this.redirectionUrl;
1006 }
1007
1008 public void resetEverything() {
1009 resetAttemptCount(true);
1010 resetStreamId();
1011 clearIqCallbacks();
1012 this.stanzasSent = 0;
1013 mStanzaQueue.clear();
1014 this.redirectionUrl = null;
1015 synchronized (this.disco) {
1016 disco.clear();
1017 }
1018 }
1019
1020 private void sendBindRequest() {
1021 try {
1022 mXmppConnectionService.restoredFromDatabaseLatch.await();
1023 } catch (InterruptedException e) {
1024 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while waiting for DB restore during bind");
1025 return;
1026 }
1027 clearIqCallbacks();
1028 if (account.getJid().isBareJid()) {
1029 account.setResource(this.createNewResource());
1030 } else {
1031 fixResource(mXmppConnectionService, account);
1032 }
1033 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1034 final String resource = Config.USE_RANDOM_RESOURCE_ON_EVERY_BIND ? nextRandomId() : account.getResource();
1035 iq.addChild("bind", Namespace.BIND).addChild("resource").setContent(resource);
1036 this.sendUnmodifiedIqPacket(iq, (account, packet) -> {
1037 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1038 return;
1039 }
1040 final Element bind = packet.findChild("bind");
1041 if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
1042 isBound = true;
1043 final Element jid = bind.findChild("jid");
1044 if (jid != null && jid.getContent() != null) {
1045 try {
1046 Jid assignedJid = Jid.ofEscaped(jid.getContent());
1047 if (!account.getJid().getDomain().equals(assignedJid.getDomain())) {
1048 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server tried to re-assign domain to " + assignedJid.getDomain());
1049 throw new StateChangingError(Account.State.BIND_FAILURE);
1050 }
1051 if (account.setJid(assignedJid)) {
1052 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": jid changed during bind. updating database");
1053 mXmppConnectionService.databaseBackend.updateAccount(account);
1054 }
1055 if (streamFeatures.hasChild("session")
1056 && !streamFeatures.findChild("session").hasChild("optional")) {
1057 sendStartSession();
1058 } else {
1059 sendPostBindInitialization();
1060 }
1061 return;
1062 } catch (final IllegalArgumentException e) {
1063 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server reported invalid jid (" + jid.getContent() + ") on bind");
1064 }
1065 } else {
1066 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
1067 }
1068 } else {
1069 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
1070 }
1071 final Element error = packet.findChild("error");
1072 if (packet.getType() == IqPacket.TYPE.ERROR && error != null && error.hasChild("conflict")) {
1073 account.setResource(createNewResource());
1074 }
1075 throw new StateChangingError(Account.State.BIND_FAILURE);
1076 }, true);
1077 }
1078
1079 private void clearIqCallbacks() {
1080 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
1081 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
1082 synchronized (this.packetCallbacks) {
1083 if (this.packetCallbacks.size() == 0) {
1084 return;
1085 }
1086 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": clearing " + this.packetCallbacks.size() + " iq callbacks");
1087 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
1088 while (iterator.hasNext()) {
1089 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
1090 callbacks.add(entry.second);
1091 iterator.remove();
1092 }
1093 }
1094 for (OnIqPacketReceived callback : callbacks) {
1095 try {
1096 callback.onIqPacketReceived(account, failurePacket);
1097 } catch (StateChangingError error) {
1098 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": caught StateChangingError(" + error.state.toString() + ") while clearing callbacks");
1099 //ignore
1100 }
1101 }
1102 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
1103 }
1104
1105 public void sendDiscoTimeout() {
1106 if (mWaitForDisco.compareAndSet(true, false)) {
1107 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": finalizing bind after disco timeout");
1108 finalizeBind();
1109 }
1110 }
1111
1112 private void sendStartSession() {
1113 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": sending legacy session to outdated server");
1114 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
1115 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
1116 this.sendUnmodifiedIqPacket(startSession, (account, packet) -> {
1117 if (packet.getType() == IqPacket.TYPE.RESULT) {
1118 sendPostBindInitialization();
1119 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1120 throw new StateChangingError(Account.State.SESSION_FAILURE);
1121 }
1122 }, true);
1123 }
1124
1125 private void sendPostBindInitialization() {
1126 smVersion = 0;
1127 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1128 smVersion = 3;
1129 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1130 smVersion = 2;
1131 }
1132 if (smVersion != 0) {
1133 synchronized (this.mStanzaQueue) {
1134 final EnablePacket enable = new EnablePacket(smVersion);
1135 tagWriter.writeStanzaAsync(enable);
1136 stanzasSent = 0;
1137 mStanzaQueue.clear();
1138 }
1139 }
1140 features.carbonsEnabled = false;
1141 features.blockListRequested = false;
1142 synchronized (this.disco) {
1143 this.disco.clear();
1144 }
1145 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": starting service discovery");
1146 mPendingServiceDiscoveries.set(0);
1147 if (smVersion == 0 || Patches.DISCO_EXCEPTIONS.contains(account.getJid().getDomain())) {
1148 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": do not wait for service discovery");
1149 mWaitForDisco.set(false);
1150 } else {
1151 mWaitForDisco.set(true);
1152 }
1153 lastDiscoStarted = SystemClock.elapsedRealtime();
1154 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1155 Element caps = streamFeatures.findChild("c");
1156 final String hash = caps == null ? null : caps.getAttribute("hash");
1157 final String ver = caps == null ? null : caps.getAttribute("ver");
1158 ServiceDiscoveryResult discoveryResult = null;
1159 if (hash != null && ver != null) {
1160 discoveryResult = mXmppConnectionService.getCachedServiceDiscoveryResult(new Pair<>(hash, ver));
1161 }
1162 final boolean requestDiscoItemsFirst = !account.isOptionSet(Account.OPTION_LOGGED_IN_SUCCESSFULLY);
1163 if (requestDiscoItemsFirst) {
1164 sendServiceDiscoveryItems(Jid.of(account.getServer()));
1165 }
1166 if (discoveryResult == null) {
1167 sendServiceDiscoveryInfo(Jid.of(account.getServer()));
1168 } else {
1169 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server caps came from cache");
1170 disco.put(Jid.of(account.getServer()), discoveryResult);
1171 }
1172 discoverMamPreferences();
1173 sendServiceDiscoveryInfo(account.getJid().asBareJid());
1174 if (!requestDiscoItemsFirst) {
1175 sendServiceDiscoveryItems(Jid.of(account.getServer()));
1176 }
1177
1178 if (!mWaitForDisco.get()) {
1179 finalizeBind();
1180 }
1181 this.lastSessionStarted = SystemClock.elapsedRealtime();
1182 }
1183
1184 private void sendServiceDiscoveryInfo(final Jid jid) {
1185 mPendingServiceDiscoveries.incrementAndGet();
1186 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1187 iq.setTo(jid);
1188 iq.query("http://jabber.org/protocol/disco#info");
1189 this.sendIqPacket(iq, (account, packet) -> {
1190 if (packet.getType() == IqPacket.TYPE.RESULT) {
1191 boolean advancedStreamFeaturesLoaded;
1192 synchronized (XmppConnection.this.disco) {
1193 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1194 if (jid.equals(Jid.of(account.getServer()))) {
1195 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1196 }
1197 disco.put(jid, result);
1198 advancedStreamFeaturesLoaded = disco.containsKey(Jid.of(account.getServer()))
1199 && disco.containsKey(account.getJid().asBareJid());
1200 }
1201 if (advancedStreamFeaturesLoaded && (jid.equals(Jid.of(account.getServer())) || jid.equals(account.getJid().asBareJid()))) {
1202 enableAdvancedStreamFeatures();
1203 }
1204 } else {
1205 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco info for " + jid.toString());
1206 }
1207 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1208 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1209 && mWaitForDisco.compareAndSet(true, false)) {
1210 finalizeBind();
1211 }
1212 }
1213 });
1214 }
1215
1216 private void discoverMamPreferences() {
1217 IqPacket request = new IqPacket(IqPacket.TYPE.GET);
1218 request.addChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1219 sendIqPacket(request, (account, response) -> {
1220 if (response.getType() == IqPacket.TYPE.RESULT) {
1221 Element prefs = response.findChild("prefs", MessageArchiveService.Version.MAM_2.namespace);
1222 isMamPreferenceAlways = "always".equals(prefs == null ? null : prefs.getAttribute("default"));
1223 }
1224 });
1225 }
1226
1227 public boolean isMamPreferenceAlways() {
1228 return isMamPreferenceAlways;
1229 }
1230
1231 private void finalizeBind() {
1232 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": online with resource " + account.getResource());
1233 if (bindListener != null) {
1234 bindListener.onBind(account);
1235 }
1236 changeStatus(Account.State.ONLINE);
1237 }
1238
1239 private void enableAdvancedStreamFeatures() {
1240 if (getFeatures().carbons() && !features.carbonsEnabled) {
1241 sendEnableCarbons();
1242 }
1243 if (getFeatures().blocking() && !features.blockListRequested) {
1244 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": Requesting block list");
1245 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1246 }
1247 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1248 listener.onAdvancedStreamFeaturesAvailable(account);
1249 }
1250 }
1251
1252 private void sendServiceDiscoveryItems(final Jid server) {
1253 mPendingServiceDiscoveries.incrementAndGet();
1254 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1255 iq.setTo(Jid.ofDomain(server.getDomain()));
1256 iq.query("http://jabber.org/protocol/disco#items");
1257 this.sendIqPacket(iq, (account, packet) -> {
1258 if (packet.getType() == IqPacket.TYPE.RESULT) {
1259 HashSet<Jid> items = new HashSet<Jid>();
1260 final List<Element> elements = packet.query().getChildren();
1261 for (final Element element : elements) {
1262 if (element.getName().equals("item")) {
1263 final Jid jid = InvalidJid.getNullForInvalid(element.getAttributeAsJid("jid"));
1264 if (jid != null && !jid.equals(Jid.of(account.getServer()))) {
1265 items.add(jid);
1266 }
1267 }
1268 }
1269 for (Jid jid : items) {
1270 sendServiceDiscoveryInfo(jid);
1271 }
1272 } else {
1273 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": could not query disco items of " + server);
1274 }
1275 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1276 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1277 && mWaitForDisco.compareAndSet(true, false)) {
1278 finalizeBind();
1279 }
1280 }
1281 });
1282 }
1283
1284 private void sendEnableCarbons() {
1285 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1286 iq.addChild("enable", "urn:xmpp:carbons:2");
1287 this.sendIqPacket(iq, new OnIqPacketReceived() {
1288
1289 @Override
1290 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1291 if (!packet.hasChild("error")) {
1292 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1293 + ": successfully enabled carbons");
1294 features.carbonsEnabled = true;
1295 } else {
1296 Log.d(Config.LOGTAG, account.getJid().asBareJid()
1297 + ": error enableing carbons " + packet.toString());
1298 }
1299 }
1300 });
1301 }
1302
1303 private void processStreamError(final Tag currentTag) throws XmlPullParserException, IOException {
1304 final Element streamError = tagReader.readElement(currentTag);
1305 if (streamError == null) {
1306 return;
1307 }
1308 if (streamError.hasChild("conflict")) {
1309 account.setResource(createNewResource());
1310 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": switching resource due to conflict (" + account.getResource() + ")");
1311 throw new IOException();
1312 } else if (streamError.hasChild("host-unknown")) {
1313 throw new StateChangingException(Account.State.HOST_UNKNOWN);
1314 } else if (streamError.hasChild("policy-violation")) {
1315 throw new StateChangingException(Account.State.POLICY_VIOLATION);
1316 } else {
1317 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": stream error " + streamError.toString());
1318 throw new StateChangingException(Account.State.STREAM_ERROR);
1319 }
1320 }
1321
1322 private void sendStartStream() throws IOException {
1323 final Tag stream = Tag.start("stream:stream");
1324 stream.setAttribute("to", account.getServer());
1325 stream.setAttribute("version", "1.0");
1326 stream.setAttribute("xml:lang", "en");
1327 stream.setAttribute("xmlns", "jabber:client");
1328 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1329 tagWriter.writeTag(stream);
1330 }
1331
1332 private String createNewResource() {
1333 return mXmppConnectionService.getString(R.string.app_name) + '.' + nextRandomId(true);
1334 }
1335
1336 private String nextRandomId() {
1337 return nextRandomId(false);
1338 }
1339
1340 private String nextRandomId(boolean s) {
1341 return CryptoHelper.random(s ? 3 : 9, mXmppConnectionService.getRNG());
1342 }
1343
1344 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1345 packet.setFrom(account.getJid());
1346 return this.sendUnmodifiedIqPacket(packet, callback, false);
1347 }
1348
1349 public synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback, boolean force) {
1350 if (packet.getId() == null) {
1351 packet.setAttribute("id", nextRandomId());
1352 }
1353 if (callback != null) {
1354 synchronized (this.packetCallbacks) {
1355 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1356 }
1357 }
1358 this.sendPacket(packet, force);
1359 return packet.getId();
1360 }
1361
1362 public void sendMessagePacket(final MessagePacket packet) {
1363 this.sendPacket(packet);
1364 }
1365
1366 public void sendPresencePacket(final PresencePacket packet) {
1367 this.sendPacket(packet);
1368 }
1369
1370 private synchronized void sendPacket(final AbstractStanza packet) {
1371 sendPacket(packet, false);
1372 }
1373
1374 private synchronized void sendPacket(final AbstractStanza packet, final boolean force) {
1375 if (stanzasSent == Integer.MAX_VALUE) {
1376 resetStreamId();
1377 disconnect(true);
1378 return;
1379 }
1380 synchronized (this.mStanzaQueue) {
1381 if (force || isBound) {
1382 tagWriter.writeStanzaAsync(packet);
1383 } else {
1384 Log.d(Config.LOGTAG, account.getJid().asBareJid() + " do not write stanza to unbound stream " + packet.toString());
1385 }
1386 if (packet instanceof AbstractAcknowledgeableStanza) {
1387 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1388
1389 if (this.mStanzaQueue.size() != 0) {
1390 int currentHighestKey = this.mStanzaQueue.keyAt(this.mStanzaQueue.size() - 1);
1391 if (currentHighestKey != stanzasSent) {
1392 throw new AssertionError("Stanza count messed up");
1393 }
1394 }
1395
1396 ++stanzasSent;
1397 this.mStanzaQueue.append(stanzasSent, stanza);
1398 if (stanza instanceof MessagePacket && stanza.getId() != null && inSmacksSession) {
1399 if (Config.EXTENDED_SM_LOGGING) {
1400 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1401 }
1402 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1403 }
1404 }
1405 }
1406 }
1407
1408 public void sendPing() {
1409 if (!r()) {
1410 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1411 iq.setFrom(account.getJid());
1412 iq.addChild("ping", "urn:xmpp:ping");
1413 this.sendIqPacket(iq, null);
1414 }
1415 this.lastPingSent = SystemClock.elapsedRealtime();
1416 }
1417
1418 public void setOnMessagePacketReceivedListener(
1419 final OnMessagePacketReceived listener) {
1420 this.messageListener = listener;
1421 }
1422
1423 public void setOnUnregisteredIqPacketReceivedListener(
1424 final OnIqPacketReceived listener) {
1425 this.unregisteredIqListener = listener;
1426 }
1427
1428 public void setOnPresencePacketReceivedListener(
1429 final OnPresencePacketReceived listener) {
1430 this.presenceListener = listener;
1431 }
1432
1433 public void setOnJinglePacketReceivedListener(
1434 final OnJinglePacketReceived listener) {
1435 this.jingleListener = listener;
1436 }
1437
1438 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1439 this.statusListener = listener;
1440 }
1441
1442 public void setOnBindListener(final OnBindListener listener) {
1443 this.bindListener = listener;
1444 }
1445
1446 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1447 this.acknowledgedListener = listener;
1448 }
1449
1450 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1451 this.advancedStreamFeaturesLoadedListeners.add(listener);
1452 }
1453
1454 private void forceCloseSocket() {
1455 if (socket != null) {
1456 try {
1457 socket.close();
1458 } catch (IOException e) {
1459 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception " + e.getMessage() + " during force close");
1460 }
1461 } else {
1462 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": socket was null during force close");
1463 }
1464 }
1465
1466 public void interrupt() {
1467 if (this.mThread != null) {
1468 this.mThread.interrupt();
1469 }
1470 }
1471
1472 public void disconnect(final boolean force) {
1473 interrupt();
1474 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": disconnecting force=" + Boolean.toString(force));
1475 if (force) {
1476 forceCloseSocket();
1477 } else {
1478 final TagWriter currentTagWriter = this.tagWriter;
1479 if (currentTagWriter.isActive()) {
1480 currentTagWriter.finish();
1481 final Socket currentSocket = this.socket;
1482 final CountDownLatch streamCountDownLatch = this.mStreamCountDownLatch;
1483 try {
1484 currentTagWriter.await(1, TimeUnit.SECONDS);
1485 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": closing stream");
1486 currentTagWriter.writeTag(Tag.end("stream:stream"));
1487 if (streamCountDownLatch != null) {
1488 if (streamCountDownLatch.await(1, TimeUnit.SECONDS)) {
1489 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote ended stream");
1490 } else {
1491 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": remote has not closed socket. force closing");
1492 }
1493 }
1494 } catch (InterruptedException e) {
1495 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": interrupted while gracefully closing stream");
1496 } catch (final IOException e) {
1497 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": io exception during disconnect (" + e.getMessage() + ")");
1498 } finally {
1499 FileBackend.close(currentSocket);
1500 }
1501 } else {
1502 forceCloseSocket();
1503 }
1504 }
1505 }
1506
1507 private void resetStreamId() {
1508 this.streamId = null;
1509 }
1510
1511 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1512 synchronized (this.disco) {
1513 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1514 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1515 if (cursor.getValue().getFeatures().contains(feature)) {
1516 items.add(cursor);
1517 }
1518 }
1519 return items;
1520 }
1521 }
1522
1523 public Jid findDiscoItemByFeature(final String feature) {
1524 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1525 if (items.size() >= 1) {
1526 return items.get(0).getKey();
1527 }
1528 return null;
1529 }
1530
1531 public boolean r() {
1532 if (getFeatures().sm()) {
1533 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1534 return true;
1535 } else {
1536 return false;
1537 }
1538 }
1539
1540 public List<String> getMucServersWithholdAccount() {
1541 List<String> servers = getMucServers();
1542 servers.remove(account.getServer());
1543 return servers;
1544 }
1545
1546 public List<String> getMucServers() {
1547 List<String> servers = new ArrayList<>();
1548 synchronized (this.disco) {
1549 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1550 final ServiceDiscoveryResult value = cursor.getValue();
1551 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1552 && value.hasIdentity("conference", "text")
1553 && !value.getFeatures().contains("jabber:iq:gateway")
1554 && !value.hasIdentity("conference", "irc")) {
1555 servers.add(cursor.getKey().toString());
1556 }
1557 }
1558 }
1559 return servers;
1560 }
1561
1562 public String getMucServer() {
1563 List<String> servers = getMucServers();
1564 return servers.size() > 0 ? servers.get(0) : null;
1565 }
1566
1567 public int getTimeToNextAttempt() {
1568 final int interval = Math.min((int) (25 * Math.pow(1.3, attempt)), 300);
1569 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1570 return interval - secondsSinceLast;
1571 }
1572
1573 public int getAttempt() {
1574 return this.attempt;
1575 }
1576
1577 public Features getFeatures() {
1578 return this.features;
1579 }
1580
1581 public long getLastSessionEstablished() {
1582 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1583 return System.currentTimeMillis() - diff;
1584 }
1585
1586 public long getLastConnect() {
1587 return this.lastConnect;
1588 }
1589
1590 public long getLastPingSent() {
1591 return this.lastPingSent;
1592 }
1593
1594 public long getLastDiscoStarted() {
1595 return this.lastDiscoStarted;
1596 }
1597
1598 public long getLastPacketReceived() {
1599 return this.lastPacketReceived;
1600 }
1601
1602 public void sendActive() {
1603 this.sendPacket(new ActivePacket());
1604 }
1605
1606 public void sendInactive() {
1607 this.sendPacket(new InactivePacket());
1608 }
1609
1610 public void resetAttemptCount(boolean resetConnectTime) {
1611 this.attempt = 0;
1612 if (resetConnectTime) {
1613 this.lastConnect = 0;
1614 }
1615 }
1616
1617 public void setInteractive(boolean interactive) {
1618 this.mInteractive = interactive;
1619 }
1620
1621 public Identity getServerIdentity() {
1622 synchronized (this.disco) {
1623 ServiceDiscoveryResult result = disco.get(Jid.ofDomain(account.getJid().getDomain()));
1624 if (result == null) {
1625 return Identity.UNKNOWN;
1626 }
1627 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1628 if (id.getType().equals("im") && id.getCategory().equals("server") && id.getName() != null) {
1629 switch (id.getName()) {
1630 case "Prosody":
1631 return Identity.PROSODY;
1632 case "ejabberd":
1633 return Identity.EJABBERD;
1634 case "Slack-XMPP":
1635 return Identity.SLACK;
1636 }
1637 }
1638 }
1639 }
1640 return Identity.UNKNOWN;
1641 }
1642
1643 private IqGenerator getIqGenerator() {
1644 return mXmppConnectionService.getIqGenerator();
1645 }
1646
1647 public enum Identity {
1648 FACEBOOK,
1649 SLACK,
1650 EJABBERD,
1651 PROSODY,
1652 NIMBUZZ,
1653 UNKNOWN
1654 }
1655
1656 private static class TlsFactoryVerifier {
1657 private final SSLSocketFactory factory;
1658 private final DomainHostnameVerifier verifier;
1659
1660 TlsFactoryVerifier(final SSLSocketFactory factory, final DomainHostnameVerifier verifier) throws IOException {
1661 this.factory = factory;
1662 this.verifier = verifier;
1663 if (factory == null || verifier == null) {
1664 throw new IOException("could not setup ssl");
1665 }
1666 }
1667 }
1668
1669 private class MyKeyManager implements X509KeyManager {
1670 @Override
1671 public String chooseClientAlias(String[] strings, Principal[] principals, Socket socket) {
1672 return account.getPrivateKeyAlias();
1673 }
1674
1675 @Override
1676 public String chooseServerAlias(String s, Principal[] principals, Socket socket) {
1677 return null;
1678 }
1679
1680 @Override
1681 public X509Certificate[] getCertificateChain(String alias) {
1682 Log.d(Config.LOGTAG, "getting certificate chain");
1683 try {
1684 return KeyChain.getCertificateChain(mXmppConnectionService, alias);
1685 } catch (Exception e) {
1686 Log.d(Config.LOGTAG, e.getMessage());
1687 return new X509Certificate[0];
1688 }
1689 }
1690
1691 @Override
1692 public String[] getClientAliases(String s, Principal[] principals) {
1693 final String alias = account.getPrivateKeyAlias();
1694 return alias != null ? new String[]{alias} : new String[0];
1695 }
1696
1697 @Override
1698 public String[] getServerAliases(String s, Principal[] principals) {
1699 return new String[0];
1700 }
1701
1702 @Override
1703 public PrivateKey getPrivateKey(String alias) {
1704 try {
1705 return KeyChain.getPrivateKey(mXmppConnectionService, alias);
1706 } catch (Exception e) {
1707 return null;
1708 }
1709 }
1710 }
1711
1712 private class StateChangingError extends Error {
1713 private final Account.State state;
1714
1715 public StateChangingError(Account.State state) {
1716 this.state = state;
1717 }
1718 }
1719
1720 private class StateChangingException extends IOException {
1721 private final Account.State state;
1722
1723 public StateChangingException(Account.State state) {
1724 this.state = state;
1725 }
1726 }
1727
1728 public class Features {
1729 XmppConnection connection;
1730 private boolean carbonsEnabled = false;
1731 private boolean encryptionEnabled = false;
1732 private boolean blockListRequested = false;
1733
1734 public Features(final XmppConnection connection) {
1735 this.connection = connection;
1736 }
1737
1738 private boolean hasDiscoFeature(final Jid server, final String feature) {
1739 synchronized (XmppConnection.this.disco) {
1740 return connection.disco.containsKey(server) &&
1741 connection.disco.get(server).getFeatures().contains(feature);
1742 }
1743 }
1744
1745 public boolean carbons() {
1746 return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:carbons:2");
1747 }
1748
1749 public boolean bookmarksConversion() {
1750 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.BOOKMARKS_CONVERSION) && pepPublishOptions();
1751 }
1752
1753 public boolean blocking() {
1754 return hasDiscoFeature(Jid.of(account.getServer()), Namespace.BLOCKING);
1755 }
1756
1757 public boolean spamReporting() {
1758 return hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:reporting:reason:spam:0");
1759 }
1760
1761 public boolean flexibleOfflineMessageRetrieval() {
1762 return hasDiscoFeature(Jid.of(account.getServer()), Namespace.FLEXIBLE_OFFLINE_MESSAGE_RETRIEVAL);
1763 }
1764
1765 public boolean register() {
1766 return hasDiscoFeature(Jid.of(account.getServer()), Namespace.REGISTER);
1767 }
1768
1769 public boolean sm() {
1770 return streamId != null
1771 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1772 }
1773
1774 public boolean csi() {
1775 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1776 }
1777
1778 public boolean pep() {
1779 synchronized (XmppConnection.this.disco) {
1780 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1781 return info != null && info.hasIdentity("pubsub", "pep");
1782 }
1783 }
1784
1785 public boolean pepPersistent() {
1786 synchronized (XmppConnection.this.disco) {
1787 ServiceDiscoveryResult info = disco.get(account.getJid().asBareJid());
1788 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1789 }
1790 }
1791
1792 public boolean pepPublishOptions() {
1793 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.PUBSUB_PUBLISH_OPTIONS);
1794 }
1795
1796 public boolean pepOmemoWhitelisted() {
1797 return hasDiscoFeature(account.getJid().asBareJid(), AxolotlService.PEP_OMEMO_WHITELISTED);
1798 }
1799
1800 public boolean mam() {
1801 return MessageArchiveService.Version.has(getAccountFeatures());
1802 }
1803
1804 public List<String> getAccountFeatures() {
1805 ServiceDiscoveryResult result = connection.disco.get(account.getJid().asBareJid());
1806 return result == null ? Collections.emptyList() : result.getFeatures();
1807 }
1808
1809 public boolean push() {
1810 return hasDiscoFeature(account.getJid().asBareJid(), "urn:xmpp:push:0")
1811 || hasDiscoFeature(Jid.of(account.getServer()), "urn:xmpp:push:0");
1812 }
1813
1814 public boolean rosterVersioning() {
1815 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1816 }
1817
1818 public void setBlockListRequested(boolean value) {
1819 this.blockListRequested = value;
1820 }
1821
1822 public boolean p1S3FileTransfer() {
1823 return hasDiscoFeature(Jid.of(account.getServer()), Namespace.P1_S3_FILE_TRANSFER);
1824 }
1825
1826 public boolean httpUpload(long filesize) {
1827 if (Config.DISABLE_HTTP_UPLOAD) {
1828 return false;
1829 } else {
1830 for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1831 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1832 if (items.size() > 0) {
1833 try {
1834 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1835 if (filesize <= maxsize) {
1836 return true;
1837 } else {
1838 Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": http upload is not available for files with size " + filesize + " (max is " + maxsize + ")");
1839 return false;
1840 }
1841 } catch (Exception e) {
1842 return true;
1843 }
1844 }
1845 }
1846 return false;
1847 }
1848 }
1849
1850 public boolean useLegacyHttpUpload() {
1851 return findDiscoItemByFeature(Namespace.HTTP_UPLOAD) == null && findDiscoItemByFeature(Namespace.HTTP_UPLOAD_LEGACY) != null;
1852 }
1853
1854 public long getMaxHttpUploadSize() {
1855 for (String namespace : new String[]{Namespace.HTTP_UPLOAD, Namespace.HTTP_UPLOAD_LEGACY}) {
1856 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(namespace);
1857 if (items.size() > 0) {
1858 try {
1859 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(namespace, "max-file-size"));
1860 } catch (Exception e) {
1861 //ignored
1862 }
1863 }
1864 }
1865 return -1;
1866 }
1867
1868 public boolean stanzaIds() {
1869 return hasDiscoFeature(account.getJid().asBareJid(), Namespace.STANZA_IDS);
1870 }
1871 }
1872}