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