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