/
MucClient.java
903 lines (805 loc) · 28.9 KB
/
MucClient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
/*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.xmpp.mucclient;
import org.jitsi.utils.collections.*;
import org.jitsi.utils.concurrent.*;
import org.jitsi.utils.logging2.*;
import org.jitsi.retry.*;
import org.jitsi.xmpp.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.iqrequest.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.tcp.*;
import org.jivesoftware.smackx.disco.*;
import org.jivesoftware.smackx.muc.*;
import org.jivesoftware.smackx.muc.packet.*;
import org.jivesoftware.smackx.ping.*;
import org.jivesoftware.smackx.xdata.form.*;
import org.jxmpp.jid.*;
import org.jxmpp.jid.impl.*;
import org.jxmpp.jid.parts.*;
import org.jitsi.xmpp.*;
import org.jxmpp.stringprep.*;
import java.util.*;
import java.util.concurrent.*;
/**
* The {@link MucClient} is responsible for handling a single XMPP connection
* on which a single MUC is joined.
*
* @author bbaldino
* @author Boris Grozev
*/
public class MucClient
{
private static final int DEFAULT_PING_INTERVAL_SECONDS = 30;
static
{
XMPPTCPConnection.setUseStreamManagementDefault(false);
XMPPTCPConnection.setUseStreamManagementResumptionDefault(false);
PingManager.setDefaultPingInterval(DEFAULT_PING_INTERVAL_SECONDS);
}
/**
* The {@link Logger} used by the {@link MucClient} class and its instances
* for logging output.
*/
private static final Logger classLogger = new LoggerImpl(MucClient.class.getName());
/**
* The IQ types we are interested in.
*/
private static final IQ.Type[] IQ_TYPES = new IQ.Type[]{ IQ.Type.get, IQ.Type.set};
/**
* Creates a Smack {@link XMPPTCPConnectionConfiguration} based on
* a {@link MucClientConfiguration}.
* @param config the {@link MucClientConfiguration} which describes
* the connection.
* @return the {@link XMPPTCPConnectionConfiguration}.
*/
private static XMPPTCPConnectionConfiguration
createXMPPTCPConnectionConfiguration(
MucClientConfiguration config)
{
String domain = config.getDomain();
if (domain == null)
{
domain = config.getHostname();
}
DomainBareJid domainJid;
try
{
domainJid = JidCreate.domainBareFrom(domain);
}
catch (XmppStringprepException xse)
{
classLogger.error("Failed to parse domain: " + domain);
return null;
}
XMPPTCPConnectionConfiguration.Builder builder
= XMPPTCPConnectionConfiguration.builder()
.setHost(config.getHostname())
.setXmppDomain(domainJid)
.setUsernameAndPassword(config.getUsername(), config.getPassword());
String portStr = config.getPort();
if (portStr != null && !portStr.isEmpty())
{
builder.setPort(Integer.parseInt(portStr));
}
if (config.getDisableCertificateVerification())
{
classLogger.warn("Disabling certificate verification!");
builder.setCustomX509TrustManager(new TrustAllX509TrustManager());
builder.setHostnameVerifier(new TrustAllHostnameVerifier());
}
ConnectionConfiguration.SecurityMode securityMode = config.getSecurityMode();
if (securityMode == null)
{
String hostname = config.getHostname();
/* We want to allow security to be disabled on loopback. */
if (hostname.equals("localhost") || hostname.equals("127.0.0.1") || hostname.equals("::1"))
{
securityMode = ConnectionConfiguration.SecurityMode.ifpossible;
}
else
{
securityMode = ConnectionConfiguration.SecurityMode.required;
}
}
if (securityMode == ConnectionConfiguration.SecurityMode.disabled)
{
classLogger.warn("XMPP security is disabled!");
}
builder.setSecurityMode(securityMode);
// Uses SASL Mechanisms ANONYMOUS and PLAIN to authenticate, but tries to authenticate with GSSAPI when
// it's offered by the server which does not work with the server components using jicoco.
// Disable GSSAPI.
SASLAuthentication.unregisterSASLMechanism("org.jivesoftware.smack.sasl.javax.SASLGSSAPIMechanism");
return builder.build();
}
/**
* The {@link AbstractXMPPConnection} object for the connection to
* the xmpp server
*/
private AbstractXMPPConnection xmppConnection;
/**
* The connect loop: we keep this running forever and it re-establishes the
* connection in case it's broken.
*/
private RetryStrategy connectRetry;
/**
* The executor to execute connect, retry connection and login.
*/
private ScheduledExecutorService executor;
/**
* The {@link MucClientManager} which owns this {@link MucClient}.
*/
private final MucClientManager mucClientManager;
/**
* The listener, if any, to call when we receive an IQ from Smack.
*/
private IQListener iqListener;
/**
* The nickname of this client in the MUC.
*/
private Resourcepart mucNickname;
/**
* The mode to use with Smack {@link IQRequestHandler}s.
*/
private IQRequestHandler.Mode iqHandlerMode = IQRequestHandler.Mode.async;
/**
* This {@link MucClient}'s configuration.
*/
private final MucClientConfiguration config;
/**
* Contains the smack {@link MultiUserChat} objects that this
* {@link MucClient} maintains (mapped by their MUC JIDs).
*/
private final Map<Jid, MucWrapper> mucs = new ConcurrentHashMap<>();
/**
* The {@link Logger} used by the {@link MucClient} class and its instances
* for logging output.
*/
private final Logger logger;
/**
* The ping fail listener.
*/
private final PingFailedListener pingFailedListener = new PingFailedListenerImpl();
/**
* The reconnection listener.
*/
private final ReconnectionListener reconnectionListener = new ReconnectionListener()
{
@Override
public void reconnectingIn(int i)
{
logger.info("Reconnecting in " + i);
}
@Override
public void reconnectionFailed(Exception e)
{
logger.warn("Reconnection failed: ", e);
}
};
/**
* Creates and XMPP connection for the given {@code config}, connects, and
* joins the MUC described by the {@code config}.
*
* @param config xmpp connection details
*/
MucClient(MucClientConfiguration config, MucClientManager mucClientManager)
{
this.mucClientManager = mucClientManager;
logger = classLogger.createChildLogger(
MucClient.class.getName(),
JMap.of(
"id", config.getId(),
"hostname", config.getHostname()));
this.config = config;
}
/**
* Initializes the executor and starts initializing, connecting and logging
* in of this muc client.
*/
void start()
{
this.executor = ExecutorUtils.newScheduledThreadPool(1, true, MucClientManager.class.getSimpleName());
this.connectRetry = new RetryStrategy(this.executor);
this.executor.execute(() ->
{
try
{
this.initializeConnectAndJoin();
}
catch(Exception e)
{
logger.error("Failed to initialize and start a MucClient: ", e);
}
});
}
/**
* Initializes this instance (by extracting the necessary fields from its
* configuration), connects and logs into the XMPP server, and joins all
* MUCs that the configuration describes.
*/
private void initializeConnectAndJoin()
throws Exception
{
logger.info("Initializing a new MucClient for " + config);
if (!config.isComplete())
{
throw new IllegalArgumentException("incomplete configuration");
}
mucNickname = Resourcepart.from(config.getMucNickname());
if ("sync".equalsIgnoreCase(config.getIqHandlerMode()))
{
iqHandlerMode = IQRequestHandler.Mode.sync;
}
xmppConnection = new XMPPTCPConnection(createXMPPTCPConnectionConfiguration(config));
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(xmppConnection);
PingManager pingManager = PingManager.getInstanceFor(xmppConnection);
if (pingManager != null)
{
pingManager.registerPingFailedListener(pingFailedListener);
}
// Register the disco#info features.
mucClientManager.getFeatures().forEach(sdm::addFeature);
ReconnectionManager reconnectionManager = ReconnectionManager.getInstanceFor(xmppConnection);
reconnectionManager.disableAutomaticReconnection();
xmppConnection.addConnectionListener(new ConnectionListener()
{
@Override
public void connected(XMPPConnection xmppConnection)
{
logger.info("Connected.");
}
@Override
public void authenticated(XMPPConnection xmppConnection, boolean b)
{
logger.info("Authenticated, b=" + b);
}
@Override
public void connectionClosed()
{
logger.info("Closed.");
}
@Override
public void connectionClosedOnError(Exception e)
{
logger.warn("Closed on error:", e);
}
});
ReconnectionManager.getInstanceFor(xmppConnection).addReconnectionListener(reconnectionListener);
mucClientManager.getRegisteredIqs().forEach(this::registerIQ);
setIQListener(mucClientManager.getIqListener());
logger.info("Dispatching a thread to connect and login.");
this.connectRetry.runRetryingTask(new SimpleRetryTask(0, 5000, true, getConnectAndLoginCallable()));
}
/**
* Create and/or join the MUCs described in the configuration.
*/
private void joinMucs()
throws SmackException.NotConnectedException,
SmackException.NoResponseException,
InterruptedException,
XMPPException.XMPPErrorException,
MultiUserChatException.MucAlreadyJoinedException,
MultiUserChatException.NotAMucServiceException,
XmppStringprepException
{
for (String mucJidStr : config.getMucJids())
{
EntityBareJid mucJid = JidCreate.entityBareFrom(mucJidStr);
MucWrapper mucWrapper = getOrCreateMucState(mucJid);
mucWrapper.join(mucJid);
}
}
/**
* Whether the XMPP connection is currently connected (and authenticated).
*/
boolean isConnected()
{
return xmppConnection != null && xmppConnection.isConnected() && xmppConnection.isAuthenticated();
}
/**
* The number of MUCs configured for this {@link MucClient}.
*/
int getMucsCount()
{
return config.getMucJids().size();
}
/**
* The number of MUCs that have been joined.
*/
int getMucsJoinedCount()
{
if (!isConnected())
{
return 0;
}
return (int) mucs.values().stream()
.filter(mucWrapper -> mucWrapper.muc.isJoined())
.count();
}
/**
* Gets the {@link MucWrapper} instance for a particular JID, creating it
* if necessary.
* @param mucJid the MUC JID.
* @return the {@link MucWrapper} instance.
*/
private MucWrapper getOrCreateMucState(Jid mucJid)
{
return mucs.computeIfAbsent(mucJid, (k) -> new MucWrapper());
}
/**
* Send an xmpp stanza on the xmpp connection
* @param stanza the stanza to send
* @return true if it is sent successfully, false otherwise
*/
public boolean sendStanza(Stanza stanza)
{
try
{
xmppConnection.sendStanza(stanza);
return true;
}
catch (Exception e)
{
logger.warn("Failed to send stanza: " + e);
return false;
}
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
return "[MucClient id=" + config.getId()
+ " hostname=" + config.getHostname() + "]";
}
/**
* Adds an extension to our presence in the MUC. If our presence already
* contains an extension with the same namespace and element name, the old
* one is removed.
* @param extension the extension to add.
*/
public void setPresenceExtension(ExtensionElement extension)
{
setPresenceExtensions(Collections.singletonList(extension));
}
/**
* Adds a set of extension to our presence in the MUC. If our presence
* already contains extensions that match the namespace or element of any
* of the extensions to be added, the old ones are removed.
* @param extensions the extensions to add.
*/
public void setPresenceExtensions(Collection<ExtensionElement> extensions)
{
if (!isConnected())
{
logger.warn("Cannot set presence extension: not connected.");
return;
}
mucs.values().forEach(ms -> ms.setPresenceExtensions(extensions));
}
/**
* Removes from our presence any extensions with the given
* {@code elementName} and {@code namespace}.
* @param elementName the element name to match.
* @param namespace the namespace to match.
*/
public void removePresenceExtension(String elementName, String namespace)
{
mucs.values().forEach(ms->ms.removePresenceExtension(elementName, namespace));
}
/**
* Sets the listener for IQs.
* @param iqListener the listener to set.
*/
void setIQListener(IQListener iqListener)
{
this.iqListener = iqListener;
}
/**
* Indicates to this instance that the {@link #iqListener} is interested
* in IQs of a specific type, represented as an {@link IQ} instance.
* @param iq the IQ which represents the IQ type (i.e. an element name and a namespace).
* @param requireResponse whether to send an error stanza as a response if the {@link IQListener} produces
* {@code null} for requests of this type.
*/
void registerIQ(IQ iq, boolean requireResponse)
{
for (IQ.Type type : IQ_TYPES)
{
xmppConnection.registerIQRequestHandler(
new AbstractIqRequestHandler(iq.getChildElementName(),
iq.getChildElementNamespace(),
type,
iqHandlerMode)
{
@Override
public IQ handleIQRequest(IQ iqRequest)
{
logger.debug(() -> "Received an IQ with type " + type + ": " + iqRequest.toString());
return handleIq(iqRequest, requireResponse);
}
}
);
}
}
/**
* Handles an IQ received from Smack by passing it to the listener which is
* registered.
* @param iq the IQ to handle.
* @param requireResponse whether to send an error stanza as a response if the {@link IQListener} produces
* {@code null}.
* @return the response.
*/
private IQ handleIq(IQ iq, boolean requireResponse)
{
IQ responseIq = null;
EntityBareJid fromJid = iq.getFrom().asEntityBareJidIfPossible();
String fromJidStr = fromJid.toString().toLowerCase();
if (this.config.getMucJids().stream()
.noneMatch(mucJid -> mucJid.toLowerCase().equals(fromJidStr)))
{
logger.warn("Received an IQ from a non-MUC member: " + fromJid);
return IQUtils.createError(iq, StanzaError.Condition.forbidden);
}
IQListener iqListener = this.iqListener;
if (iqListener == null)
{
logger.error("Received an IQ, but the listener is null.");
}
else
{
try
{
responseIq = iqListener.handleIq(iq, this);
}
catch (Exception e)
{
logger.warn("Exception processing IQ, returning internal server error. Request: " + iq, e);
responseIq = IQUtils.createError(iq, StanzaError.Condition.internal_server_error, e.getMessage());
}
}
if (requireResponse && responseIq == null)
{
logger.info(
"Failed to produce a response for IQ, returning internal server error. Request: " + iq);
responseIq = IQUtils.createError(iq, StanzaError.Condition.internal_server_error, "Unknown error");
}
return responseIq;
}
/**
* @return the ID of this {@link MucClient}.
*/
public String getId()
{
return config.getId();
}
/**
* Leaves all MUCs and disconnects from the XMPP server.
*/
void stop()
{
this.connectRetry.cancel();
ReconnectionManager.getInstanceFor(xmppConnection).removeReconnectionListener(reconnectionListener);
if (this.executor != null)
{
this.executor.shutdown();
this.executor = null;
}
// If we are still not connected leave and disconnect my through
// errors
try
{
mucs.values().forEach(MucWrapper::leave);
}
catch(Exception e)
{
logger.error("Error leaving mucs", e);
}
PingManager pingManager = PingManager.getInstanceFor(xmppConnection);
if (pingManager != null)
{
pingManager.unregisterPingFailedListener(pingFailedListener);
}
try
{
xmppConnection.disconnect();
}
catch(Exception e)
{
logger.error("Error disconnecting xmpp connection", e);
}
}
/**
* The callable returned by this method describes the task of connecting
* and login to XMPP service.
*
* @return <tt>Callable<Boolean></tt> which returns <tt>true</tt> as long
* as we're failing to connect.
*/
private Callable<Boolean> getConnectAndLoginCallable()
{
return () ->
{
try
{
if (!xmppConnection.isConnected())
{
xmppConnection.connect();
}
}
catch(Exception t)
{
logger.warn(MucClient.this + " error connecting", t);
return true;
}
if (!xmppConnection.isAuthenticated())
{
logger.info("Logging in.");
try
{
xmppConnection.login();
}
catch (SmackException.AlreadyLoggedInException e)
{
logger.info("Already logged in.");
}
catch (Exception e)
{
// We've observed the XMPPTCPConnection get in a broken state where it is connected, but unable to
// login (because the locally cached SASL mechanisms supported by the server are empty). We
// disconnect in order to trigger a re-connect and clear that state on the next attempt.
logger.warn("Failed to login. Disconnecting to trigger a re-connect.");
xmppConnection.disconnect();
return true;
}
try
{
joinMucs();
}
catch(Exception e)
{
logger.warn("Failed to join the MUCs.", e);
return true;
}
}
return true;
};
}
/**
* Wraps a {@link MultiUserChat} with logic for adding extensions to our
* own presence.
*/
private class MucWrapper
{
/**
* The {@link MultiUserChat} object for the MUC we'll be joining.
*/
private MultiUserChat muc;
/**
* Stores our last MUC presence packet for future update.
*/
private PresenceBuilder lastPresenceSent;
/**
* Intercepts presence packets sent by smack and saves the last one.
*/
private final PresenceListener presenceInterceptor = presence ->
{
// The initial presence sent by smack contains an empty "x"
// extension. If this extension is included in a subsequent stanza,
// it indicates that the client lost its synchronization and causes
// the MUC service to re-send the presence of each occupant in the
// room.
PresenceBuilder nextLastPresence = presence.asBuilder((String) null)
.removeExtension(MUCInitialPresence.ELEMENT, MUCInitialPresence.NAMESPACE);
synchronized (this)
{
lastPresenceSent = nextLastPresence;
}
};
/**
* Leaves the MUC.
*/
private void leave()
{
try
{
muc.leave();
}
catch (Exception e)
{
logger.warn("Error while trying to leave a MUC: ", e);
}
muc = null;
}
/**
* Joins the MUC.
* @param mucJid the JID of the MUC to join.
*/
private void join(EntityBareJid mucJid)
throws SmackException.NotConnectedException,
SmackException.NoResponseException,
InterruptedException,
XMPPException.XMPPErrorException,
MultiUserChatException.MucAlreadyJoinedException,
MultiUserChatException.NotAMucServiceException
{
// We're about to join or re-join the MUC.
resetLastPresenceSent();
if (muc != null)
{
muc.removePresenceInterceptor(presenceInterceptor);
logger.info("Leaving a MUC we already occupy.");
leave();
}
MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(xmppConnection);
muc = mucManager.getMultiUserChat(mucJid);
muc.addPresenceInterceptor(presenceInterceptor);
MultiUserChat.MucCreateConfigFormHandle mucCreateHandle = muc.createOrJoin(mucNickname);
if (mucCreateHandle != null)
{
// the room was just created. Let's send a config
// making the room non-anonymous, so that others can
// recognize our JID
Form config = muc.getConfigurationForm();
FillableForm answer = config.getFillableForm();
// Room non-anonymous
String whoisFieldName = "muc#roomconfig_whois";
answer.setAnswer(whoisFieldName, "anyone");
muc.sendConfigurationForm(answer);
}
logger.info("Joined MUC: " + mucJid);
setPresenceExtensions(mucClientManager.getPresenceExtensions());
}
/**
* Adds a set of extensions to our presence in this MUC.
* @param extensions the extensions to add.
*/
void setPresenceExtensions(Collection<ExtensionElement> extensions)
{
Presence updatedPresence;
synchronized (this)
{
if (lastPresenceSent == null)
{
logger.warn("Cannot set presence extensions: no previous presence available.");
return;
}
// Remove the old extensions if present and override
extensions.forEach(lastPresenceSent::overrideExtension);
updatedPresence = lastPresenceSent.build();
}
try
{
xmppConnection.sendStanza(updatedPresence);
}
catch (Exception e)
{
logger.error("Failed to send stanza:", e);
}
}
/**
* Removes from our presence in the MUC any extensions with the given
* {@code elementName} and {@code namespace}.
* @param elementName the element name to match.
* @param namespace the namespace to match.
*/
private void removePresenceExtension(String elementName, String namespace)
{
Presence updatedPresence = null;
synchronized (this)
{
if (lastPresenceSent == null)
{
return;
}
if (lastPresenceSent.removeExtension(elementName, namespace) != null)
{
updatedPresence = lastPresenceSent.build();
}
}
if (updatedPresence != null)
{
try
{
xmppConnection.sendStanza(updatedPresence);
}
catch (Exception e)
{
logger.error("Failed to send stanza:", e);
}
}
}
/**
* Resets the field which stores the last presence Smack sent on our
* behalf.
*/
private synchronized void resetLastPresenceSent()
{
logger.debug("Resetting lastPresenceSent");
lastPresenceSent = null;
}
}
/**
* Detects ping failures and in case of two consecutive failures where the connection is still
* connected and authenticated we will close it and let the connectRetry task handle that.
*/
private class PingFailedListenerImpl
implements PingFailedListener
{
/**
* When ping fails the PingManager stops scheduling new pings.
* That's why we will send manually another one to check and disconnect if that fails.
*/
@Override
public void pingFailed()
{
logger.warn("Ping failed, the XMPP connection needs to reconnect.");
if (xmppConnection.isConnected() && xmppConnection.isAuthenticated())
{
logger.warn("XMPP connection still connected, will trigger a disconnect.");
// two pings in a row fail and the XMPP connection is connected and authenticated.
// This is a weird situation that we have seen in the past when using VPN.
// Everything stays like this forever as the socket remains open on the OS level
// and it is never dropped. We will trigger reconnect just in case.
xmppConnection.disconnect();
}
}
}
private final PeriodicRunnable halfOpenConnectionPeriodicCheck = new HalfOpenConnectionPeriodicCheck();
/**
* @return the {@link PeriodicRunnable} that checks the XMPP connection state and triggers a disconnect if a
* half-open connection is detected.
*/
public PeriodicRunnable getHalfOpenConnectionPeriodicCheck()
{
return halfOpenConnectionPeriodicCheck;
}
/**
* Periodically checks the connection state and triggers a disconnect if a half-open connection is detected.
*/
class HalfOpenConnectionPeriodicCheck
extends PeriodicRunnable
{
public HalfOpenConnectionPeriodicCheck() {
super(2*1000*DEFAULT_PING_INTERVAL_SECONDS);
}
/**
* Triggers a disconnect if a half-open connection is detected.
*/
@Override
public void run() {
super.run();
AbstractXMPPConnection con = xmppConnection;
if (con != null && con.isConnected() && con.isAuthenticated())
{
long lastStanzaReceivedMs = con.getLastStanzaReceived();
if (lastStanzaReceivedMs > 0)
{
long nowMs = System.currentTimeMillis();
if (nowMs - lastStanzaReceivedMs > 2 * 1000 * DEFAULT_PING_INTERVAL_SECONDS)
{
logger.warn("Half-open XMPP connection detected, will trigger a disconnect.");
con.disconnect();
}
}
}
}
}
}