-
Notifications
You must be signed in to change notification settings - Fork 138
/
VirtualServer.java
2367 lines (2049 loc) · 92.4 KB
/
VirtualServer.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
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) 2022, 2023 Contributors to the Eclipse Foundation.
* Copyright (c) 1997, 2018 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.enterprise.web;
import com.sun.enterprise.config.serverbeans.ApplicationRef;
import com.sun.enterprise.config.serverbeans.Applications;
import com.sun.enterprise.config.serverbeans.AuthRealm;
import com.sun.enterprise.config.serverbeans.Config;
import com.sun.enterprise.config.serverbeans.ConfigBeansUtilities;
import com.sun.enterprise.config.serverbeans.Domain;
import com.sun.enterprise.config.serverbeans.HttpService;
import com.sun.enterprise.config.serverbeans.SecurityService;
import com.sun.enterprise.config.serverbeans.ServerTags;
import com.sun.enterprise.deploy.shared.ArchiveFactory;
import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.security.web.GlassFishSingleSignOn;
import com.sun.enterprise.util.StringUtils;
import com.sun.enterprise.v3.common.PlainTextActionReporter;
import com.sun.enterprise.v3.services.impl.GrizzlyProxy;
import com.sun.enterprise.v3.services.impl.GrizzlyService;
import com.sun.enterprise.web.logger.CatalinaLogger;
import com.sun.enterprise.web.logger.FileLoggerHandler;
import com.sun.enterprise.web.logger.FileLoggerHandlerFactory;
import com.sun.enterprise.web.logger.VirtualServerGlassFishLogger;
import com.sun.enterprise.web.pluggable.WebContainerFeatureFactory;
import com.sun.enterprise.web.session.SessionCookieConfig;
import com.sun.web.security.RealmAdapter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.catalina.Container;
import org.apache.catalina.ContainerListener;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Pipeline;
import org.apache.catalina.Realm;
import org.apache.catalina.Valve;
import org.apache.catalina.authenticator.AuthenticatorBase;
import org.apache.catalina.authenticator.SingleSignOn;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardHost;
import org.apache.catalina.deploy.ErrorPage;
import org.apache.catalina.valves.RemoteAddrValve;
import org.apache.catalina.valves.RemoteHostValve;
import org.glassfish.api.ActionReport;
import org.glassfish.api.admin.ServerEnvironment;
import org.glassfish.api.deployment.DeployCommandParameters;
import org.glassfish.api.deployment.OpsParams;
import org.glassfish.api.deployment.UndeployCommandParameters;
import org.glassfish.api.deployment.archive.ArchiveHandler;
import org.glassfish.api.deployment.archive.ReadableArchive;
import org.glassfish.deployment.common.ApplicationConfigInfo;
import org.glassfish.deployment.common.DeploymentContextImpl;
import org.glassfish.deployment.common.DeploymentUtils;
import org.glassfish.embeddable.GlassFishException;
import org.glassfish.embeddable.web.ConfigException;
import org.glassfish.embeddable.web.Context;
import org.glassfish.embeddable.web.WebListener;
import org.glassfish.embeddable.web.config.VirtualServerConfig;
import org.glassfish.grizzly.Buffer;
import org.glassfish.grizzly.Connection;
import org.glassfish.grizzly.ConnectionProbe;
import org.glassfish.grizzly.config.GenericGrizzlyListener;
import org.glassfish.grizzly.config.dom.NetworkListener;
import org.glassfish.grizzly.filterchain.FilterChainContext;
import org.glassfish.grizzly.http.HttpCodecFilter;
import org.glassfish.grizzly.http.HttpPacket;
import org.glassfish.grizzly.http.HttpProbe;
import org.glassfish.grizzly.http.HttpRequestPacket;
import org.glassfish.grizzly.http.HttpResponsePacket;
import org.glassfish.grizzly.http.util.HttpStatus;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.internal.api.ClassLoaderHierarchy;
import org.glassfish.internal.api.Globals;
import org.glassfish.internal.api.ServerContext;
import org.glassfish.internal.data.ApplicationInfo;
import org.glassfish.internal.data.ApplicationRegistry;
import org.glassfish.internal.deployment.Deployment;
import org.glassfish.internal.deployment.ExtendedDeploymentContext;
import org.glassfish.main.jul.GlassFishLogManager;
import org.glassfish.main.jul.handler.GlassFishLogHandler;
import org.glassfish.web.LogFacade;
import org.glassfish.web.admin.monitor.RequestProbeProvider;
import org.glassfish.web.deployment.archivist.WebArchivist;
import org.glassfish.web.deployment.descriptor.WebBundleDescriptorImpl;
import org.glassfish.web.loader.WebappClassLoader;
import org.glassfish.web.valve.GlassFishValve;
import org.jvnet.hk2.config.Transaction;
import org.jvnet.hk2.config.TransactionFailure;
import org.jvnet.hk2.config.types.Property;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import static com.sun.enterprise.web.Constants.DEFAULT_WEB_MODULE_NAME;
import static com.sun.enterprise.web.Constants.ERROR_REPORT_VALVE;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.SEVERE;
import static java.util.logging.Level.WARNING;
import static org.glassfish.api.web.Constants.ADMIN_VS;
import static org.glassfish.web.LogFacade.*;
/**
* Standard implementation of a virtual server (aka virtual host) in the iPlanet Application Server.
*/
public class VirtualServer extends StandardHost implements org.glassfish.embeddable.web.VirtualServer {
private static final String SSO_MAX_IDLE = "sso-max-inactive-seconds";
private static final String SSO_REAP_INTERVAL = "sso-reap-interval-seconds";
private static final String DISABLED = "disabled";
private static final String ON = "on";
/**
* The logger to use for logging this virtual server
*/
private static final Logger DEFAULT_LOGGER = LogFacade.getLogger();
/**
* The resource bundle containing the message strings for _logger.
*/
protected static final ResourceBundle rb = DEFAULT_LOGGER.getResourceBundle();
// ------------------------------------------------------------ Constructor
/**
* Default constructor that simply gets a handle to the web container subsystem's logger.
*/
public VirtualServer() {
origPipeline = pipeline;
vsPipeline = new VirtualServerPipeline(this);
accessLogValve = new PEAccessLogValve();
accessLogValve.setContainer(this);
}
// ----------------------------------------------------- Instance Variables
/*
* The custom pipeline of this VirtualServer, which implements the following virtual server features:
*
* - state (disabled/off) - redirects
*/
private final VirtualServerPipeline vsPipeline;
/*
* The original (standard) pipeline of this VirtualServer.
*
* Only one (custom or original) pipeline may be active at any given time. Any updates (such as adding or removing
* valves) to the currently active pipeline are propagated to the other.
*/
private final Pipeline origPipeline;
/**
* The id of this virtual server as specified in the configuration.
*/
private String _id;
/**
* The logger to use for logging this virtual server
*/
protected Logger _logger = DEFAULT_LOGGER;
/**
* The descriptive information about this implementation.
*/
private static final String _info = VirtualServer.class.getName() + "/1.0";
/**
* The config bean associated with this VirtualServer
*/
private com.sun.enterprise.config.serverbeans.VirtualServer vsBean;
/**
* The mime mapping associated with this VirtualServer
*/
private MimeMap mimeMap;
/*
* Indicates whether symbolic links from this virtual server's docroot are followed. This setting is inherited by all
* web modules deployed on this virtual server, unless overridden by a web modules allowLinking property in sun-web.xml.
*/
private boolean allowLinking;
private String[] cacheControls;
private ClassLoaderHierarchy classLoaderHierarchy;
private Domain domain;
private ServiceLocator services;
// Is this virtual server active?
private boolean isActive;
private String authRealmName;
/*
* The accesslog valve of this VirtualServer.
*
* This valve is activated, that is, added to this virtual server's pipeline, only when access logging has been enabled.
* When acess logging has been disabled, this valve is removed from this virtual server's pipeline.
*/
private final PEAccessLogValve accessLogValve;
// The value of the ssoCookieSecure property
private String ssoCookieSecure;
private boolean ssoCookieHttpOnly;
private String defaultContextPath;
private ServerContext serverContext;
private Config serverConfig;
private GrizzlyService grizzlyService;
private WebContainer webContainer;
private boolean ssoFailoverEnabled;
private volatile FileLoggerHandler fileLoggerHandler;
private volatile FileLoggerHandlerFactory fileLoggerHandlerFactory;
private Deployment deployment;
private ArchiveFactory factory;
private ActionReport report;
private VirtualServerConfig config;
private List<WebListener> listeners = new ArrayList<>();
// ------------------------------------------------------------- Properties
/**
* Return the virtual server identifier.
*/
@Override
public String getID() {
return _id;
}
/**
* Set the virtual server identifier string.
*
* @param id New identifier for this virtual server
*/
@Override
public void setID(String id) {
_id = id;
}
/**
* Sets the state of this virtual server.
*
* @param isActive true if this virtual server is active, false otherwise
*/
public void setIsActive(boolean isActive) {
this.isActive = isActive;
if (isActive) {
vsPipeline.setIsDisabled(false);
vsPipeline.setIsOff(false);
if (pipeline == vsPipeline && !vsPipeline.hasRedirects()) {
// Restore original pipeline
setPipeline(origPipeline);
}
}
}
/**
* Gets the value of the allowLinking property of this virtual server.
*
* @return true if symbolic links from this virtual server's docroot (as well as symbolic links from archives of web
* modules deployed on this virtual server) are followed, false otherwise
*/
public boolean getAllowLinking() {
return allowLinking;
}
/**
* Sets the allowLinking property of this virtual server, which determines whether symblic links from this virtual
* server's docroot are followed.
*
* This property is inherited by all web modules deployed on this virtual server, unless overridden by the allowLinking
* property in a web module's sun-web.xml.
*
* @param allowLinking Value of allowLinking property
*/
public void setAllowLinking(boolean allowLinking) {
this.allowLinking = allowLinking;
}
/**
* @return the config bean associated with this VirtualServer.
*/
public com.sun.enterprise.config.serverbeans.VirtualServer getBean() {
return vsBean;
}
/**
* @param vsBean the config bean for this VirtualServer
*/
public void setBean(com.sun.enterprise.config.serverbeans.VirtualServer vsBean) {
this.vsBean = vsBean;
}
/**
* @return the mime map associated with this VirtualServer.
*/
public MimeMap getMimeMap() {
return mimeMap;
}
/**
* Sets the mime map for this VirtualServer
*/
public void setMimeMap(MimeMap mimeMap) {
this.mimeMap = mimeMap;
}
/**
* @return the Cache-Control configuration of this VirtualServer or null if no such
* configuration exists for this VirtualServer
*/
public String[] getCacheControls() {
return cacheControls;
}
/**
* Sets the Cache-Control configuration for this VirtualServer
*
* @param cacheControls Cache-Control configuration settings for this VirtualServer
*/
public void setCacheControls(String[] cacheControls) {
this.cacheControls = cacheControls;
}
public void setServices(ServiceLocator services) {
this.services = services;
}
@Override
public String getInfo() {
return _info;
}
public void setDefaultContextPath(String defaultContextPath) {
this.defaultContextPath = defaultContextPath;
}
public void setFileLoggerHandlerFactory(FileLoggerHandlerFactory factory) {
fileLoggerHandlerFactory = factory;
}
public void setClassLoaderHierarchy(ClassLoaderHierarchy clh) {
this.classLoaderHierarchy = clh;
}
public void setDomain(Domain domain) {
this.domain = domain;
}
@Override
public Container findChild(String contextRoot) {
if (defaultContextPath != null && "/".equals(contextRoot)) {
return super.findChild(defaultContextPath);
}
return super.findChild(contextRoot);
}
// --------------------------------------------------------- Public Methods
/**
* Configures the Secure attribute of the given SSO cookie.
*
* @param ssoCookie the SSO cookie to be configured
* @param hreq the HttpServletRequest that has initiated the SSO session
*/
@Override
public void configureSingleSignOnCookieSecure(Cookie ssoCookie, HttpServletRequest hreq) {
super.configureSingleSignOnCookieSecure(ssoCookie, hreq);
if (ssoCookieSecure != null && !ssoCookieSecure.equals(SessionCookieConfig.DYNAMIC_SECURE)) {
ssoCookie.setSecure(Boolean.parseBoolean(ssoCookieSecure));
}
}
@Override
public void configureSingleSignOnCookieHttpOnly(Cookie ssoCookie) {
ssoCookie.setHttpOnly(ssoCookieHttpOnly);
}
// ------------------------------------------------------ Lifecycle Methods
/**
* Adds the given valve to the currently active pipeline, keeping the pipeline that is not currently active in sync.
*/
@Override
public synchronized void addValve(GlassFishValve valve) {
super.addValve(valve);
if (pipeline == vsPipeline) {
origPipeline.addValve(valve);
} else {
vsPipeline.addValve(valve);
}
}
/**
* Adds the given Tomcat-style valve to the currently active pipeline, keeping the pipeline that is not currently active
* in sync.
*/
@Override
public synchronized void addValve(Valve valve) {
super.addValve(valve);
if (pipeline == vsPipeline) {
origPipeline.addValve(valve);
} else {
vsPipeline.addValve(valve);
}
}
/**
* Removes the given valve from the currently active pipeline, keeping the valve that is not currently active in sync.
*/
@Override
public synchronized void removeValve(GlassFishValve valve) {
super.removeValve(valve);
if (pipeline == vsPipeline) {
origPipeline.removeValve(valve);
} else {
vsPipeline.removeValve(valve);
}
}
private ConfigBeansUtilities getConfigBeansUtilities() {
if (services == null) {
return null;
}
return services.getService(ConfigBeansUtilities.class);
}
// ------------------------------------------------------ Protected Methods
/**
* Gets the context root of the web module that the user/configuration has designated as the default-web-module for this
* virtual server.
*
* The default-web-module for a virtual server is specified via the 'default-web-module' attribute of the
* 'virtual-server' element in server.xml. This is an optional attribute and if the configuration does not specify
* another web module (standalone or part of a j2ee-application) that is configured at a context-root="", then a default
* web module will be created and loaded. The value for this attribute is either "${standalone-web-module-name}" or
* "${j2ee-app-name}:${web-module-uri}".
*
* @return null if the default-web-module has not been specified or if the web module specified either could not be
* found or is disabled or does not specify this virtual server (if it specifies a value for the virtual-servers
* attribute) or if there was an error loading its deployment descriptors.
*/
protected String getDefaultContextPath(Domain domain, ApplicationRegistry appRegistry) {
String contextRoot = null;
String webModuleID = getDefaultWebModuleID();
if (webModuleID != null) {
// Check if the default-web-module is part of a Jakarta EE application
Applications appsBean = domain.getApplications();
WebModuleConfig wmInfo = findWebModuleInJ2eeApp(appsBean, webModuleID, appRegistry);
if (wmInfo == null) {
ConfigBeansUtilities cbu = getConfigBeansUtilities();
if (cbu != null) {
contextRoot = cbu.getContextRoot(webModuleID);
}
} else {
contextRoot = wmInfo.getContextPath();
}
if (contextRoot == null) {
Object[] params = { webModuleID, getID() };
_logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_NOT_FOUND, params);
}
}
return contextRoot;
}
protected WebModuleConfig getDefaultWebModule(Domain domain, WebArchivist webArchivist, ApplicationRegistry appRegistry) {
WebModuleConfig webModuleConfig = null;
String webModuleID = getDefaultWebModuleID();
if (webModuleID != null) {
// Check if the default-web-module is part of a Jakarta EE application
Applications appsBean = domain.getApplications();
webModuleConfig = findWebModuleInJ2eeApp(appsBean, webModuleID, appRegistry);
if (webModuleConfig == null) {
ConfigBeansUtilities cbu = getConfigBeansUtilities();
String contextRoot = null;
String location = null;
if (cbu != null) {
contextRoot = cbu.getContextRoot(webModuleID);
location = cbu.getLocation(webModuleID);
}
if (contextRoot != null && location != null) {
File docroot = new File(location);
WebBundleDescriptorImpl webBundleDescriptor = webArchivist.getDefaultWebXmlBundleDescriptor();
webModuleConfig = new WebModuleConfig();
webBundleDescriptor.setName(DEFAULT_WEB_MODULE_NAME);
webBundleDescriptor.setContextRoot(contextRoot);
webModuleConfig.setLocation(docroot);
webModuleConfig.setDescriptor(webBundleDescriptor);
webModuleConfig.setParentLoader(EmbeddedWebContainer.class.getClassLoader());
PrivilegedAction<WebappClassLoader> action = () -> new WebappClassLoader(
EmbeddedWebContainer.class.getClassLoader());
WebappClassLoader cloader = AccessController.doPrivileged(action);
webModuleConfig.setAppClassLoader(cloader);
}
}
if (webModuleConfig == null) {
_logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_NOT_FOUND, new Object[] { webModuleID, getID() });
}
}
return webModuleConfig;
}
/**
* If a default web module has not yet been configured and added to this virtual server's list of web modules then
* return the configuration information needed in order to create a default web module for this virtual server.
*
* This method should be invoked only after all the standalone modules and the modules within j2ee-application elements
* have been added to this virtual server's list of modules (only then will one know whether the user has already
* configured a default web module or not).
*/
public WebModuleConfig createSystemDefaultWebModuleIfNecessary(WebArchivist webArchivist) {
WebModuleConfig webModuleConfig = null;
// Add a default context only if one hasn't already been loaded
// and then too only if docroot is not null
//
String docroot = getAppBase();
if (getDefaultWebModuleID() == null && findChild("") == null && docroot != null) {
WebBundleDescriptorImpl webBundleDescriptor = webArchivist.getDefaultWebXmlBundleDescriptor();
webModuleConfig = new WebModuleConfig();
webBundleDescriptor.setModuleID(DEFAULT_WEB_MODULE_NAME);
webBundleDescriptor.setContextRoot("");
webModuleConfig.setLocation(new File(docroot));
webModuleConfig.setDescriptor(webBundleDescriptor);
webModuleConfig.setParentLoader(serverContext.getCommonClassLoader());
PrivilegedAction<WebappClassLoader> action = () -> new WebappClassLoader(serverContext.getCommonClassLoader());
WebappClassLoader loader = AccessController.doPrivileged(action);
loader.start();
webModuleConfig.setAppClassLoader(loader);
if (webBundleDescriptor.getApplication() == null) {
Application application = Application.createApplication();
application.setVirtual(true);
application.setName(DEFAULT_WEB_MODULE_NAME);
webBundleDescriptor.setApplication(application);
}
}
return webModuleConfig;
}
/**
* Returns the id of the default web module for this virtual server as specified in the 'default-web-module' attribute
* of the 'virtual-server' element.
*/
protected String getDefaultWebModuleID() {
String webModuleID = vsBean.getDefaultWebModule();
if ("".equals(webModuleID)) {
webModuleID = null;
}
if (webModuleID != null && _logger.isLoggable(FINE)) {
Object[] params = { webModuleID, _id };
_logger.log(FINE, VS_DEFAULT_WEB_MODULE, params);
}
return webModuleID;
}
/**
* Finds and returns information about a web module embedded within a J2EE application, which is identified by a string
* of the form <code>a:b</code> or <code>a#b</code>, where <code>a</code> is the name of the J2EE application and
* <code>b</code> is the name of the embedded web module.
*
* @return null if <code>id</code> does not identify a web module embedded within a J2EE application.
*/
protected WebModuleConfig findWebModuleInJ2eeApp(Applications appsBean, String id, ApplicationRegistry appRegistry) {
WebModuleConfig webModuleConfig = null;
// Check for ':' separator
int separatorIndex = id.indexOf(Constants.NAME_SEPARATOR);
if (separatorIndex == -1) {
// Check for '#' separator
separatorIndex = id.indexOf('#');
}
if (separatorIndex != -1) {
String appID = id.substring(0, separatorIndex);
String moduleID = id.substring(separatorIndex + 1);
com.sun.enterprise.config.serverbeans.Application appBean =
appsBean.getModule(com.sun.enterprise.config.serverbeans.Application.class, appID);
if ((appBean != null) && Boolean.valueOf(appBean.getEnabled())) {
String location = appBean.getLocation();
String moduleDir = DeploymentUtils.getRelativeEmbeddedModulePath(location, moduleID);
ApplicationInfo appInfo = appRegistry.get(appID);
Application app = null;
if (appInfo != null) {
app = appInfo.getMetaData(Application.class);
} else {
// XXX ApplicaionInfo is NULL after restart
Object[] params = { id, getID() };
_logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_DISABLED, params);
return webModuleConfig;
}
WebBundleDescriptorImpl webBundleDescriptor = app.getModuleByTypeAndUri(WebBundleDescriptorImpl.class, moduleID);
String webUri = webBundleDescriptor.getModuleDescriptor().getArchiveUri();
String contextRoot = webBundleDescriptor.getModuleDescriptor().getContextRoot();
if (moduleID.equals(webUri)) {
StringBuilder dir = new StringBuilder(location);
dir.append(File.separator);
dir.append(moduleDir);
File docroot = new File(dir.toString());
webModuleConfig = new WebModuleConfig();
webBundleDescriptor.setName(moduleID);
webBundleDescriptor.setContextRoot(contextRoot);
webModuleConfig.setDescriptor(webBundleDescriptor);
webModuleConfig.setLocation(docroot);
webModuleConfig.setParentLoader(EmbeddedWebContainer.class.getClassLoader());
PrivilegedAction<WebappClassLoader> action = () -> new WebappClassLoader(
EmbeddedWebContainer.class.getClassLoader());
WebappClassLoader cloader = AccessController.doPrivileged(action);
webModuleConfig.setAppClassLoader(cloader);
}
} else {
Object[] params = { id, getID() };
_logger.log(SEVERE, VS_DEFAULT_WEB_MODULE_DISABLED, params);
}
}
return webModuleConfig;
}
/**
* Virtual servers are maintained in the reference contained in Server element. First, we need to find the server and
* then get the virtual server from the correct reference
*
* @param appName Name of the app to get vs
*
* @return virtual servers as a string (separated by space or comma)
*
* private String getVirtualServers(String appName) { String ret = null; Server server =
* Globals.getDefaultHabitat().forContract(Server.class).get(); for (ApplicationRef appRef : server.getApplicationRef())
* { if (appRef.getRef().equals(appName)) { return appRef.getVirtualServers(); } }
*
* return ret; }
*/
/**
* Delete all aliases.
*/
public void clearAliases() {
aliases = new String[0];
}
private void setIsDisabled(boolean isDisabled) {
vsPipeline.setIsDisabled(isDisabled);
vsPipeline.setIsOff(false);
if (isDisabled && pipeline != vsPipeline) {
// Enable custom pipeline
setPipeline(vsPipeline);
}
}
private void setIsOff(boolean isOff) {
vsPipeline.setIsOff(isOff);
vsPipeline.setIsDisabled(false);
if (isOff && pipeline != vsPipeline) {
// Enable custom pipeline
setPipeline(vsPipeline);
}
}
private void close(FileLoggerHandler handler) {
if (handler != null && !handler.isAssociated()) {
if (fileLoggerHandlerFactory != null) {
// should always be here
fileLoggerHandlerFactory.removeHandler(handler.getLogFile());
}
handler.flush();
handler.close();
}
}
private void setLogger(Logger newLogger, String logLevel) {
_logger = newLogger;
// wrap into a cataline logger
CatalinaLogger catalinaLogger = new CatalinaLogger(newLogger);
setLogger(catalinaLogger);
}
/**
* @return The properties of this virtual server
*/
List<Property> getProperties() {
return vsBean.getProperty();
}
/**
* Configures this virtual server.
*/
public void configure(String vsID, com.sun.enterprise.config.serverbeans.VirtualServer vsBean, String vsDocroot, String vsLogFile,
MimeMap vsMimeMap, String logServiceFile, String logLevel) {
setDebug(debug);
setAppBase(vsDocroot);
setName(vsID);
setID(vsID);
setBean(vsBean);
setMimeMap(vsMimeMap);
String defaultContextXmlLocation = Constants.DEFAULT_CONTEXT_XML;
String defaultWebXmlLocation = Constants.DEFAULT_WEB_XML;
// Begin EE: 4920692 Make the default-web.xml be relocatable
Property prop = vsBean.getProperty("default-web-xml");
if (prop != null) {
defaultWebXmlLocation = prop.getValue();
}
// End EE: 4920692 Make the default-web.xml be relocatable
// allowLinking
boolean allowLinking = false;
prop = vsBean.getProperty("allowLinking");
if (prop != null) {
allowLinking = Boolean.parseBoolean(prop.getValue());
}
setAllowLinking(allowLinking);
prop = vsBean.getProperty("contextXmlDefault");
if (prop != null) {
defaultContextXmlLocation = prop.getValue();
}
setDefaultWebXmlLocation(defaultWebXmlLocation);
setDefaultContextXmlLocation(defaultContextXmlLocation);
// Set vs state
String state = vsBean.getState();
if (state == null) {
state = ON;
}
if (DISABLED.equalsIgnoreCase(state)) {
setIsActive(false);
} else {
setIsActive(Boolean.parseBoolean(state));
}
setLogFile(vsLogFile, logLevel, logServiceFile);
}
/**
* Configures the valve_ and listener_ properties of this VirtualServer.
*/
protected void configureCatalinaProperties() {
List<Property> props = vsBean.getProperty();
if (props == null) {
return;
}
for (Property prop : props) {
String propName = prop.getName();
String propValue = prop.getValue();
if (propName == null || propValue == null) {
_logger.log(WARNING, NULL_VIRTUAL_SERVER_PROPERTY, getName());
}
if (propName != null) {
if (propName.startsWith("valve_")) {
addValve(propValue);
} else if (propName.startsWith("listener_")) {
addListener(propValue);
} else if (propName.equals("securePagesWithPragma")) {
setSecurePagesWithPragma(Boolean.parseBoolean(propValue));
}
}
}
}
/**
* Configures this virtual server with the specified log file.
*
* @param logFile The value of the virtual server's log-file attribute in the domain.xml
*/
synchronized void setLogFile(String logFile, String logLevel, String logServiceFile) {
_logger.log(Level.CONFIG, "setLogFile(logFile={0}, logServiceFile={1})",
new Object[] {logFile, logServiceFile});
/*
* Configure separate logger for this virtual server only if 'log-file' attribute of this <virtual-server> and 'file'
* attribute of <log-service> are different (See 6189219).
*/
boolean customLog = (logFile != null && logServiceFile != null
&& !new File(logFile).equals(new File(logServiceFile)));
boolean logFileChanged = logFile != null
&& ((fileLoggerHandler != null && !logFile.equals(fileLoggerHandler.getLogFile()))
|| fileLoggerHandler == null);
/*
* Exit early if the log file isn't being changed.
*/
if (!logFileChanged) {
return;
}
// As it is being changed, close the old file handler
if (fileLoggerHandler != null) {
_logger.removeHandler(fileLoggerHandler);
close(fileLoggerHandler);
fileLoggerHandler = null;
}
// Store new logger to replace current one
// append the _logger name with ".vs.<virtual-server-id>" if it doesn't already have it
final LogManager logManager = LogManager.getLogManager();
final String lname = DEFAULT_LOGGER.getName() + ".vs." + getID();
if (logManager.getLogger(lname) == null) {
final Logger newLogger = new VirtualServerGlassFishLogger(lname, rb);
logManager.addLogger(newLogger);
}
final Logger newLogger = Objects.requireNonNull(logManager.getLogger(lname),
"Failed to get or create a logger " + lname);
if (!customLog) {
for (Handler h : _logger.getHandlers()) {
newLogger.removeHandler(h);
}
newLogger.setUseParentHandlers(true);
setLogger(newLogger);
return;
}
// remove old handlers if necessary
// FIXME: does not respect the configuration - why?
final Handler[] originalLoggerHandlers = newLogger.getHandlers();
if (originalLoggerHandlers != null) {
for (Handler h : originalLoggerHandlers) {
newLogger.removeHandler(h);
}
}
// FIXME: takes handlers only from root logger! What about intermediate?
// add all handlers from root which are not GlassFishLogHandlers
final Logger rootLogger = logManager.getLogger(GlassFishLogManager.ROOT_LOGGER_NAME);
_logger.finest(() -> "rootLogger=" + rootLogger);
if (rootLogger != null) {
final Handler[] rootHandlers = rootLogger.getHandlers();
if (rootHandlers != null) {
for (Handler h : rootHandlers) {
// FIXME: controversial.
// FIXME: Don't use parent handlers (setUseParentHandlers(false)), but uses them.
if (!(h instanceof GlassFishLogHandler)) {
newLogger.addHandler(h);
}
}
}
}
// create and add new handler
fileLoggerHandler = fileLoggerHandlerFactory.getHandler(logFile);
newLogger.addHandler(fileLoggerHandler);
newLogger.setUseParentHandlers(false);
setLogger(newLogger);
}
private void setLogger(Logger newLogger) {
_logger = newLogger;
// wrap into a cataline logger
CatalinaLogger catalinaLogger = new CatalinaLogger(newLogger);
setLogger(catalinaLogger);
}
/**
* Adds each host name from the 'hosts' attribute as an alias
*/
void configureAliases() {
List<String> hosts = StringUtils.parseStringList(vsBean.getHosts(), ",");
for (String host : hosts) {
if (!host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("localhost.localdomain")) {
addAlias(host);
}
}
}
void configureAliases(String... hosts) {
for (String host : hosts) {
if (!host.equalsIgnoreCase("localhost") && !host.equalsIgnoreCase("localhost.localdomain")) {
addAlias(host);
}
}
}
/**
* Configures this virtual server with its authentication realm.
*
* Checks if this virtual server specifies any authRealm property, and if so, ensures that its value identifies a valid
* realm.
*
* @param securityService The security-service element from domain.xml
*/
void configureAuthRealm(SecurityService securityService) {
List<Property> properties = vsBean.getProperty();
if (properties != null && !properties.isEmpty()) {
for (Property p : properties) {
if (p != null && "authRealm".equals(p.getName())) {
authRealmName = p.getValue();
if (authRealmName != null) {
AuthRealm realm = null;
List<AuthRealm> rs = securityService.getAuthRealm();
if (rs != null && rs.size() > 0) {
for (AuthRealm r : rs) {
if (r != null && r.getName().equals(authRealmName)) {
realm = r;
break;
}
}
}
if (realm == null) {
_logger.log(SEVERE, INVALID_AUTH_REALM, new Object[] { getID(), authRealmName });
}
}
break;
}
}
}
}
/**
* @return the value of the authRealm property of this virtual server or null of this virtual
* server does not have any such property
*/
String getAuthRealmName() {