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