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