-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathXMPPServer.java
More file actions
1805 lines (1635 loc) · 72.3 KB
/
Copy pathXMPPServer.java
File metadata and controls
1805 lines (1635 loc) · 72.3 KB
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2004-2008 Jive Software, 2016-2026 Ignite Realtime Foundation. All rights reserved.
*
* 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.jivesoftware.openfire;
import com.google.common.reflect.ClassPath;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.logging.log4j.LogManager;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.JNDIDataSourceProvider;
import org.jivesoftware.openfire.admin.AdminManager;
import org.jivesoftware.openfire.archive.ArchiveManager;
import org.jivesoftware.openfire.audit.AuditManager;
import org.jivesoftware.openfire.audit.spi.AuditManagerImpl;
import org.jivesoftware.openfire.cluster.ClusterManager;
import org.jivesoftware.openfire.cluster.ClusterMonitor;
import org.jivesoftware.openfire.cluster.NodeID;
import org.jivesoftware.openfire.commands.AdHocCommandHandler;
import org.jivesoftware.openfire.component.InternalComponentManager;
import org.jivesoftware.openfire.container.AdminConsolePlugin;
import org.jivesoftware.openfire.container.Module;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.csi.CsiModule;
import org.jivesoftware.openfire.disco.*;
import org.jivesoftware.openfire.entitycaps.EntityCapabilitiesManager;
import org.jivesoftware.openfire.filetransfer.DefaultFileTransferManager;
import org.jivesoftware.openfire.filetransfer.FileTransferManager;
import org.jivesoftware.openfire.filetransfer.proxy.FileTransferProxy;
import org.jivesoftware.openfire.handler.*;
import org.jivesoftware.openfire.keystore.CertificateStoreManager;
import org.jivesoftware.openfire.keystore.IdentityStore;
import org.jivesoftware.openfire.lockout.LockOutManager;
import org.jivesoftware.openfire.mediaproxy.MediaProxyService;
import org.jivesoftware.openfire.muc.MultiUserChatManager;
import org.jivesoftware.openfire.net.MulticastDNSService;
import org.jivesoftware.openfire.net.ServerTrafficCounter;
import org.jivesoftware.openfire.pep.IQPEPHandler;
import org.jivesoftware.openfire.pep.IQPEPOwnerHandler;
import org.jivesoftware.openfire.pubsub.PubSubModule;
import org.jivesoftware.openfire.roster.DefaultRosterItemProvider;
import org.jivesoftware.openfire.roster.RosterItem;
import org.jivesoftware.openfire.roster.RosterItemProvider;
import org.jivesoftware.openfire.roster.RosterManager;
import org.jivesoftware.openfire.sasl.AnonymousSaslServer;
import org.jivesoftware.openfire.session.ConnectionSettings;
import org.jivesoftware.openfire.session.RemoteSessionLocator;
import org.jivesoftware.openfire.session.SoftwareServerVersionManager;
import org.jivesoftware.openfire.session.SoftwareVersionManager;
import org.jivesoftware.openfire.spi.*;
import org.jivesoftware.openfire.transport.TransportHandler;
import org.jivesoftware.openfire.update.UpdateManager;
import org.jivesoftware.openfire.user.User;
import org.jivesoftware.openfire.user.UserManager;
import org.jivesoftware.openfire.vcard.xep0398.UserAvatarToVCardConvertor;
import org.jivesoftware.openfire.vcard.VCardManager;
import org.jivesoftware.util.*;
import org.jivesoftware.util.cache.CacheFactory;
import org.jivesoftware.util.cert.CertificateExpiryChecker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import javax.annotation.Nonnull;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
/**
* The main XMPP server that will load, initialize and start all the server's
* modules. The server is unique in the JVM and could be obtained by using the
* {@link #getInstance()} method.
* <p>
* The loaded modules will be initialized and may access through the server other
* modules. This means that the only way for a module to locate another module is
* through the server. The server maintains a list of loaded modules.
* </p>
* <p>
* After starting up all the modules the server will load any available plugin.
* For more information see: {@link org.jivesoftware.openfire.container.PluginManager}.
* </p>
* <p>A configuration file keeps the server configuration. This information is required for the
* server to work correctly. The server assumes that the configuration file is named
* <b>openfire.xml</b> and is located in the <b>conf</b> folder. The folder that keeps
* the configuration file must be located under the home folder. The server will try different
* methods to locate the home folder.</p>
* <ol>
* <li><b>system property</b> - The server will use the value defined in the <i>openfireHome</i>
* system property.</li>
* <li><b>working folder</b> - The server will check if there is a <i>conf</i> folder in the
* working directory. This is the case when running in standalone mode.</li>
* <li><b>openfire_init.xml file</b> - Attempt to load the value from openfire_init.xml which
* must be in the classpath</li>
* </ol>
*
* @author Gaston Dombiak
*/
public class XMPPServer {
private static final Logger logger = LoggerFactory.getLogger(XMPPServer.class);
private static XMPPServer instance;
private boolean initialized = false;
private boolean started = false;
private NodeID nodeID;
private Timer terminatorTimer;
public static final String EXIT = "exit";
private final static Set<String> XML_ONLY_PROPERTIES;
static {
final List<String> properties = new ArrayList<>(Arrays.asList(
// Admin console network settings
"adminConsole.port", "adminConsole.securePort", "adminConsole.interface", "network.interface",
// Misc. settings
"locale", "fqdn", "setup", ClusterManager.CLUSTER_PROPERTY_NAME, ClusterManager.NODEID_PROPERTY_NAME,
// Database config
"connectionProvider.className",
"database.defaultProvider.driver", "database.defaultProvider.serverURL", "database.defaultProvider.username",
"database.defaultProvider.password", "database.defaultProvider.testSQL", "database.defaultProvider.testBeforeUse",
"database.defaultProvider.testAfterUse", "database.defaultProvider.testTimeout", "database.defaultProvider.timeBetweenEvictionRuns",
"database.defaultProvider.minIdleTime", "database.defaultProvider.maxWaitTime", "database.defaultProvider.minConnections",
"database.defaultProvider.maxConnections", "database.defaultProvider.connectionTimeout", "database.mysql.useUnicode",
"database.JNDIProvider.name"
));
// JDNI database config
properties.addAll(Arrays.asList(JNDIDataSourceProvider.jndiPropertyKeys));
XML_ONLY_PROPERTIES = Collections.unmodifiableSet(new HashSet<>(properties));
}
/**
* All modules loaded by this server
*/
private Map<Class<Module>, Module> modules = new LinkedHashMap<>();
/**
* Listeners that will be notified when the server has started or is about to be stopped.
*/
private List<XMPPServerListener> listeners = new CopyOnWriteArrayList<>();
/**
* Location of the home directory. All configuration files should be
* located here.
*/
private Path openfireHome;
private ClassLoader loader;
private PluginManager pluginManager;
private InternalComponentManager componentManager;
private RemoteSessionLocator remoteSessionLocator;
/**
* True if in setup mode
*/
private boolean setupMode = true;
private static final String STARTER_CLASSNAME =
"org.jivesoftware.openfire.starter.ServerStarter";
private static final String WRAPPER_CLASSNAME =
"org.tanukisoftware.wrapper.WrapperManager";
private boolean shuttingDown;
private XMPPServerInfoImpl xmppServerInfo;
/**
* Returns a singleton instance of XMPPServer.
*
* @return an instance.
*/
public static XMPPServer getInstance() {
return instance;
}
/**
* TODO: (2019-04-24) Remove and replace with <a href="https://github.com/mockito/mockito/issues/1013">Mockito mocking of static methods</a>, when available
*
* @param instance the mock/stub/spy XMPPServer to return when {@link #getInstance()} is called.
* @deprecated - for test use only
*/
@Deprecated
public static void setInstance(final XMPPServer instance) {
XMPPServer.instance = instance;
}
/**
* Creates a server and starts it.
*/
public XMPPServer() {
// We may only have one instance of the server running on the JVM
if (instance != null) {
throw new IllegalStateException("A server is already running");
}
instance = this;
start();
}
/**
* Returns a snapshot of the server's status.
*
* @return the server information current at the time of the method call.
*/
public XMPPServerInfo getServerInfo() {
if (!initialized) {
throw new IllegalStateException("Not initialized yet");
}
return xmppServerInfo;
}
/**
* Returns true if the given address is local to the server (managed by this
* server domain). Return false even if the jid's domain matches a local component's
* service JID.
*
* @param jid the JID to check.
* @return true if the address is a local address to this server.
*/
public boolean isLocal( JID jid )
{
return jid != null && jid.getDomain().equals( xmppServerInfo.getXMPPDomain() );
}
/**
* Returns true if the domain-part of the given address does not match the local server hostname and does not
* match a component service JID
*
* @param jid the JID to check.
* @return true if the given address does not match the local server hostname and does not
* match a component service JID.
*/
public boolean isRemote( JID jid )
{
return jid != null
&& !jid.getDomain().equals( xmppServerInfo.getXMPPDomain() )
&& !componentManager.hasComponent( new JID(null, jid.getDomain(), null, true) );
}
/**
* Returns an ID that uniquely identifies this server in a cluster.
*
* @return an ID that uniquely identifies this server in a cluster.
*/
@Nonnull
public NodeID getNodeID() {
if (nodeID == null) {
throw new IllegalStateException("Not initialized yet.");
}
return nodeID;
}
/**
* Sets an ID that uniquely identifies this server in a cluster.
*
* @param nodeID an ID that uniquely identifies this server in a cluster.
*/
public void setNodeID(@Nonnull final NodeID nodeID) {
this.nodeID = Objects.requireNonNull(nodeID, "nodeID argument cannot be null");
}
/**
* @return The node ID.
* @deprecated use {@link #getNodeID()} instead. In versions of Openfire prior to 4.4.0, the cluster node identifier of a server was changed when a server joined a cluster. That's no longer the case: a cluster node now has a static identifier. As such, it's no longer needed to distinguish between the 'default' nodeID (which was used when no cluster was joined) and the cluster node ID.
*/
@Deprecated(forRemoval = true, since = "5.1.0") // Remove in or after Openfire 5.2.0.
public NodeID getDefaultNodeID() {
return getNodeID();
}
/**
* Returns true if the domain-part of the given address matches a component service JID for a component that is
* connected to the local XMPP domain.
*
* @param jid the JID to check.
* @return true if the given address matches a component service JID.
*/
public boolean matchesComponent( JID jid )
{
return jid != null
&& !jid.getDomain().equals( xmppServerInfo.getXMPPDomain() )
&& componentManager.hasComponent( new JID(null, jid.getDomain(), null, true) );
}
/**
* Creates an XMPPAddress local to this server.
*
* @param username the user name portion of the id or null to indicate none is needed.
* @param resource the resource portion of the id or null to indicate none is needed.
* @return an XMPPAddress for the server.
*/
public JID createJID(String username, String resource) {
return new JID(username, xmppServerInfo.getXMPPDomain(), resource);
}
/**
* Creates an XMPPAddress local to this server. The construction of the new JID
* can be optimized by skipping stringprep operations.
*
* @param username the user name portion of the id or null to indicate none is needed.
* @param resource the resource portion of the id or null to indicate none is needed.
* @param skipStringprep true if stringprep should not be applied.
* @return an XMPPAddress for the server.
*/
public JID createJID(String username, String resource, boolean skipStringprep) {
return new JID(username, xmppServerInfo.getXMPPDomain(), resource, skipStringprep);
}
/**
* Returns a collection with the JIDs of the server's admins. The collection may include
* JIDs of local users and users of remote servers.
*
* @return a collection with the JIDs of the server's admins.
*/
public Collection<JID> getAdmins() {
return AdminManager.getInstance().getAdminAccounts();
}
/**
* Adds a new server listener that will be notified when the server has been started
* or is about to be stopped.
*
* @param listener the new server listener to add.
*/
public void addServerListener(XMPPServerListener listener) {
listeners.add(listener);
}
/**
* Removes a server listener that was being notified when the server was being started
* or was about to be stopped.
*
* @param listener the server listener to remove.
*/
public void removeServerListener(XMPPServerListener listener) {
listeners.remove(listener);
}
private void initialize() throws FileNotFoundException {
locateOpenfire();
if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
setupMode = false;
}
if (isStandAlone()) {
logger.info("Registering shutdown hook (standalone mode)");
Runtime.getRuntime().addShutdownHook(new ShutdownHookThread());
terminatorTimer = new Timer(); // Not using TaskEngine here, as that requires configuration to be available, which it is not yet.
terminatorTimer.schedule(new Terminator(), 1000, 1000);
}
loader = Thread.currentThread().getContextClassLoader();
try {
CacheFactory.initialize();
} catch (InitializationException e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
JiveGlobals.migrateProperty(XMPPServerInfo.XMPP_DOMAIN.getKey());
JiveGlobals.migrateProperty(Log.DEBUG_ENABLED.getKey());
if (Log.DEBUG_ENABLED.getValue()) {
Log.setDebugEnabled(true);
}
if (Log.TRACE_ENABLED.getValue()) {
Log.setTraceEnabled(true);
}
// Update server info
xmppServerInfo = new XMPPServerInfoImpl(new Date());
initialized = true;
if (setupMode && "true".equals(JiveGlobals.getXMLProperty("autosetup.run"))) {
this.runAutoSetup();
JiveGlobals.deleteXMLProperty("autosetup");
JiveGlobals.deleteProperty("autosetup");
}
// OF-1548: Move the storage of the FQDN from the database to the XML configuration
final String hostNameFromDatabase = JiveGlobals.getProperty("xmpp.fqdn", "");
final String hostNameFromXML = JiveGlobals.getXMLProperty("fqdn", "");
if (!hostNameFromDatabase.isEmpty() && hostNameFromXML.isEmpty()) {
final String hostname;
if (ClusterManager.isClusteringEnabled()) {
// The database value has at best a 50% chance of being right - so instead use a sensible default
String hostnameFromOS;
try {
hostnameFromOS = InetAddress.getLocalHost().getCanonicalHostName();
} catch (final UnknownHostException e) {
logger.warn("Unable to determine local hostname", e);
hostnameFromOS = "localhost";
}
hostname = hostnameFromOS;
} else {
hostname = hostNameFromDatabase;
}
JiveGlobals.setXMLProperty("fqdn", hostname);
JiveGlobals.deleteProperty("xmpp.fqdn");
}
initClusterNodeID();
}
void runAutoSetup() {
// Setup property encryptor as early as possible so that database related properties can use it
JiveGlobals.setupPropertyEncryptionAlgorithm(JiveGlobals.getXMLProperty("autosetup.encryption.algorithm", "Blowfish")); // or AES
JiveGlobals.setupPropertyEncryptionKey(JiveGlobals.getXMLProperty("autosetup.encryption.key", null));
// steps from setup-datasource-standard.jsp
// do this first so that other changes persist
if ("standard".equals(JiveGlobals.getXMLProperty("autosetup.database.mode"))) {
JiveGlobals.setXMLProperty("database.defaultProvider.driver", JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.driver"));
JiveGlobals.setXMLProperty("database.defaultProvider.serverURL", JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.serverURL"));
JiveGlobals.setXMLProperty("database.defaultProvider.username", JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.username"));
JiveGlobals.setXMLProperty("database.defaultProvider.password", JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.password"));
int minConnections;
int maxConnections;
double connectionTimeout;
try {
minConnections = Integer.parseInt(
JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.minConnections"));
}
catch (Exception e) {
minConnections = 5;
}
try {
maxConnections = Integer.parseInt(
JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.maxConnections"));
}
catch (Exception e) {
maxConnections = 25;
}
try {
connectionTimeout = Double.parseDouble(
JiveGlobals.getXMLProperty("autosetup.database.defaultProvider.connectionTimeout"));
}
catch (Exception e) {
connectionTimeout = 1.0;
}
JiveGlobals.setXMLProperty("database.defaultProvider.minConnections",
Integer.toString(minConnections));
JiveGlobals.setXMLProperty("database.defaultProvider.maxConnections",
Integer.toString(maxConnections));
JiveGlobals.setXMLProperty("database.defaultProvider.connectionTimeout",
Double.toString(connectionTimeout));
}
// mark setup as done, so that other things can be written to the DB
JiveGlobals.setXMLProperty("setup","true");
// steps from index.jsp
String localeCode = JiveGlobals.getXMLProperty("autosetup.locale");
logger.info("Setting locale to {}", localeCode);
JiveGlobals.setLocale(LocaleUtils.localeCodeToLocale(localeCode.trim()));
// steps from setup-host-settings.jsp
JiveGlobals.setXMLProperty(XMPPServerInfo.XMPP_DOMAIN.getKey(), JiveGlobals.getXMLProperty("autosetup." + XMPPServerInfo.XMPP_DOMAIN.getKey()));
JiveGlobals.setXMLProperty("fqdn", JiveGlobals.getXMLProperty("autosetup.xmpp.fqdn"));
JiveGlobals.migrateProperty(XMPPServerInfo.XMPP_DOMAIN.getKey());
ConnectionSettings.Client.ENABLE_OLD_SSLPORT_PROPERTY.setValue(Boolean.valueOf(JiveGlobals.getXMLProperty("autosetup." + ConnectionSettings.Client.ENABLE_OLD_SSLPORT_PROPERTY.getKey(), "true")));
AnonymousSaslServer.ENABLED.setValue(Boolean.valueOf(JiveGlobals.getXMLProperty("autosetup." + AnonymousSaslServer.ENABLED.getKey(), "false")));
// steps from setup-profile-settings.jsp
if ("default".equals(JiveGlobals.getXMLProperty("autosetup.authprovider.mode", "default"))) {
// make configurable?
JiveGlobals.setProperty("user.scramHashedPasswordOnly", "true");
}
// steps from setup-admin-settings.jsp: change attributes of the default admin user
if (JiveGlobals.getXMLProperty("autosetup.admin.password") != null || JiveGlobals.getXMLProperty("autosetup.admin.email") != null) {
try {
User adminUser = UserManager.getInstance().getUser("admin");
if (JiveGlobals.getXMLProperty("autosetup.admin.password") != null) {
adminUser.setPassword(JiveGlobals.getXMLProperty("autosetup.admin.password"));
}
if (JiveGlobals.getXMLProperty("autosetup.admin.email") != null) {
adminUser.setEmail(JiveGlobals.getXMLProperty("autosetup.admin.email"));
}
Date now = new Date();
adminUser.setCreationDate(now);
adminUser.setModificationDate(now);
} catch (Exception e) {
e.printStackTrace();
logger.warn("There was an unexpected error encountered when "
+ "setting the new admin information. Please check your error "
+ "logs and try to remedy the problem.");
}
}
// Import any provisioned users.
try {
RosterItemProvider rosterItemProvider = null;
for (int userId = 1; userId < Integer.MAX_VALUE; userId++ ) {
final String username = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".username" );
final String password = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".password" );
if (username == null || password == null) {
break;
}
final String name = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".name" );
final String email = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".email" );
final User user = UserManager.getInstance().createUser(username, password, name, email );
for (int itemId = 1; itemId < Integer.MAX_VALUE; itemId++) {
final String jid = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".roster.item" + itemId + ".jid" );
if (jid == null) {
break;
}
final String nickname = JiveGlobals.getXMLProperty( "autosetup.users.user" + userId + ".roster.item" + itemId + ".nickname" );
final RosterItem rosterItem = new RosterItem(new JID(jid), RosterItem.SubType.BOTH, RosterItem.AskType.NONE, RosterItem.RecvType.NONE, nickname, null);
if (rosterItemProvider == null) {
// Modules have not started at this point, so we can't go through the roster. Use the default provider instead.
rosterItemProvider = new DefaultRosterItemProvider();
}
rosterItemProvider.createItem(user.getUsername(), rosterItem);
}
}
} catch (Exception e) {
e.printStackTrace();
logger.warn("There was an unexpected error encountered when provisioning auto-setup provided users.", e);
}
// finish setup
this.finalSetupSteps();
setupMode = false;
}
/**
* Initialize the (supposedly unique) identifier of this server in a cluster of servers.
*/
private void initClusterNodeID()
{
final String staticNodeID = JiveGlobals.getXMLProperty(ClusterManager.NODEID_PROPERTY_NAME);
if (staticNodeID != null && !staticNodeID.isEmpty()) {
nodeID = NodeID.getInstance(staticNodeID.getBytes(StandardCharsets.UTF_8));
} else {
nodeID = NodeID.getInstance( UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8) );
JiveGlobals.setXMLProperty(ClusterManager.NODEID_PROPERTY_NAME, nodeID.toString());
}
}
private void finalSetupSteps() {
for (String propName : JiveGlobals.getXMLPropertyNames()) {
if (!XML_ONLY_PROPERTIES.contains(propName)) {
if (JiveGlobals.getProperty(propName) == null) {
JiveGlobals.setProperty(propName, JiveGlobals.getXMLProperty(propName));
}
JiveGlobals.setPropertyEncrypted(propName, JiveGlobals.isXMLPropertyEncrypted(propName));
}
}
// Check if keystore (that out-of-the-box is a fallback for all keystores) already has certificates for current domain.
CertificateStoreManager certificateStoreManager = null; // Will be a module after finishing setup.
try {
certificateStoreManager = new CertificateStoreManager(true);
certificateStoreManager.initialize( this );
certificateStoreManager.start();
final IdentityStore identityStore = certificateStoreManager.getIdentityStore( ConnectionType.SOCKET_C2S );
identityStore.ensureDomainCertificate();
} catch (Exception e) {
logger.error("Error generating self-signed certificates", e);
} finally {
if (certificateStoreManager != null)
{
certificateStoreManager.stop();
certificateStoreManager.destroy();
}
}
// Initialize list of admins now (before we restart Jetty)
AdminManager.getInstance().getAdminAccounts();
}
/**
* Finish the setup process. Because this method is meant to be called from inside
* the Admin console plugin, it spawns its own thread to do the work so that the
* class loader is correct.
*/
public void finishSetup() {
if (!setupMode) {
return;
}
this.finalSetupSteps();
// Make sure that setup finished correctly.
if ("true".equals(JiveGlobals.getXMLProperty("setup"))) {
// Iterate through all the provided XML properties and set the ones that haven't
// already been touched by setup prior to this method being called.
Thread finishSetup = new Thread(() -> {
try {
if (isStandAlone()) {
// Always restart the HTTP server manager. This covers the case
// of changing the ports, as well as generating self-signed certificates.
// Wait a short period before shutting down the admin console.
// Otherwise, the page that requested the setup finish won't
// render properly!
Thread.sleep(1000);
pluginManager.getPluginByCanonicalName("admin").ifPresent(plugin -> ((AdminConsolePlugin) plugin).restart());
}
verifyDataSource();
// First load all the modules so that modules may access other modules while
// being initialized
loadModules();
// Initize all the modules
initModules();
// Start all the modules
startModules();
scanForSystemPropertyClasses();
}
catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
shutdownServer();
}
});
// Use the correct class loader.
finishSetup.setContextClassLoader(loader);
finishSetup.start();
// We can now safely indicate that setup has finished
setupMode = false;
}
}
public void start() {
try {
initialize();
// Create PluginManager now (but don't start it) so that modules may use it
Path pluginDir = openfireHome.resolve("plugins");
pluginManager = new PluginManager(pluginDir);
// If the server has already been setup then we can start all the server's modules
if (!setupMode) {
verifyDataSource();
// First load all the modules so that modules may access other modules while
// being initialized
loadModules();
// Initize all the modules
initModules();
// Start all the modules
startModules();
}
// Initialize statistics
ServerTrafficCounter.initStatistics();
// Load plugins (when in setup mode only the admin console will be loaded)
pluginManager.start();
// Log that the server has been started
String startupBanner = LocaleUtils.getLocalizedString("short.title") + " " + xmppServerInfo.getVersion().getVersionString() +
" [" + JiveGlobals.formatDateTime(new Date()) + "]";
logger.info(startupBanner);
System.out.println(startupBanner);
started = true;
// Notify server listeners that the server has been started
for (XMPPServerListener listener : listeners) {
try {
listener.serverStarted();
} catch (Exception e) {
logger.warn("An exception occurred while dispatching a 'serverStarted' event!", e);
}
}
if (!setupMode) {
scanForSystemPropertyClasses();
}
}
catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
System.out.println(LocaleUtils.getLocalizedString("startup.error"));
shutdownServer();
}
}
// A SystemProperty class will not appear in the System Properties screen until it is referenced. This method
// ensures that they are all referenced immediately.
// The following class cannot always be loaded as it references a class that's part of the Install4J launcher
private static final Set<String> CLASSES_TO_EXCLUDE = Collections.singleton("org.jivesoftware.openfire.launcher.Uninstaller");
private void scanForSystemPropertyClasses() {
try {
final Set<ClassPath.ClassInfo> classesInPackage = ClassPath.from(getClass().getClassLoader()).getTopLevelClassesRecursive("org.jivesoftware.openfire");
for (final ClassPath.ClassInfo classInfo : classesInPackage) {
final String className = classInfo.getName();
if (!CLASSES_TO_EXCLUDE.contains(className)) {
try {
final Class<?> clazz = classInfo.load();
final Field[] fields = clazz.getDeclaredFields();
for (final Field field : fields) {
if (field.getType().equals(SystemProperty.class)) {
try {
field.setAccessible(true);
logger.debug("Accessing SystemProperty field {}#{}", className, field.getName());
field.get(null);
} catch (final Throwable t) {
logger.warn("Unable to access field {}#{}", className, field.getName(), t);
}
}
}
} catch (final Throwable t) {
logger.warn("Unable to load class {}", className, t);
}
}
}
} catch (final Throwable t) {
logger.warn("Unable to scan classpath for SystemProperty classes", t);
}
}
private void loadModules() {
// Load boot modules
loadModule(RoutingTableImpl.class.getName());
loadModule(AuditManagerImpl.class.getName());
loadModule(RosterManager.class.getName());
loadModule(PrivateStorage.class.getName());
// Load core modules
loadModule(PresenceManagerImpl.class.getName());
loadModule(SessionManager.class.getName());
loadModule(PacketRouterImpl.class.getName());
loadModule(IQRouter.class.getName());
loadModule(MessageRouter.class.getName());
loadModule(PresenceRouter.class.getName());
loadModule(MulticastRouter.class.getName());
loadModule(PacketTransporterImpl.class.getName());
loadModule(PacketDelivererImpl.class.getName());
loadModule(TransportHandler.class.getName());
loadModule(OfflineMessageStrategy.class.getName());
loadModule(OfflineMessageStore.class.getName());
loadModule(VCardManager.class.getName());
// Load standard modules
loadModule(CsiModule.class.getName());
loadModule(IQBindHandler.class.getName());
loadModule(IQSessionEstablishmentHandler.class.getName());
loadModule(IQPingHandler.class.getName());
loadModule(IQBlockingHandler.class.getName());
loadModule(IQPrivateHandler.class.getName());
loadModule(IQRegisterHandler.class.getName());
loadModule(IQRosterHandler.class.getName());
loadModule(IQEntityTimeHandler.class.getName());
loadModule(IQvCardHandler.class.getName());
loadModule(IQVersionHandler.class.getName());
loadModule(IQLastActivityHandler.class.getName());
loadModule(PresenceSubscribeHandler.class.getName());
loadModule(PresenceUpdateHandler.class.getName());
loadModule(IQOfflineMessagesHandler.class.getName());
loadModule(IQPEPHandler.class.getName());
loadModule(IQPEPOwnerHandler.class.getName());
loadModule(MulticastDNSService.class.getName());
loadModule(IQSharedGroupHandler.class.getName());
loadModule(AdHocCommandHandler.class.getName());
loadModule(IQPrivacyHandler.class.getName());
loadModule(DefaultFileTransferManager.class.getName());
loadModule(FileTransferProxy.class.getName());
loadModule(MediaProxyService.class.getName());
loadModule(PubSubModule.class.getName());
loadModule(IQDiscoInfoHandler.class.getName());
loadModule(IQDiscoItemsHandler.class.getName());
loadModule(UpdateManager.class.getName());
loadModule(InternalComponentManager.class.getName());
loadModule(MultiUserChatManager.class.getName());
loadModule(IQMessageCarbonsHandler.class.getName());
loadModule(ArchiveManager.class.getName());
loadModule(CertificateStoreManager.class.getName());
loadModule(EntityCapabilitiesManager.class.getName());
loadModule(SoftwareVersionManager.class.getName());
loadModule(SoftwareServerVersionManager.class.getName());
loadModule(CertificateExpiryChecker.class.getName());
loadModule(UserAvatarToVCardConvertor.class.getName());
// Load this module always last since we don't want to start listening for clients
// before the rest of the modules have been started
loadModule(ConnectionManagerImpl.class.getName());
loadModule(ClusterMonitor.class.getName());
// Keep a reference to the internal component manager
componentManager = getComponentManager();
}
/**
* Loads a module.
*
* @param module the name of the class that implements the Module interface.
*/
private void loadModule(String module) {
try {
Class<Module> modClass = (Class<Module>) loader.loadClass(module);
Module mod = modClass.newInstance();
this.modules.put(modClass, mod);
}
catch (Exception e) {
e.printStackTrace();
logger.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
private void initModules() {
for (Module module : modules.values()) {
try {
module.initialize(this);
}
catch (Exception e) {
e.printStackTrace();
// Remove the failed initialized module
this.modules.remove(module.getClass());
module.stop();
module.destroy();
logger.error(LocaleUtils.getLocalizedString("admin.error"), e);
}
}
// Register modules with service discovery provides where applicable.
for (Module module : modules.values() )
{
// Service discovery info
if (module instanceof ServerFeaturesProvider) {
getIQDiscoInfoHandler().addServerFeaturesProvider( (ServerFeaturesProvider) module );
}
if (module instanceof ServerIdentitiesProvider) {
getIQDiscoInfoHandler().addServerIdentitiesProvider( (ServerIdentitiesProvider) module );
}
if (module instanceof UserIdentitiesProvider) {
getIQDiscoInfoHandler().addUserIdentitiesProvider( (UserIdentitiesProvider) module );
}
if (module instanceof UserFeaturesProvider ) {
getIQDiscoInfoHandler().addUserFeaturesProvider( (UserFeaturesProvider) module );
}
// Service discovery items
if (module instanceof ServerItemsProvider) {
getIQDiscoItemsHandler().addServerItemsProvider( (ServerItemsProvider) module );
}
if (module instanceof UserItemsProvider) {
getIQDiscoItemsHandler().addUserItemsProvider( (UserItemsProvider) module);
}
}
}
/**
* <p>Following the loading and initialization of all the modules
* this method is called to iterate through the known modules and
* start them.</p>
*/
private void startModules() {
for (Module module : modules.values()) {
try {
logger.debug( "Starting module: " + module.getName() );
module.start();
}
catch (Exception e) {
logger.error( "An exception occurred while starting module '{}'.", module.getName(), e );
}
}
}
/**
* Restarts the server and all it's modules only if the server is restartable. Otherwise do
* nothing.
*/
public void restart() {
if (isStandAlone() && isRestartable()) {
try {
Class<?> wrapperClass = Class.forName(WRAPPER_CLASSNAME);
Method restartMethod = wrapperClass.getMethod("restart", (Class []) null);
restartMethod.invoke(null, (Object []) null);
}
catch (Exception e) {
logger.error("Could not restart container", e);
}
}
}
/**
* Restarts the HTTP server only when running in stand alone mode. The restart
* process will be done in another thread that will wait 1 second before doing
* the actual restart. The delay will give time to the page that requested the
* restart to fully render its content.
*/
public void restartHTTPServer() {
Thread restartThread = new Thread(() -> {
if (isStandAlone()) {
// Restart the HTTP server manager. This covers the case
// of changing the ports, as well as generating self-signed certificates.
// Wait a short period before shutting down the admin console.
// Otherwise, this page won't render properly!
try {
Thread.sleep(1000);
pluginManager.getPluginByCanonicalName("admin").ifPresent(plugin -> ((AdminConsolePlugin) plugin).restart());
} catch (Exception e) {
e.printStackTrace();
}
}
});
restartThread.setContextClassLoader(loader);
restartThread.start();
}
/**
* Stops the server only if running in standalone mode. Do nothing if the server is running
* inside of another server.
*/
public void stop() {
logger.info("Initiating shutdown ...");
// Only do a system exit if we're running standalone
if (isStandAlone()) {
// if we're in a wrapper, we have to tell the wrapper to shut us down
if (isRestartable()) {
try {
Class<?> wrapperClass = Class.forName(WRAPPER_CLASSNAME);
Method stopMethod = wrapperClass.getMethod("stop", Integer.TYPE);
stopMethod.invoke(null, 0);
}
catch (Exception e) {
logger.error("Could not stop container", e);
}
}
else {
shutdownServer();
Thread shutdownThread = new ShutdownThread();
shutdownThread.setDaemon(true);
shutdownThread.start();
}
}
else {
// Close listening socket no matter what the condition is in order to be able
// to be restartable inside a container.
shutdownServer();
}
}
public boolean isSetupMode() {
return setupMode;
}
public boolean isRestartable() {
boolean restartable;
try {
restartable = Class.forName(WRAPPER_CLASSNAME) != null;
}
catch (ClassNotFoundException e) {
restartable = false;
}
return restartable;
}
/**
* Returns if the server is running in standalone mode. We consider that it's running in
* standalone if the "org.jivesoftware.openfire.starter.ServerStarter" class is present in the
* system.
*
* @return true if the server is running in standalone mode.
*/
public boolean isStandAlone() {
boolean standalone;