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