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