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