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