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 resetAttemptCount();
884 resetStreamId();
885 clearIqCallbacks();
886 mStanzaQueue.clear();
887 synchronized (this.disco) {
888 disco.clear();
889 }
890 }
891
892 private void sendBindRequest() {
893 while(!mXmppConnectionService.areMessagesInitialized() && socket != null && !socket.isClosed()) {
894 try {
895 Thread.sleep(500);
896 } catch (final InterruptedException ignored) {
897 }
898 }
899 needsBinding = false;
900 clearIqCallbacks();
901 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
902 iq.addChild("bind", "urn:ietf:params:xml:ns:xmpp-bind")
903 .addChild("resource").setContent(account.getResource());
904 this.sendUnmodifiedIqPacket(iq, new OnIqPacketReceived() {
905 @Override
906 public void onIqPacketReceived(final Account account, final IqPacket packet) {
907 if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
908 return;
909 }
910 final Element bind = packet.findChild("bind");
911 if (bind != null && packet.getType() == IqPacket.TYPE.RESULT) {
912 final Element jid = bind.findChild("jid");
913 if (jid != null && jid.getContent() != null) {
914 try {
915 account.setResource(Jid.fromString(jid.getContent()).getResourcepart());
916 if (streamFeatures.hasChild("session")) {
917 sendStartSession();
918 } else {
919 sendPostBindInitialization();
920 }
921 return;
922 } catch (final InvalidJidException e) {
923 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server reported invalid jid ("+jid.getContent()+") on bind");
924 }
925 } else {
926 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure. (no jid)");
927 }
928 } else {
929 Log.d(Config.LOGTAG, account.getJid() + ": disconnecting because of bind failure (" + packet.toString());
930 }
931 forceCloseSocket();
932 changeStatus(Account.State.BIND_FAILURE);
933 }
934 });
935 }
936
937 private void clearIqCallbacks() {
938 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.TIMEOUT);
939 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
940 synchronized (this.packetCallbacks) {
941 if (this.packetCallbacks.size() == 0) {
942 return;
943 }
944 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": clearing "+this.packetCallbacks.size()+" iq callbacks");
945 final Iterator<Pair<IqPacket, OnIqPacketReceived>> iterator = this.packetCallbacks.values().iterator();
946 while (iterator.hasNext()) {
947 Pair<IqPacket, OnIqPacketReceived> entry = iterator.next();
948 callbacks.add(entry.second);
949 iterator.remove();
950 }
951 }
952 for(OnIqPacketReceived callback : callbacks) {
953 callback.onIqPacketReceived(account,failurePacket);
954 }
955 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": done clearing iq callbacks. " + this.packetCallbacks.size() + " left");
956 }
957
958 public void sendDiscoTimeout() {
959 final IqPacket failurePacket = new IqPacket(IqPacket.TYPE.ERROR); //don't use timeout
960 final ArrayList<OnIqPacketReceived> callbacks = new ArrayList<>();
961 synchronized (this.mPendingServiceDiscoveriesIds) {
962 for(String id : mPendingServiceDiscoveriesIds) {
963 synchronized (this.packetCallbacks) {
964 Pair<IqPacket, OnIqPacketReceived> pair = this.packetCallbacks.remove(id);
965 if (pair != null) {
966 callbacks.add(pair.second);
967 }
968 }
969 }
970 this.mPendingServiceDiscoveriesIds.clear();
971 }
972 if (callbacks.size() > 0) {
973 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": sending disco timeout");
974 resetStreamId(); //we don't want to live with this for ever
975 }
976 for(OnIqPacketReceived callback : callbacks) {
977 callback.onIqPacketReceived(account,failurePacket);
978 }
979 }
980
981 private void sendStartSession() {
982 final IqPacket startSession = new IqPacket(IqPacket.TYPE.SET);
983 startSession.addChild("session", "urn:ietf:params:xml:ns:xmpp-session");
984 this.sendUnmodifiedIqPacket(startSession, new OnIqPacketReceived() {
985 @Override
986 public void onIqPacketReceived(Account account, IqPacket packet) {
987 if (packet.getType() == IqPacket.TYPE.RESULT) {
988 sendPostBindInitialization();
989 } else if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
990 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not init sessions");
991 disconnect(true);
992 }
993 }
994 });
995 }
996
997 private void sendPostBindInitialization() {
998 smVersion = 0;
999 if (streamFeatures.hasChild("sm", "urn:xmpp:sm:3")) {
1000 smVersion = 3;
1001 } else if (streamFeatures.hasChild("sm", "urn:xmpp:sm:2")) {
1002 smVersion = 2;
1003 }
1004 if (smVersion != 0) {
1005 final EnablePacket enable = new EnablePacket(smVersion);
1006 tagWriter.writeStanzaAsync(enable);
1007 stanzasSent = 0;
1008 mStanzaQueue.clear();
1009 }
1010 features.carbonsEnabled = false;
1011 features.blockListRequested = false;
1012 synchronized (this.disco) {
1013 this.disco.clear();
1014 }
1015 mPendingServiceDiscoveries.set(0);
1016 mIsServiceItemsDiscoveryPending.set(true);
1017 mWaitForDisco = mServerIdentity != Identity.NIMBUZZ;
1018 lastDiscoStarted = SystemClock.elapsedRealtime();
1019 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": starting service discovery");
1020 mXmppConnectionService.scheduleWakeUpCall(Config.CONNECT_DISCO_TIMEOUT, account.getUuid().hashCode());
1021 Element caps = streamFeatures.findChild("c");
1022 final String hash = caps == null ? null : caps.getAttribute("hash");
1023 final String ver = caps == null ? null : caps.getAttribute("ver");
1024 ServiceDiscoveryResult discoveryResult = null;
1025 if (hash != null && ver != null) {
1026 discoveryResult = mXmppConnectionService.databaseBackend.findDiscoveryResult(hash, ver);
1027 }
1028 if (discoveryResult == null) {
1029 sendServiceDiscoveryInfo(account.getServer());
1030 } else {
1031 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": server caps came from cache");
1032 disco.put(account.getServer(), discoveryResult);
1033 }
1034 sendServiceDiscoveryInfo(account.getJid().toBareJid());
1035 sendServiceDiscoveryItems(account.getServer());
1036 if (!mWaitForDisco) {
1037 finalizeBind();
1038 }
1039 this.lastSessionStarted = SystemClock.elapsedRealtime();
1040 }
1041
1042 private void sendServiceDiscoveryInfo(final Jid jid) {
1043 mPendingServiceDiscoveries.incrementAndGet();
1044 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1045 iq.setTo(jid);
1046 iq.query("http://jabber.org/protocol/disco#info");
1047 String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1048
1049 @Override
1050 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1051 if (packet.getType() == IqPacket.TYPE.RESULT) {
1052 boolean advancedStreamFeaturesLoaded;
1053 synchronized (XmppConnection.this.disco) {
1054 ServiceDiscoveryResult result = new ServiceDiscoveryResult(packet);
1055 for (final ServiceDiscoveryResult.Identity id : result.getIdentities()) {
1056 if (mServerIdentity == Identity.UNKNOWN && id.getType().equals("im") &&
1057 id.getCategory().equals("server") && id.getName() != null &&
1058 jid.equals(account.getServer())) {
1059 switch (id.getName()) {
1060 case "Prosody":
1061 mServerIdentity = Identity.PROSODY;
1062 break;
1063 case "ejabberd":
1064 mServerIdentity = Identity.EJABBERD;
1065 break;
1066 case "Slack-XMPP":
1067 mServerIdentity = Identity.SLACK;
1068 break;
1069 }
1070 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": server name: " + id.getName());
1071 }
1072 }
1073 if (jid.equals(account.getServer())) {
1074 mXmppConnectionService.databaseBackend.insertDiscoveryResult(result);
1075 }
1076 disco.put(jid, result);
1077 advancedStreamFeaturesLoaded = disco.containsKey(account.getServer())
1078 && disco.containsKey(account.getJid().toBareJid());
1079 }
1080 if (advancedStreamFeaturesLoaded && (jid.equals(account.getServer()) || jid.equals(account.getJid().toBareJid()))) {
1081 enableAdvancedStreamFeatures();
1082 }
1083 } else {
1084 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco info for " + jid.toString());
1085 }
1086 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1087 if (mPendingServiceDiscoveries.decrementAndGet() == 0
1088 && !mIsServiceItemsDiscoveryPending.get()
1089 && mWaitForDisco) {
1090 finalizeBind();
1091 }
1092 }
1093 }
1094 });
1095 synchronized (this.mPendingServiceDiscoveriesIds) {
1096 this.mPendingServiceDiscoveriesIds.add(id);
1097 }
1098 }
1099
1100 private void finalizeBind() {
1101 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": online with resource " + account.getResource());
1102 if (bindListener != null) {
1103 bindListener.onBind(account);
1104 }
1105 changeStatus(Account.State.ONLINE);
1106 }
1107
1108 private void enableAdvancedStreamFeatures() {
1109 if (getFeatures().carbons() && !features.carbonsEnabled) {
1110 sendEnableCarbons();
1111 }
1112 if (getFeatures().blocking() && !features.blockListRequested) {
1113 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": Requesting block list");
1114 this.sendIqPacket(getIqGenerator().generateGetBlockList(), mXmppConnectionService.getIqParser());
1115 }
1116 for (final OnAdvancedStreamFeaturesLoaded listener : advancedStreamFeaturesLoadedListeners) {
1117 listener.onAdvancedStreamFeaturesAvailable(account);
1118 }
1119 }
1120
1121 private void sendServiceDiscoveryItems(final Jid server) {
1122 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1123 iq.setTo(server.toDomainJid());
1124 iq.query("http://jabber.org/protocol/disco#items");
1125 String id = this.sendIqPacket(iq, new OnIqPacketReceived() {
1126
1127 @Override
1128 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1129 if (packet.getType() == IqPacket.TYPE.RESULT) {
1130 final List<Element> elements = packet.query().getChildren();
1131 for (final Element element : elements) {
1132 if (element.getName().equals("item")) {
1133 final Jid jid = element.getAttributeAsJid("jid");
1134 if (jid != null && !jid.equals(account.getServer())) {
1135 sendServiceDiscoveryInfo(jid);
1136 }
1137 }
1138 }
1139 } else {
1140 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not query disco items of " + server);
1141 }
1142 if (packet.getType() != IqPacket.TYPE.TIMEOUT) {
1143 mIsServiceItemsDiscoveryPending.set(false);
1144 if (mPendingServiceDiscoveries.get() == 0 && mWaitForDisco) {
1145 finalizeBind();
1146 }
1147 }
1148 }
1149 });
1150 synchronized (this.mPendingServiceDiscoveriesIds) {
1151 this.mPendingServiceDiscoveriesIds.add(id);
1152 }
1153 }
1154
1155 private void sendEnableCarbons() {
1156 final IqPacket iq = new IqPacket(IqPacket.TYPE.SET);
1157 iq.addChild("enable", "urn:xmpp:carbons:2");
1158 this.sendIqPacket(iq, new OnIqPacketReceived() {
1159
1160 @Override
1161 public void onIqPacketReceived(final Account account, final IqPacket packet) {
1162 if (!packet.hasChild("error")) {
1163 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1164 + ": successfully enabled carbons");
1165 features.carbonsEnabled = true;
1166 } else {
1167 Log.d(Config.LOGTAG, account.getJid().toBareJid()
1168 + ": error enableing carbons " + packet.toString());
1169 }
1170 }
1171 });
1172 }
1173
1174 private void processStreamError(final Tag currentTag)
1175 throws XmlPullParserException, IOException {
1176 final Element streamError = tagReader.readElement(currentTag);
1177 if (streamError == null) {
1178 return;
1179 }
1180 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": stream error "+streamError.toString());
1181 if (streamError.hasChild("conflict")) {
1182 final String resource = account.getResource().split("\\.")[0];
1183 account.setResource(resource + "." + nextRandomId());
1184 Log.d(Config.LOGTAG,
1185 account.getJid().toBareJid() + ": switching resource due to conflict ("
1186 + account.getResource() + ")");
1187 } else if (streamError.hasChild("host-unknown")) {
1188 changeStatus(Account.State.HOST_UNKNOWN);
1189 }
1190 forceCloseSocket();
1191 }
1192
1193 private void sendStartStream() throws IOException {
1194 final Tag stream = Tag.start("stream:stream");
1195 stream.setAttribute("to", account.getServer().toString());
1196 stream.setAttribute("version", "1.0");
1197 stream.setAttribute("xml:lang", "en");
1198 stream.setAttribute("xmlns", "jabber:client");
1199 stream.setAttribute("xmlns:stream", "http://etherx.jabber.org/streams");
1200 tagWriter.writeTag(stream);
1201 }
1202
1203 private String nextRandomId() {
1204 return new BigInteger(50, mXmppConnectionService.getRNG()).toString(32);
1205 }
1206
1207 public String sendIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1208 packet.setFrom(account.getJid());
1209 return this.sendUnmodifiedIqPacket(packet, callback);
1210 }
1211
1212 private synchronized String sendUnmodifiedIqPacket(final IqPacket packet, final OnIqPacketReceived callback) {
1213 if (packet.getId() == null) {
1214 final String id = nextRandomId();
1215 packet.setAttribute("id", id);
1216 }
1217 if (callback != null) {
1218 synchronized (this.packetCallbacks) {
1219 packetCallbacks.put(packet.getId(), new Pair<>(packet, callback));
1220 }
1221 }
1222 this.sendPacket(packet);
1223 return packet.getId();
1224 }
1225
1226 public void sendMessagePacket(final MessagePacket packet) {
1227 this.sendPacket(packet);
1228 }
1229
1230 public void sendPresencePacket(final PresencePacket packet) {
1231 this.sendPacket(packet);
1232 }
1233
1234 private synchronized void sendPacket(final AbstractStanza packet) {
1235 if (stanzasSent == Integer.MAX_VALUE) {
1236 resetStreamId();
1237 disconnect(true);
1238 return;
1239 }
1240 tagWriter.writeStanzaAsync(packet);
1241 if (packet instanceof AbstractAcknowledgeableStanza) {
1242 AbstractAcknowledgeableStanza stanza = (AbstractAcknowledgeableStanza) packet;
1243 ++stanzasSent;
1244 this.mStanzaQueue.put(stanzasSent, stanza);
1245 if (stanza instanceof MessagePacket && stanza.getId() != null && getFeatures().sm()) {
1246 if (Config.EXTENDED_SM_LOGGING) {
1247 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": requesting ack for message stanza #" + stanzasSent);
1248 }
1249 tagWriter.writeStanzaAsync(new RequestPacket(this.smVersion));
1250 }
1251 }
1252 }
1253
1254 public void sendPing() {
1255 if (!r()) {
1256 final IqPacket iq = new IqPacket(IqPacket.TYPE.GET);
1257 iq.setFrom(account.getJid());
1258 iq.addChild("ping", "urn:xmpp:ping");
1259 this.sendIqPacket(iq, null);
1260 }
1261 this.lastPingSent = SystemClock.elapsedRealtime();
1262 }
1263
1264 public void setOnMessagePacketReceivedListener(
1265 final OnMessagePacketReceived listener) {
1266 this.messageListener = listener;
1267 }
1268
1269 public void setOnUnregisteredIqPacketReceivedListener(
1270 final OnIqPacketReceived listener) {
1271 this.unregisteredIqListener = listener;
1272 }
1273
1274 public void setOnPresencePacketReceivedListener(
1275 final OnPresencePacketReceived listener) {
1276 this.presenceListener = listener;
1277 }
1278
1279 public void setOnJinglePacketReceivedListener(
1280 final OnJinglePacketReceived listener) {
1281 this.jingleListener = listener;
1282 }
1283
1284 public void setOnStatusChangedListener(final OnStatusChanged listener) {
1285 this.statusListener = listener;
1286 }
1287
1288 public void setOnBindListener(final OnBindListener listener) {
1289 this.bindListener = listener;
1290 }
1291
1292 public void setOnMessageAcknowledgeListener(final OnMessageAcknowledged listener) {
1293 this.acknowledgedListener = listener;
1294 }
1295
1296 public void addOnAdvancedStreamFeaturesAvailableListener(final OnAdvancedStreamFeaturesLoaded listener) {
1297 if (!this.advancedStreamFeaturesLoadedListeners.contains(listener)) {
1298 this.advancedStreamFeaturesLoadedListeners.add(listener);
1299 }
1300 }
1301
1302 public void waitForPush() {
1303 if (tagWriter.isActive()) {
1304 tagWriter.finish();
1305 new Thread(new Runnable() {
1306 @Override
1307 public void run() {
1308 try {
1309 while(!tagWriter.finished()) {
1310 Thread.sleep(10);
1311 }
1312 socket.close();
1313 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closed tcp without closing stream");
1314 } catch (IOException e) {
1315 e.printStackTrace();
1316 } catch (InterruptedException e) {
1317 e.printStackTrace();
1318 }
1319 }
1320 }).start();
1321 } else {
1322 forceCloseSocket();
1323 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": closed tcp without closing stream (no waiting)");
1324 }
1325 }
1326
1327 private void forceCloseSocket() {
1328 if (socket != null) {
1329 try {
1330 socket.close();
1331 } catch (IOException e) {
1332 e.printStackTrace();
1333 }
1334 }
1335 }
1336
1337 public void disconnect(final boolean force) {
1338 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": disconnecting force="+Boolean.valueOf(force));
1339 if (force) {
1340 forceCloseSocket();
1341 return;
1342 } else {
1343 if (tagWriter.isActive()) {
1344 tagWriter.finish();
1345 try {
1346 int i = 0;
1347 boolean warned = false;
1348 while (!tagWriter.finished() && socket.isConnected() && i <= 10) {
1349 if (!warned) {
1350 Log.d(Config.LOGTAG, account.getJid().toBareJid()+": waiting for tag writer to finish");
1351 warned = true;
1352 }
1353 Thread.sleep(200);
1354 i++;
1355 }
1356 if (warned) {
1357 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": tag writer has finished");
1358 }
1359 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": closing stream");
1360 tagWriter.writeTag(Tag.end("stream:stream"));
1361 } catch (final IOException e) {
1362 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": io exception during disconnect ("+e.getMessage()+")");
1363 } catch (final InterruptedException e) {
1364 Log.d(Config.LOGTAG, "interrupted");
1365 }
1366 }
1367 }
1368 }
1369
1370 public void resetStreamId() {
1371 this.streamId = null;
1372 }
1373
1374 private List<Entry<Jid, ServiceDiscoveryResult>> findDiscoItemsByFeature(final String feature) {
1375 synchronized (this.disco) {
1376 final List<Entry<Jid, ServiceDiscoveryResult>> items = new ArrayList<>();
1377 for (final Entry<Jid, ServiceDiscoveryResult> cursor : this.disco.entrySet()) {
1378 if (cursor.getValue().getFeatures().contains(feature)) {
1379 items.add(cursor);
1380 }
1381 }
1382 return items;
1383 }
1384 }
1385
1386 public Jid findDiscoItemByFeature(final String feature) {
1387 final List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(feature);
1388 if (items.size() >= 1) {
1389 return items.get(0).getKey();
1390 }
1391 return null;
1392 }
1393
1394 public boolean r() {
1395 if (getFeatures().sm()) {
1396 this.tagWriter.writeStanzaAsync(new RequestPacket(smVersion));
1397 return true;
1398 } else {
1399 return false;
1400 }
1401 }
1402
1403 public String getMucServer() {
1404 synchronized (this.disco) {
1405 for (final Entry<Jid, ServiceDiscoveryResult> cursor : disco.entrySet()) {
1406 final ServiceDiscoveryResult value = cursor.getValue();
1407 if (value.getFeatures().contains("http://jabber.org/protocol/muc")
1408 && !value.getFeatures().contains("jabber:iq:gateway")
1409 && !value.hasIdentity("conference", "irc")) {
1410 return cursor.getKey().toString();
1411 }
1412 }
1413 }
1414 return null;
1415 }
1416
1417 public int getTimeToNextAttempt() {
1418 final int interval = (int) (25 * Math.pow(1.5, attempt));
1419 final int secondsSinceLast = (int) ((SystemClock.elapsedRealtime() - this.lastConnect) / 1000);
1420 return interval - secondsSinceLast;
1421 }
1422
1423 public int getAttempt() {
1424 return this.attempt;
1425 }
1426
1427 public Features getFeatures() {
1428 return this.features;
1429 }
1430
1431 public long getLastSessionEstablished() {
1432 final long diff = SystemClock.elapsedRealtime() - this.lastSessionStarted;
1433 return System.currentTimeMillis() - diff;
1434 }
1435
1436 public long getLastConnect() {
1437 return this.lastConnect;
1438 }
1439
1440 public long getLastPingSent() {
1441 return this.lastPingSent;
1442 }
1443
1444 public long getLastDiscoStarted() {
1445 return this.lastDiscoStarted;
1446 }
1447 public long getLastPacketReceived() {
1448 return this.lastPacketReceived;
1449 }
1450
1451 public void sendActive() {
1452 this.sendPacket(new ActivePacket());
1453 }
1454
1455 public void sendInactive() {
1456 this.sendPacket(new InactivePacket());
1457 }
1458
1459 public void resetAttemptCount() {
1460 this.attempt = 0;
1461 this.lastConnect = 0;
1462 }
1463
1464 public void setInteractive(boolean interactive) {
1465 this.mInteractive = interactive;
1466 }
1467
1468 public Identity getServerIdentity() {
1469 return mServerIdentity;
1470 }
1471
1472 private class UnauthorizedException extends IOException {
1473
1474 }
1475
1476 private class SecurityException extends IOException {
1477
1478 }
1479
1480 private class IncompatibleServerException extends IOException {
1481
1482 }
1483
1484 public enum Identity {
1485 FACEBOOK,
1486 SLACK,
1487 EJABBERD,
1488 PROSODY,
1489 NIMBUZZ,
1490 UNKNOWN
1491 }
1492
1493 public class Features {
1494 XmppConnection connection;
1495 private boolean carbonsEnabled = false;
1496 private boolean encryptionEnabled = false;
1497 private boolean blockListRequested = false;
1498
1499 public Features(final XmppConnection connection) {
1500 this.connection = connection;
1501 }
1502
1503 private boolean hasDiscoFeature(final Jid server, final String feature) {
1504 synchronized (XmppConnection.this.disco) {
1505 return connection.disco.containsKey(server) &&
1506 connection.disco.get(server).getFeatures().contains(feature);
1507 }
1508 }
1509
1510 public boolean carbons() {
1511 return hasDiscoFeature(account.getServer(), "urn:xmpp:carbons:2");
1512 }
1513
1514 public boolean blocking() {
1515 return hasDiscoFeature(account.getServer(), Xmlns.BLOCKING);
1516 }
1517
1518 public boolean register() {
1519 return hasDiscoFeature(account.getServer(), Xmlns.REGISTER);
1520 }
1521
1522 public boolean sm() {
1523 return streamId != null
1524 || (connection.streamFeatures != null && connection.streamFeatures.hasChild("sm"));
1525 }
1526
1527 public boolean csi() {
1528 return connection.streamFeatures != null && connection.streamFeatures.hasChild("csi", "urn:xmpp:csi:0");
1529 }
1530
1531 public boolean pep() {
1532 synchronized (XmppConnection.this.disco) {
1533 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1534 return info != null && info.hasIdentity("pubsub", "pep");
1535 }
1536 }
1537
1538 public boolean pepPersistent() {
1539 synchronized (XmppConnection.this.disco) {
1540 ServiceDiscoveryResult info = disco.get(account.getJid().toBareJid());
1541 return info != null && info.getFeatures().contains("http://jabber.org/protocol/pubsub#persistent-items");
1542 }
1543 }
1544
1545 public boolean mam() {
1546 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:mam:0")
1547 || hasDiscoFeature(account.getServer(), "urn:xmpp:mam:0");
1548 }
1549
1550 public boolean push() {
1551 return hasDiscoFeature(account.getJid().toBareJid(), "urn:xmpp:push:0")
1552 || hasDiscoFeature(account.getServer(), "urn:xmpp:push:0");
1553 }
1554
1555 public boolean rosterVersioning() {
1556 return connection.streamFeatures != null && connection.streamFeatures.hasChild("ver");
1557 }
1558
1559 public void setBlockListRequested(boolean value) {
1560 this.blockListRequested = value;
1561 }
1562
1563 public boolean httpUpload(long filesize) {
1564 if (Config.DISABLE_HTTP_UPLOAD) {
1565 return false;
1566 } else {
1567 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1568 if (items.size() > 0) {
1569 try {
1570 long maxsize = Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1571 if(filesize <= maxsize) {
1572 return true;
1573 } else {
1574 Log.d(Config.LOGTAG,account.getJid().toBareJid()+": http upload is not available for files with size "+filesize+" (max is "+maxsize+")");
1575 return false;
1576 }
1577 } catch (Exception e) {
1578 return true;
1579 }
1580 } else {
1581 return false;
1582 }
1583 }
1584 }
1585
1586 public long getMaxHttpUploadSize() {
1587 List<Entry<Jid, ServiceDiscoveryResult>> items = findDiscoItemsByFeature(Xmlns.HTTP_UPLOAD);
1588 if (items.size() > 0) {
1589 try {
1590 return Long.parseLong(items.get(0).getValue().getExtendedDiscoInformation(Xmlns.HTTP_UPLOAD, "max-file-size"));
1591 } catch (Exception e) {
1592 return -1;
1593 }
1594 } else {
1595 return -1;
1596 }
1597 }
1598 }
1599
1600 private IqGenerator getIqGenerator() {
1601 return mXmppConnectionService.getIqGenerator();
1602 }
1603}