/
BaseConfigurationRecord.cs
4624 lines (3909 loc) · 220 KB
/
BaseConfigurationRecord.cs
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 file="BaseConfigurationRecord.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration {
using System.Configuration.Internal;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Security;
using System.Text;
using System.Threading;
using System.Xml;
using System.Runtime.Versioning;
//
// This object represents the configuration for a request path, and is cached per-path.
//
[System.Diagnostics.DebuggerDisplay("ConfigPath = {ConfigPath}")]
abstract internal class BaseConfigurationRecord : IInternalConfigRecord {
protected const string NL = "\r\n";
internal const string KEYWORD_TRUE = "true";
internal const string KEYWORD_FALSE = "false";
protected const string KEYWORD_CONFIGURATION = "configuration";
protected const string KEYWORD_CONFIGURATION_NAMESPACE = "http://schemas.microsoft.com/.NetConfiguration/v2.0";
protected const string KEYWORD_CONFIGSECTIONS = "configSections";
protected const string KEYWORD_SECTION = "section";
protected const string KEYWORD_SECTION_NAME = "name";
protected const string KEYWORD_SECTION_TYPE = "type";
protected const string KEYWORD_SECTION_ALLOWLOCATION = "allowLocation";
protected const string KEYWORD_SECTION_ALLOWDEFINITION = "allowDefinition";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_EVERYWHERE = "Everywhere";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINEONLY = "MachineOnly";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOAPPLICATION = "MachineToApplication";
protected const string KEYWORD_SECTION_ALLOWDEFINITION_MACHINETOWEBROOT = "MachineToWebRoot";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION = "allowExeDefinition";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOROAMING = "MachineToRoamingUser";
protected const string KEYWORD_SECTION_ALLOWEXEDEFINITION_MACHTOLOCAL = "MachineToLocalUser";
protected const string KEYWORD_SECTION_RESTARTONEXTERNALCHANGES = "restartOnExternalChanges";
protected const string KEYWORD_SECTION_REQUIREPERMISSION = "requirePermission";
protected const string KEYWORD_SECTIONGROUP = "sectionGroup";
protected const string KEYWORD_SECTIONGROUP_NAME = "name";
protected const string KEYWORD_SECTIONGROUP_TYPE = "type";
protected const string KEYWORD_REMOVE = "remove";
protected const string KEYWORD_CLEAR = "clear";
protected const string KEYWORD_LOCATION = "location";
protected const string KEYWORD_LOCATION_PATH = "path";
internal const string KEYWORD_LOCATION_ALLOWOVERRIDE = "allowOverride";
protected const string KEYWORD_LOCATION_INHERITINCHILDAPPLICATIONS = "inheritInChildApplications";
protected const string KEYWORD_CONFIGSOURCE = "configSource";
protected const string KEYWORD_XMLNS = "xmlns";
protected const string KEYWORD_CONFIG_BUILDER = "configBuilders";
internal const string KEYWORD_PROTECTION_PROVIDER = "configProtectionProvider";
protected const string FORMAT_NEWCONFIGFILE = "<?xml version=\"1.0\" encoding=\"{0}\"?>\r\n";
protected const string FORMAT_CONFIGURATION = "<configuration>\r\n";
protected const string FORMAT_CONFIGURATION_NAMESPACE = "<configuration xmlns=\"{0}\">\r\n";
protected const string FORMAT_CONFIGURATION_ENDELEMENT = "</configuration>";
internal const string KEYWORD_SECTION_OVERRIDEMODEDEFAULT = "overrideModeDefault";
internal const string KEYWORD_LOCATION_OVERRIDEMODE = "overrideMode";
internal const string KEYWORD_OVERRIDEMODE_INHERIT = "Inherit";
internal const string KEYWORD_OVERRIDEMODE_ALLOW = "Allow";
internal const string KEYWORD_OVERRIDEMODE_DENY = "Deny";
protected const string FORMAT_LOCATION_NOPATH = "<location {0} inheritInChildApplications=\"{1}\">\r\n";
protected const string FORMAT_LOCATION_PATH = "<location path=\"{2}\" {0} inheritInChildApplications=\"{1}\">\r\n";
protected const string FORMAT_LOCATION_ENDELEMENT = "</location>";
internal const string KEYWORD_LOCATION_OVERRIDEMODE_STRING = "{0}=\"{1}\"";
protected const string FORMAT_SECTION_CONFIGSOURCE = "<{0} configSource=\"{1}\" />";
protected const string FORMAT_CONFIGSOURCE_FILE = "<?xml version=\"1.0\" encoding=\"{0}\"?>\r\n";
protected const string FORMAT_SECTIONGROUP_ENDELEMENT = "</sectionGroup>";
// Class flags should only be used with the ClassFlags property.
protected const int ClassSupportsChangeNotifications = 0x00000001;
protected const int ClassSupportsRefresh = 0x00000002;
protected const int ClassSupportsImpersonation = 0x00000004;
protected const int ClassSupportsRestrictedPermissions = 0x00000008;
protected const int ClassSupportsKeepInputs = 0x00000010;
protected const int ClassSupportsDelayedInit = 0x00000020;
protected const int ClassIgnoreLocalErrors = 0x00000040;
// Flags to use with the _flags field.
protected const int ProtectedDataInitialized = 0x00000001;
protected const int Closed = 0x00000002;
protected const int PrefetchAll = 0x00000008;
protected const int IsAboveApplication = 0x00000020;
private const int ContextEvaluated = 0x00000080;
private const int IsLocationListResolved = 0x00000100;
protected const int NamespacePresentInFile = 0x00000200;
private const int RestrictedPermissionsResolved = 0x00000800;
protected const int IsTrusted = 0x00002000;
protected const int SupportsChangeNotifications = 0x00010000;
protected const int SupportsRefresh = 0x00020000;
protected const int SupportsPath = 0x00040000;
protected const int SupportsKeepInputs = 0x00080000;
protected const int SupportsLocation = 0x00100000;
// Flags for Mgmt Configuration Record
protected const int ForceLocationWritten = 0x01000000;
protected const int SuggestLocationRemoval = 0x02000000;
protected const int NamespacePresentCurrent = 0x04000000;
protected const int ConfigBuildersInitialized = 0x08000000;
internal const char ConfigPathSeparatorChar = '/';
internal const string ConfigPathSeparatorString = "/";
static internal readonly char[] ConfigPathSeparatorParams = new char[] {ConfigPathSeparatorChar};
private static volatile ConfigurationPermission s_unrestrictedConfigPermission; // cached ConfigurationPermission
protected SafeBitVector32 _flags; // state
protected BaseConfigurationRecord _parent; // parent record
protected Hashtable _children; // configName -> record
protected InternalConfigRoot _configRoot; // root of configuration
protected string _configName; // the last part of the config path
protected string _configPath; // the full config path
protected string _locationSubPath; // subPath for the config record when editing a location configuration
private ConfigRecordStreamInfo _configStreamInfo; // stream info for the config record
private object _configContext; // Context for config level
private ConfigurationBuildersSection _configBuilders; // section containing the general config builders
private ProtectedConfigurationSection _protectedConfig; // section containing the encryption providers
private PermissionSet _restrictedPermissions; // cached restricted permission set
private ConfigurationSchemaErrors _initErrors; // errors encountered during the parse of the configuration file
private BaseConfigurationRecord _initDelayedRoot; // root of delayed initialization
// Records information about <configSections> present in this web.config file.
// config key -> FactoryRecord
protected Hashtable _factoryRecords;
// Records information about sections that apply to this path,
// which may be found in this web.config file, in a parent through
// inheritance, or in a parent through <location>
// config key -> SectionRecord
protected Hashtable _sectionRecords;
// Records information about sections in a <location> directive
// that do not apply to this configPath (sections where path != ".")
protected ArrayList _locationSections;
// WOS 1955773: (Perf) 4,000 location sections in web.config file degrades working set
private static string s_appConfigPath;
// Comparer used in sorting IndirectInputs.
private static IComparer<SectionInput> s_indirectInputsComparer = new IndirectLocationInputComparer();
internal BaseConfigurationRecord() {
// not strictly necessary, but compiler spits out a warning without this initiailization
_flags = new SafeBitVector32();
}
// Class flags
protected abstract SimpleBitVector32 ClassFlags {get;}
// Create the factory that will evaluate configuration
protected abstract object CreateSectionFactory(FactoryRecord factoryRecord);
// Create the configuration object
protected abstract object CreateSection(bool inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, SectionInput sectionInput, object parentConfig, ConfigXmlReader reader);
// Use the parent result in creating the child
protected abstract object UseParentResult(string configKey, object parentResult, SectionRecord sectionRecord);
// Return the runtime object from GetSection
protected abstract object GetRuntimeObject(object result);
//
// IInternalConfigRecord methods
//
public string ConfigPath {
get {return _configPath;}
}
public string StreamName {
get {return ConfigStreamInfo.StreamName;}
}
public bool HasInitErrors {
get {
return _initErrors.HasErrors(ClassFlags[ClassIgnoreLocalErrors]);
}
}
public void ThrowIfInitErrors() {
ThrowIfParseErrors(_initErrors);
}
public object GetSection(string configKey) {
#if DBG
// On debug builds, the config system depends on system.diagnostics,
// so we must always return a valid result and never throw.
if (configKey == "system.diagnostics" && !ClassFlags[ClassIgnoreLocalErrors]) {
return GetSection(configKey, true, true);
}
else {
return GetSection(configKey, false, true);
}
#else
return GetSection(configKey, false, true);
#endif
}
public object GetLkgSection(string configKey) {
return GetSection(configKey, true, true);
}
public void RefreshSection(string configKey) {
_configRoot.ClearResult(this, configKey, true);
}
public void Remove() {
_configRoot.RemoveConfigRecord(this);
}
//
// end of IInternalConfigRecord methods
//
internal bool HasStream {
get { return ConfigStreamInfo.HasStream; }
}
// Determine which sections should be prefetched during the first scan.
private bool ShouldPrefetchRawXml(FactoryRecord factoryRecord) {
if (_flags[PrefetchAll])
return true;
switch (factoryRecord.ConfigKey) {
case BaseConfigurationRecord.RESERVED_SECTION_PROTECTED_CONFIGURATION:
case "system.diagnostics":
case "appSettings":
case "connectionStrings":
return true;
}
return Host.PrefetchSection(factoryRecord.Group, factoryRecord.Name);
}
protected IDisposable Impersonate() {
IDisposable context = null;
if (ClassFlags[ClassSupportsImpersonation]) {
context = Host.Impersonate();
}
if (context == null) {
context = EmptyImpersonationContext.GetStaticInstance();
}
return context;
}
internal PermissionSet GetRestrictedPermissions()
{
if (!_flags[RestrictedPermissionsResolved])
{
lock (this)
{
if (!_flags[RestrictedPermissionsResolved])
{
if (AppDomain.CurrentDomain.IsHomogenous)
{
// in a homogenous domain, just call PermitOnly() on the AppDomain's existing permission set
_restrictedPermissions = AppDomain.CurrentDomain.PermissionSet;
_flags[RestrictedPermissionsResolved] = true;
}
else
{
// in a non-homogenous domain, use Evidence to calculate the current security policy
PermissionSet restrictedPermissions;
bool isHostReady;
GetRestrictedPermissionsWithAssert(out restrictedPermissions, out isHostReady);
if (isHostReady)
{
_restrictedPermissions = restrictedPermissions;
_flags[RestrictedPermissionsResolved] = true;
}
}
// calling PermitOnly() on an unrestricted PermissionSet is a no-op
if (_restrictedPermissions != null && _restrictedPermissions.IsUnrestricted())
{
_restrictedPermissions = null;
}
}
}
}
return _restrictedPermissions;
}
// Getting the PermissionSet object is a FullTrust operation; we can Assert since our callers are careful not to leak it
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
private void GetRestrictedPermissionsWithAssert(out PermissionSet permissionSet, out bool isHostReady) {
Host.GetRestrictedPermissions(this, out permissionSet, out isHostReady);
}
internal void Init(
IInternalConfigRoot configRoot,
BaseConfigurationRecord parent,
string configPath,
string locationSubPath) {
_initErrors = new ConfigurationSchemaErrors();
//
// try/catch here is only for unexpected exceptions due to errors in
// our own code, as we always want the configuration record to be
// usable
//
try {
_configRoot = (InternalConfigRoot) configRoot;
_parent = parent;
_configPath = configPath;
_locationSubPath = locationSubPath;
_configName = ConfigPathUtility.GetName(configPath);
if (IsLocationConfig) {
_configStreamInfo = _parent.ConfigStreamInfo;
}
else {
_configStreamInfo = new ConfigRecordStreamInfo();
}
// no more initialization in case of root config
if (IsRootConfig)
return;
// determine what features we support
_flags[SupportsChangeNotifications] = ClassFlags[ClassSupportsChangeNotifications] && Host.SupportsChangeNotifications;
_flags[SupportsRefresh] = ClassFlags[ClassSupportsRefresh] && Host.SupportsRefresh;
_flags[SupportsKeepInputs] = ClassFlags[ClassSupportsKeepInputs] || _flags[SupportsRefresh];
_flags[SupportsPath] = Host.SupportsPath;
_flags[SupportsLocation] = Host.SupportsLocation;
// get static state based on the configPath
if (_flags[SupportsLocation]) {
_flags[IsAboveApplication] = Host.IsAboveApplication(_configPath);
}
_flags[IsTrusted] = Host.IsTrustedConfigPath(_configPath);
ArrayList locationSubPathInputs = null;
if (_flags[SupportsLocation]) {
//
// Treat location inputs from parent record
// as though they were bonafide sections in this record.
//
if (IsLocationConfig && _parent._locationSections != null) {
// Resolve paths and check for errors in location sections.
_parent.ResolveLocationSections();
int i = 0;
while (i < _parent._locationSections.Count) {
LocationSectionRecord locationSectionRecord = (LocationSectionRecord) _parent._locationSections[i];
if (!StringUtil.EqualsIgnoreCase(locationSectionRecord.SectionXmlInfo.TargetConfigPath, this.ConfigPath)) {
i++;
}
else {
// remove the locationSectionRecord from the list
_parent._locationSections.RemoveAt(i);
if (locationSubPathInputs == null) {
locationSubPathInputs = new ArrayList();
}
locationSubPathInputs.Add(locationSectionRecord);
}
}
}
// Handle indirect inputs for location config record.
if (IsLocationConfig && Host.IsLocationApplicable(_configPath)) {
Dictionary<string, List<SectionInput>> indirectLocationInputs = null;
BaseConfigurationRecord current = _parent;
// Note that the code will also go thru all parents, just like what we did
// with the location inputs later. But perf-wise it's okay not to merge the two loops
// because a Configuration object will contain at most one location config record.
while (!current.IsRootConfig) {
if (current._locationSections != null) {
current.ResolveLocationSections();
foreach (LocationSectionRecord locationSectionRecord in current._locationSections) {
//
// VSWhidbey 540184
// If we're initializing a location config record, we will also use those location
// tags that apply to the directories between the parent and the location config
// record's ConfigPath.
//
// This way, the result will contain all the inputs (we've parsed so far) which
// affect the path specified by locationSubPath.
///
// To look for this kind of input, make sure that:
// 1. We are creating a location config
// 2. The location tag's target path lies between parent's config path and ConfigPath
// 2.1: ConfigPath must be a child of the location tag's target path
// 2.2: The target path must be a child of parent's config path
//
// One example of why we need 2.2:
// The root web.config has a location tag with path="1", and we open a configuration
// at "1" with locationSubPath="sub". If we don't have 2.2, then we will incorrectly set
// addInput to true for this location tag. It's incorrect because that location tag
// is already used by configRecord at level "1".
//
// 3. The location tag shouldn't be skipped due to inheritInChildApplications setting
//
if (
// Check #1
IsLocationConfig &&
// Check #2.1
UrlPath.IsSubpath(locationSectionRecord.SectionXmlInfo.TargetConfigPath, ConfigPath) &&
// Check #2.2
UrlPath.IsSubpath(parent.ConfigPath, locationSectionRecord.SectionXmlInfo.TargetConfigPath) &&
// Check #3
!ShouldSkipDueToInheritInChildApplications(locationSectionRecord.SectionXmlInfo.SkipInChildApps, locationSectionRecord.SectionXmlInfo.TargetConfigPath)
) {
//
// In order to separate these kinds of input from "file inputs" and "location inputs"
// we introduce a new kind of input called the "indirect location inputs".
//
// First add all indirect inputs per configKey to a local list.
// We will sort all lists after the while loop.
if (indirectLocationInputs == null) {
indirectLocationInputs = new Dictionary<string, List<SectionInput>>(1);
}
string configKey = locationSectionRecord.SectionXmlInfo.ConfigKey;
if (!((IDictionary)indirectLocationInputs).Contains(configKey)) {
indirectLocationInputs.Add(configKey, new List<SectionInput>(1));
}
indirectLocationInputs[configKey].Add(
new SectionInput(locationSectionRecord.SectionXmlInfo,
locationSectionRecord.ErrorsList));
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
current = current._parent;
}
if (indirectLocationInputs != null) {
// Add indirect inputs per configKey
foreach(KeyValuePair<string, List<SectionInput>> keyValuePair in indirectLocationInputs) {
List<SectionInput> inputsPerConfigKey = keyValuePair.Value;
string configKey = keyValuePair.Key;
// We have to sort the indirect inputs
// 1. First by the location tag's target config path, and if they're the same,
// 2. Then by the location tag's definition config path.
inputsPerConfigKey.Sort(s_indirectInputsComparer);
// Add them to the section record.
// In the sorted list, the closest parent is at the beginning of the
// list, which is what we'll add first.
SectionRecord sectionRecord = EnsureSectionRecord(configKey, true);
Debug.Assert(inputsPerConfigKey.Count > 0, "We won't get here unless we have inputs.");
foreach(SectionInput sectionInput in inputsPerConfigKey) {
sectionRecord.AddIndirectLocationInput(sectionInput);
}
DebugValidateIndirectInputs(sectionRecord);
}
}
}
//
// Add location inputs that apply to this path, all the way up the parent hierarchy.
//
if (Host.IsLocationApplicable(_configPath)) {
BaseConfigurationRecord current = _parent;
while (!current.IsRootConfig) {
if (current._locationSections != null) {
current.ResolveLocationSections();
foreach (LocationSectionRecord locationSectionRecord in current._locationSections) {
// We use the location tag input if:
// - The path matches, and
// - It's not skipped due to inheritInChildApplications setting.
if (StringUtil.EqualsIgnoreCase(locationSectionRecord.SectionXmlInfo.TargetConfigPath, this._configPath) &&
!ShouldSkipDueToInheritInChildApplications(locationSectionRecord.SectionXmlInfo.SkipInChildApps)) {
// add the location input for this section
SectionRecord sectionRecord = EnsureSectionRecord(locationSectionRecord.ConfigKey, true);
SectionInput sectionInput = new SectionInput(
locationSectionRecord.SectionXmlInfo, locationSectionRecord.ErrorsList);
sectionRecord.AddLocationInput(sectionInput);
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
current = current._parent;
}
}
}
if (!IsLocationConfig) {
//
// If config file exists, open it and parse it once so we can
// find what to evaluate later.
//
InitConfigFromFile();
}
else {
// Add location sections for this record as bonafide sections.
if (locationSubPathInputs != null) {
foreach (LocationSectionRecord locationSectionRecord in locationSubPathInputs) {
// add the file input
SectionRecord sectionRecord = EnsureSectionRecord(locationSectionRecord.ConfigKey, true);
SectionInput sectionInput = new SectionInput(locationSectionRecord.SectionXmlInfo, locationSectionRecord.ErrorsList);
sectionRecord.AddFileInput(sectionInput);
// copy the initialization errors to the record
if (locationSectionRecord.HasErrors) {
this._initErrors.AddSavedLocalErrors(locationSectionRecord.Errors);
}
}
}
}
}
//
// Capture all exceptions and include them in initialization errors.
//
catch (Exception e) {
string streamname = (ConfigStreamInfo != null) ? ConfigStreamInfo.StreamName : null;
_initErrors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, streamname, 0),
ExceptionAction.Global);
}
}
// InitConfigFromFile
//
// Init the Config From the File.
//
private void InitConfigFromFile() {
bool implicitSectionsAdded = false;
try {
// If initialization should be delayed, do not read the file.
if (ClassFlags[ClassSupportsDelayedInit] && Host.IsInitDelayed(this)) {
// determine the root of delayed initialization
if (_parent._initDelayedRoot == null) {
_initDelayedRoot = this;
}
else {
_initDelayedRoot = _parent._initDelayedRoot;
}
}
else {
//
// This parent of a record that is not initDelayed must also
// not be initDelayed.
//
Debug.Assert(!_parent.IsInitDelayed, "!_parent.IsInitDelayed");
using (Impersonate()) {
//
// Get the stream name. Note that this may be an expensive operation
// for the client configuration host, which is why it comes after the
// check for delayed init.
//
ConfigStreamInfo.StreamName = Host.GetStreamName(_configPath);
if (!String.IsNullOrEmpty(ConfigStreamInfo.StreamName)) {
// Lets listen to the stream
ConfigStreamInfo.StreamVersion = MonitorStream(null, null, ConfigStreamInfo.StreamName);
using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) {
if (stream == null) {
// There is no stream to load from
return;
}
ConfigStreamInfo.HasStream = true;
// Determine whether or not to prefetch.
_flags[PrefetchAll] = Host.PrefetchAll(_configPath, ConfigStreamInfo.StreamName);
using (XmlUtil xmlUtil = new XmlUtil(stream, ConfigStreamInfo.StreamName, true, _initErrors)) {
ConfigStreamInfo.StreamEncoding = xmlUtil.Reader.Encoding;
// Read the factories
Hashtable factoryList = ScanFactories(xmlUtil);
_factoryRecords = factoryList;
// Add implicit sections before scanning sections
AddImplicitSections(null);
implicitSectionsAdded = true;
// Read the sections themselves
if (xmlUtil.Reader.Depth == 1) {
ScanSections(xmlUtil);
}
}
}
}
}
}
}
//
// Capture all exceptions and include them in _initErrors so execution in Init can continue.
//
catch (XmlException e) {
//
// Treat invalid XML as unrecoverable by replacing all errors with the XML error.
//
_initErrors.SetSingleGlobalError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, 0));
}
catch (Exception e) {
_initErrors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, 0),
ExceptionAction.Global);
}
//
// If there are global errors that make all input invalid,
// reset our state so that inherited configuration can still be used,
// including location sections that apply to this file.
//
if (_initErrors.HasGlobalErrors) {
//
// Parsing of a section may have been in progress when the exception
// was thrown, so clear any accumulated local errors.
//
_initErrors.ResetLocalErrors();
//
// Stop monitoring any configSource streams, but still continue
// to monitor the main config file if it was successfully monitored.
//
HybridDictionary streamInfos = null;
lock (this) {
if (ConfigStreamInfo.HasStreamInfos) {
streamInfos = ConfigStreamInfo.StreamInfos;
ConfigStreamInfo.ClearStreamInfos();
if (!String.IsNullOrEmpty(ConfigStreamInfo.StreamName)) {
StreamInfo fileStreamInfo = (StreamInfo) streamInfos[ConfigStreamInfo.StreamName];
// add this file's streaminfo to the now empty list
if (fileStreamInfo != null) {
streamInfos.Remove(ConfigStreamInfo.StreamName);
ConfigStreamInfo.StreamInfos.Add(ConfigStreamInfo.StreamName, fileStreamInfo);
}
}
}
}
// Stop monitoring streams outside the lock, to prevent deadlock.
if (streamInfos != null) {
foreach (StreamInfo streamInfo in streamInfos.Values) {
if (streamInfo.IsMonitored) {
Host.StopMonitoringStreamForChanges(streamInfo.StreamName, ConfigStreamInfo.CallbackDelegate);
}
}
}
// Remove file input
if (_sectionRecords != null) {
List<SectionRecord> removes = null;
foreach (SectionRecord sectionRecord in _sectionRecords.Values) {
Debug.Assert(!sectionRecord.HasIndirectLocationInputs,
"Don't expect to have any IndirectLocationInputs because location config record shouldn't call InitConfigFromFile");
if (sectionRecord.HasLocationInputs) {
// Remove any file input
sectionRecord.RemoveFileInput();
}
else {
// Remove the entire section record
if (removes == null) {
removes = new List<SectionRecord>();
}
removes.Add(sectionRecord);
}
}
if (removes != null) {
foreach (SectionRecord sectionRecord in removes) {
_sectionRecords.Remove(sectionRecord.ConfigKey);
}
}
}
// Remove all location section input defined here
if (_locationSections != null) {
_locationSections.Clear();
}
// Remove all factory records
if (_factoryRecords != null) {
_factoryRecords.Clear();
}
}
if (!implicitSectionsAdded) {
// Always add implicit sections no matter we have a file or not.
AddImplicitSections(null);
}
}
private bool IsInitDelayed {
get {
return _initDelayedRoot != null;
}
}
// RefreshFactoryRecord
//
// Refresh the Factory Record for a particular section.
//
private void RefreshFactoryRecord(string configKey) {
Hashtable factoryList = null;
FactoryRecord factoryRecord = null;
ConfigurationSchemaErrors errors;
errors = new ConfigurationSchemaErrors();
// Get Updated Factory List from File
int lineNumber = 0;
try {
using (Impersonate()) {
using (Stream stream = Host.OpenStreamForRead(ConfigStreamInfo.StreamName)) {
if (stream != null) {
ConfigStreamInfo.HasStream = true;
using (XmlUtil xmlUtil = new XmlUtil(stream, ConfigStreamInfo.StreamName, true, errors)) {
try {
factoryList = ScanFactories(xmlUtil);
ThrowIfParseErrors(xmlUtil.SchemaErrors);
}
catch {
lineNumber = xmlUtil.LineNumber;
throw;
}
}
}
}
}
// Add implicit sections to the factory list
if (factoryList == null) {
// But if factoryList isn't found in this config, we still try to
// add implicit sections to an empty factoryList.
factoryList = new Hashtable();
}
AddImplicitSections(factoryList);
if (factoryList != null) {
factoryRecord = (FactoryRecord) factoryList[configKey];
}
}
//
// Guarantee that exceptions contain the name of the stream and an approximate line number if available.
//
// And don't allow frames up the stack to run exception filters while impersonated.
catch (Exception e) {
errors.AddError(
ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_error_loading_XML_file), e, ConfigStreamInfo.StreamName, lineNumber),
ExceptionAction.Global);
}
// Set/Add/Remove Record
// Note that the _factoryRecords hashtable is protected by the hierarchy lock.
if (factoryRecord != null || HasFactoryRecords) {
EnsureFactories()[configKey] = factoryRecord;
}
// Throw accumulated errors
ThrowIfParseErrors(errors);
}
internal IInternalConfigHost Host {
get {return _configRoot.Host;}
}
internal IInternalConfigurationBuilderHost ConfigBuilderHost {
get { return _configRoot.ConfigBuilderHost; }
}
internal BaseConfigurationRecord Parent {
get {return _parent;}
}
internal bool IsRootConfig {
get {return _parent == null;}
}
internal bool IsMachineConfig {
get {return _parent == _configRoot.RootConfigRecord;}
}
internal string LocationSubPath {
get {return _locationSubPath;}
}
internal bool IsLocationConfig {
get {return _locationSubPath != null;}
}
protected ConfigRecordStreamInfo ConfigStreamInfo {
get {
if (IsLocationConfig) {
return _parent._configStreamInfo;
}
else {
return _configStreamInfo;
}
}
}
private object GetSection(string configKey, bool getLkg, bool checkPermission) {
object result;
object resultRuntimeObject;
//
// Note that GetSectionRecursive may invalidate this record,
// so there should be no further references to 'this' after the call.
//
GetSectionRecursive(
configKey, getLkg, checkPermission, true /* getRuntimeObject */, true /* requestIsHere */,
out result, out resultRuntimeObject);
return resultRuntimeObject;
}
private void GetSectionRecursive(
string configKey, bool getLkg, bool checkPermission, bool getRuntimeObject, bool requestIsHere,
out object result, out object resultRuntimeObject) {
result = null;
resultRuntimeObject = null;
#if DBG
Debug.Assert(requestIsHere || !checkPermission, "requestIsHere || !checkPermission");
if (getLkg) {
Debug.Assert(getRuntimeObject == true, "getRuntimeObject == true");
Debug.Assert(requestIsHere == true, "requestIsHere == true");
}
#endif
//
// Store results in temporary variables, because we don't want to return
// results if an exception is thrown by CheckPermissionAllowed.
//
object tmpResult = null;
object tmpResultRuntimeObject = null;
bool requirePermission = true;
bool isResultTrustedWithoutAptca = true;
// Throw errors from initial parse, if any.
if (!getLkg) {
ThrowIfInitErrors();
}
//
// check for a cached result
//
bool hasResult = false;
SectionRecord sectionRecord = GetSectionRecord(configKey, getLkg);
if (sectionRecord != null && sectionRecord.HasResult) {
// Results should never be stored if the section has errors.
Debug.Assert(!sectionRecord.HasErrors, "!sectionRecord.HasErrors");
// Create the runtime object if requested and does not yet exist.
if (getRuntimeObject && !sectionRecord.HasResultRuntimeObject) {
try {
sectionRecord.ResultRuntimeObject = GetRuntimeObject(sectionRecord.Result);
}
catch {
//
// Ignore the error if we are attempting to retreive
// the last known good configuration.
//
if (!getLkg) {
throw;
}
}
}
// Get the cached result.
if (!getRuntimeObject || sectionRecord.HasResultRuntimeObject) {
requirePermission = sectionRecord.RequirePermission;
isResultTrustedWithoutAptca = sectionRecord.IsResultTrustedWithoutAptca;
tmpResult = sectionRecord.Result;
if (getRuntimeObject) {
tmpResultRuntimeObject = sectionRecord.ResultRuntimeObject;
}
hasResult = true;
}
}
//
// If there is no cached result, get the parent's section,
// then merge it with our own input if we have any.
//
if (!hasResult) {
FactoryRecord factoryRecord = null;
bool hasInput = (sectionRecord != null && sectionRecord.HasInput);
//
// We want to cache results in a section record if:
// - The request is made at this level, and so is likely to be
// made here again.
// OR
// - The section has input, in which case we want to
// avoid evaluating the same input multiple times.
//
bool cacheResults = (requestIsHere || hasInput);
bool isRootDeclaration;
try {
//
// We need to get a factory record to:
// - Check whether the caller has permission to access a section.
// - Determine if this is the root declaration of a config section,
// and thus the termination point for recursion.
// - Get a factory that can create a configuration section.
//
// Since most factories will be declared in machine.config and not in
// child config files, we do not optimize for checking whether a
// factory record is the root declaration, as the calculation at
// machine.config is trivial.
//
// It WILL be common in web scenarios for there to be
// deep hierarchies of config files, most of which have
// sparse input. Therefore we do not want to retreive a
// factory record if it is not necessary to do so, as
// it would always lead to an order N-squared operation,
// where N is the depth of the config hierarchy.
//
// We can skip the reteival of a factory record if:
// - This is the recursive call to GetSectionRecursive,
// AND
// - There is no section input at this level,
// AND
// - No factory is declared at this level.
//
// In this case, we'll simply continue the recursion to our parent.
//
if (requestIsHere) {
//
// Ensure that we have a valid factory record and a valid factory
// for creating sections when a request for a section is first
// made.
//
factoryRecord = FindAndEnsureFactoryRecord(configKey, out isRootDeclaration);
//