ConfigurationSettings.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. //
  2. // System.Configuration.ConfigurationSettings.cs
  3. //
  4. // Author:
  5. // Christopher Podurgiel ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Eric Lindvall ([email protected])
  8. //
  9. // (c) Christopher Podurgiel
  10. // (c) 2002 Ximian, Inc. (http://www.ximian.com)
  11. // (c) 2003 Novell, Inc. (http://www.novell.com)
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. #if CONFIGURATION_DEP
  34. extern alias PrebuiltSystem;
  35. using NameValueCollection = PrebuiltSystem.System.Collections.Specialized.NameValueCollection;
  36. #endif
  37. using System;
  38. using System.Collections;
  39. using System.Collections.Specialized;
  40. using System.IO;
  41. using System.Runtime.CompilerServices;
  42. using System.Security.Permissions;
  43. #if (XML_DEP)
  44. using System.Xml;
  45. using System.Xml.XPath;
  46. #endif
  47. #if TARGET_JVM
  48. using vmw.common;
  49. using [email protected];
  50. #endif
  51. namespace System.Configuration
  52. {
  53. public sealed class ConfigurationSettings
  54. {
  55. #if !TARGET_JVM
  56. static IConfigurationSystem config = DefaultConfig.GetInstance ();
  57. #else
  58. static IConfigurationSystem config {
  59. get {
  60. IConfigurationSystem conf = (IConfigurationSystem) AppDomain.CurrentDomain.GetData ("ConfigurationSettings.Config");
  61. if (conf == null) {
  62. conf = DefaultConfig.GetInstance ();
  63. AppDomain.CurrentDomain.SetData ("ConfigurationSettings.Config", conf);
  64. }
  65. return conf;
  66. }
  67. set {
  68. AppDomain.CurrentDomain.SetData ("ConfigurationSettings.Config", value);
  69. }
  70. }
  71. #endif
  72. static object lockobj = new object ();
  73. private ConfigurationSettings ()
  74. {
  75. }
  76. #if NET_2_0
  77. [Obsolete ("This method is obsolete, it has been replaced by System.Configuration!System.Configuration.ConfigurationManager.GetSection")]
  78. #endif
  79. public static object GetConfig (string sectionName)
  80. {
  81. return config.GetConfig (sectionName);
  82. }
  83. #if NET_2_0
  84. [Obsolete ("This property is obsolete. Please use System.Configuration.ConfigurationManager.AppSettings")]
  85. #endif
  86. public static NameValueCollection AppSettings
  87. {
  88. get {
  89. #if NET_2_0 && CONFIGURATION_DEP
  90. object appSettings = ConfigurationManager.GetSection ("appSettings");
  91. #else
  92. object appSettings = GetConfig ("appSettings");
  93. #endif
  94. if (appSettings == null)
  95. appSettings = new NameValueCollection ();
  96. return (NameValueCollection) appSettings;
  97. }
  98. }
  99. // Invoked from System.Web, disable warning
  100. internal static IConfigurationSystem ChangeConfigurationSystem (IConfigurationSystem newSystem)
  101. {
  102. if (newSystem == null)
  103. throw new ArgumentNullException ("newSystem");
  104. lock (lockobj) {
  105. IConfigurationSystem old = config;
  106. config = newSystem;
  107. return old;
  108. }
  109. }
  110. }
  111. //
  112. // class DefaultConfig: read configuration from machine.config file and application
  113. // config file if available.
  114. //
  115. class DefaultConfig : IConfigurationSystem
  116. {
  117. #if !TARGET_JVM
  118. static readonly DefaultConfig instance = new DefaultConfig ();
  119. #else
  120. static DefaultConfig instance {
  121. get {
  122. DefaultConfig conf = (DefaultConfig) AppDomain.CurrentDomain.GetData ("DefaultConfig.instance");
  123. if (conf == null) {
  124. conf = new DefaultConfig ();
  125. AppDomain.CurrentDomain.SetData ("DefaultConfig.instance", conf);
  126. }
  127. return conf;
  128. }
  129. set {
  130. AppDomain.CurrentDomain.SetData ("DefaultConfig.instance", value);
  131. }
  132. }
  133. #endif
  134. ConfigurationData config;
  135. private DefaultConfig ()
  136. {
  137. }
  138. public static DefaultConfig GetInstance ()
  139. {
  140. return instance;
  141. }
  142. #if NET_2_0
  143. [Obsolete ("This method is obsolete. Please use System.Configuration.ConfigurationManager.GetConfig")]
  144. #endif
  145. public object GetConfig (string sectionName)
  146. {
  147. Init ();
  148. return config.GetConfig (sectionName);
  149. }
  150. public void Init ()
  151. {
  152. lock (this) {
  153. if (config != null)
  154. return;
  155. ConfigurationData data = new ConfigurationData ();
  156. if (!data.Load (GetMachineConfigPath ()))
  157. throw new ConfigurationException ("Cannot find " + GetMachineConfigPath ());
  158. string appfile = GetAppConfigPath ();
  159. if (appfile == null) {
  160. config = data;
  161. return;
  162. }
  163. ConfigurationData appData = new ConfigurationData (data);
  164. if (appData.Load (appfile))
  165. config = appData;
  166. else
  167. config = data;
  168. }
  169. }
  170. #if TARGET_JVM
  171. internal static string GetMachineConfigPath ()
  172. {
  173. return "/machine.config";
  174. }
  175. #else
  176. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  177. extern private static string get_machine_config_path ();
  178. internal static string GetMachineConfigPath ()
  179. {
  180. return get_machine_config_path ();
  181. }
  182. #endif
  183. private static string GetAppConfigPath ()
  184. {
  185. AppDomainSetup currentInfo = AppDomain.CurrentDomain.SetupInformation;
  186. string configFile = currentInfo.ConfigurationFile;
  187. if (configFile == null || configFile.Length == 0)
  188. return null;
  189. return configFile;
  190. }
  191. }
  192. enum AllowDefinition
  193. {
  194. Everywhere,
  195. MachineOnly,
  196. MachineToApplication
  197. }
  198. class SectionData
  199. {
  200. public readonly string SectionName;
  201. public readonly string TypeName;
  202. public readonly bool AllowLocation;
  203. public readonly AllowDefinition AllowDefinition;
  204. public string FileName;
  205. public readonly bool RequirePermission;
  206. public SectionData (string sectionName, string typeName,
  207. bool allowLocation, AllowDefinition allowDefinition, bool requirePermission)
  208. {
  209. SectionName = sectionName;
  210. TypeName = typeName;
  211. AllowLocation = allowLocation;
  212. AllowDefinition = allowDefinition;
  213. RequirePermission = requirePermission;
  214. }
  215. }
  216. class ConfigurationData
  217. {
  218. ConfigurationData parent;
  219. Hashtable factories;
  220. static object removedMark = new object ();
  221. static object emptyMark = new object ();
  222. #if (XML_DEP)
  223. Hashtable pending;
  224. string fileName;
  225. static object groupMark = new object ();
  226. #endif
  227. Hashtable cache;
  228. Hashtable FileCache {
  229. get {
  230. if (cache != null)
  231. return cache;
  232. cache = new Hashtable ();
  233. return cache;
  234. }
  235. }
  236. public ConfigurationData () : this (null)
  237. {
  238. }
  239. public ConfigurationData (ConfigurationData parent)
  240. {
  241. this.parent = (parent == this) ? null : parent;
  242. factories = new Hashtable ();
  243. }
  244. // SECURITY-FIXME: limit this with an imperative assert for reading the specific file
  245. [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
  246. public bool Load (string fileName)
  247. {
  248. #if (XML_DEP)
  249. this.fileName = fileName;
  250. if (fileName == null
  251. #if !TARGET_JVM
  252. || !File.Exists (fileName)
  253. #endif
  254. )
  255. return false;
  256. XmlTextReader reader = null;
  257. try {
  258. #if !TARGET_JVM
  259. FileStream fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  260. #else
  261. Stream fs = (Stream) vmw.common.IOUtils.getStream (fileName);
  262. //patch for machine.config
  263. if (fs == null && fileName.EndsWith ("machine.config")) {
  264. fs = (Stream) IOUtils.getStreamForGHConfigs (fileName);
  265. }
  266. if (fs == null) {
  267. return false;
  268. }
  269. #endif
  270. reader = new XmlTextReader (fs);
  271. InitRead (reader);
  272. ReadConfigFile (reader);
  273. } catch (ConfigurationException) {
  274. throw;
  275. } catch (Exception e) {
  276. throw new ConfigurationException ("Error reading " + fileName, e);
  277. } finally {
  278. if (reader != null)
  279. reader.Close();
  280. }
  281. #endif
  282. return true;
  283. }
  284. object GetHandler (string sectionName)
  285. {
  286. lock (factories) {
  287. object o = factories [sectionName];
  288. if (o == null || o == removedMark) {
  289. if (parent != null)
  290. return parent.GetHandler (sectionName);
  291. return null;
  292. }
  293. if (o is IConfigurationSectionHandler)
  294. return (IConfigurationSectionHandler) o;
  295. o = CreateNewHandler (sectionName, (SectionData) o);
  296. factories [sectionName] = o;
  297. return o;
  298. }
  299. }
  300. object CreateNewHandler (string sectionName, SectionData section)
  301. {
  302. Type t = Type.GetType (section.TypeName);
  303. if (t == null)
  304. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  305. #if false
  306. Type iconfig = typeof (IConfigurationSectionHandler);
  307. if (!iconfig.IsAssignableFrom (t))
  308. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  309. #endif
  310. object o = Activator.CreateInstance (t, true);
  311. if (o == null)
  312. throw new ConfigurationException ("Cannot get instance for " + t);
  313. return o;
  314. }
  315. #if (XML_DEP)
  316. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  317. {
  318. if (++i >= sectionPath.Length)
  319. return doc;
  320. if (doc.DocumentElement == null)
  321. return null;
  322. XmlNode node = doc.DocumentElement.FirstChild;
  323. while (node != null) {
  324. if (node.Name == sectionPath [i]) {
  325. ConfigXmlDocument result = new ConfigXmlDocument ();
  326. result.Load (new StringReader (node.OuterXml));
  327. return GetInnerDoc (result, i, sectionPath);
  328. }
  329. node = node.NextSibling;
  330. }
  331. return null;
  332. }
  333. XmlDocument GetDocumentForSection (string sectionName)
  334. {
  335. ConfigXmlDocument doc = new ConfigXmlDocument ();
  336. if (pending == null)
  337. return doc;
  338. string [] sectionPath = sectionName.Split ('/');
  339. string outerxml = pending [sectionPath [0]] as string;
  340. if (outerxml == null)
  341. return doc;
  342. StringReader reader = new StringReader (outerxml);
  343. XmlTextReader rd = new XmlTextReader (reader);
  344. rd.MoveToContent ();
  345. doc.LoadSingleElement (fileName, rd);
  346. return GetInnerDoc (doc, 0, sectionPath);
  347. }
  348. object GetConfigInternal (string sectionName)
  349. {
  350. object handler = GetHandler (sectionName);
  351. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  352. if (iconf == null)
  353. return handler;
  354. object parentConfig = null;
  355. if (parent != null)
  356. parentConfig = parent.GetConfig (sectionName);
  357. XmlDocument doc = GetDocumentForSection (sectionName);
  358. if (doc == null || doc.DocumentElement == null)
  359. return parentConfig;
  360. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  361. }
  362. #else
  363. object GetConfigInternal (string sectionName)
  364. {
  365. return null;
  366. }
  367. #endif
  368. public object GetConfig (string sectionName)
  369. {
  370. object config;
  371. lock (this) {
  372. config = this.FileCache [sectionName];
  373. }
  374. if (config == emptyMark)
  375. return null;
  376. if (config != null)
  377. return config;
  378. lock (this) {
  379. config = GetConfigInternal (sectionName);
  380. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  381. }
  382. return config;
  383. }
  384. private object LookForFactory (string key)
  385. {
  386. object o = factories [key];
  387. if (o != null)
  388. return o;
  389. if (parent != null)
  390. return parent.LookForFactory (key);
  391. return null;
  392. }
  393. #if (XML_DEP)
  394. private void InitRead (XmlTextReader reader)
  395. {
  396. reader.MoveToContent ();
  397. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  398. ThrowException ("Configuration file does not have a valid root element", reader);
  399. if (reader.HasAttributes)
  400. ThrowException ("Unrecognized attribute in root element", reader);
  401. MoveToNextElement (reader);
  402. }
  403. // FIXME: this approach is not always safe and likely to cause bugs.
  404. private void MoveToNextElement (XmlTextReader reader)
  405. {
  406. while (reader.Read ()) {
  407. XmlNodeType ntype = reader.NodeType;
  408. if (ntype == XmlNodeType.Element)
  409. return;
  410. if (ntype != XmlNodeType.Whitespace &&
  411. ntype != XmlNodeType.Comment &&
  412. ntype != XmlNodeType.SignificantWhitespace &&
  413. ntype != XmlNodeType.EndElement)
  414. ThrowException ("Unrecognized element", reader);
  415. }
  416. }
  417. private void ReadSection (XmlTextReader reader, string sectionName)
  418. {
  419. string attName;
  420. string nameValue = null;
  421. string typeValue = null;
  422. string allowLoc = null, allowDef = null;
  423. bool requirePermission = false;
  424. string requirePer = null;
  425. bool allowLocation = true;
  426. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  427. while (reader.MoveToNextAttribute ()) {
  428. attName = reader.Name;
  429. if (attName == null)
  430. continue;
  431. if (attName == "allowLocation") {
  432. if (allowLoc != null)
  433. ThrowException ("Duplicated allowLocation attribute.", reader);
  434. allowLoc = reader.Value;
  435. allowLocation = (allowLoc == "true");
  436. if (!allowLocation && allowLoc != "false")
  437. ThrowException ("Invalid attribute value", reader);
  438. continue;
  439. }
  440. if (attName == "requirePermission") {
  441. if (requirePer != null)
  442. ThrowException ("Duplicated requirePermission attribute.", reader);
  443. requirePer = reader.Value;
  444. requirePermission = (requirePer == "true");
  445. if (!requirePermission && requirePer != "false")
  446. ThrowException ("Invalid attribute value", reader);
  447. continue;
  448. }
  449. if (attName == "allowDefinition") {
  450. if (allowDef != null)
  451. ThrowException ("Duplicated allowDefinition attribute.", reader);
  452. allowDef = reader.Value;
  453. try {
  454. allowDefinition = (AllowDefinition) Enum.Parse (
  455. typeof (AllowDefinition), allowDef);
  456. } catch {
  457. ThrowException ("Invalid attribute value", reader);
  458. }
  459. continue;
  460. }
  461. if (attName == "type") {
  462. if (typeValue != null)
  463. ThrowException ("Duplicated type attribute.", reader);
  464. typeValue = reader.Value;
  465. continue;
  466. }
  467. if (attName == "name") {
  468. if (nameValue != null)
  469. ThrowException ("Duplicated name attribute.", reader);
  470. nameValue = reader.Value;
  471. if (nameValue == "location")
  472. ThrowException ("location is a reserved section name", reader);
  473. continue;
  474. }
  475. ThrowException ("Unrecognized attribute.", reader);
  476. }
  477. if (nameValue == null || typeValue == null)
  478. ThrowException ("Required attribute missing", reader);
  479. if (sectionName != null)
  480. nameValue = sectionName + '/' + nameValue;
  481. reader.MoveToElement();
  482. object o = LookForFactory (nameValue);
  483. if (o != null && o != removedMark)
  484. ThrowException ("Already have a factory for " + nameValue, reader);
  485. SectionData section = new SectionData (nameValue, typeValue, allowLocation,
  486. allowDefinition, requirePermission);
  487. section.FileName = fileName;
  488. factories [nameValue] = section;
  489. MoveToNextElement (reader);
  490. }
  491. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  492. {
  493. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  494. ThrowException ("Unrecognized attribute.", reader);
  495. string removeValue = reader.Value;
  496. if (removeValue == null || removeValue.Length == 0)
  497. ThrowException ("Empty name to remove", reader);
  498. reader.MoveToElement ();
  499. if (sectionName != null)
  500. removeValue = sectionName + '/' + removeValue;
  501. object o = LookForFactory (removeValue);
  502. if (o != null && o == removedMark)
  503. ThrowException ("No factory for " + removeValue, reader);
  504. factories [removeValue] = removedMark;
  505. MoveToNextElement (reader);
  506. }
  507. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  508. {
  509. if (!reader.MoveToNextAttribute ())
  510. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  511. string value = null;
  512. do {
  513. if (reader.Name == "name") {
  514. if (value != null)
  515. ThrowException ("Duplicate 'name' attribute.", reader);
  516. value = reader.Value;
  517. }
  518. else
  519. #if NET_2_0
  520. if (reader.Name != "type")
  521. #endif
  522. ThrowException ("Unrecognized attribute.", reader);
  523. } while (reader.MoveToNextAttribute ());
  524. if (value == null)
  525. ThrowException ("No 'name' attribute.", reader);
  526. if (value == "location")
  527. ThrowException ("location is a reserved section name", reader);
  528. if (configSection != null)
  529. value = configSection + '/' + value;
  530. object o = LookForFactory (value);
  531. if (o != null && o != removedMark && o != groupMark)
  532. ThrowException ("Already have a factory for " + value, reader);
  533. factories [value] = groupMark;
  534. if (reader.IsEmptyElement) {
  535. reader.Skip ();
  536. reader.MoveToContent ();
  537. } else {
  538. reader.Read ();
  539. reader.MoveToContent ();
  540. if (reader.NodeType != XmlNodeType.EndElement)
  541. ReadSections (reader, value);
  542. else
  543. reader.Read ();
  544. reader.MoveToContent ();
  545. }
  546. }
  547. private void ReadSections (XmlTextReader reader, string configSection)
  548. {
  549. int depth = reader.Depth;
  550. while (reader.Depth == depth) {
  551. string name = reader.Name;
  552. if (name == "section") {
  553. ReadSection (reader, configSection);
  554. continue;
  555. }
  556. if (name == "remove") {
  557. ReadRemoveSection (reader, configSection);
  558. continue;
  559. }
  560. if (name == "clear") {
  561. if (reader.HasAttributes)
  562. ThrowException ("Unrecognized attribute.", reader);
  563. factories.Clear ();
  564. MoveToNextElement (reader);
  565. continue;
  566. }
  567. if (name == "sectionGroup") {
  568. ReadSectionGroup (reader, configSection);
  569. continue;
  570. }
  571. ThrowException ("Unrecognized element: " + reader.Name, reader);
  572. }
  573. }
  574. void StorePending (string name, XmlTextReader reader)
  575. {
  576. if (pending == null)
  577. pending = new Hashtable ();
  578. pending [name] = reader.ReadOuterXml ();
  579. }
  580. private void ReadConfigFile (XmlTextReader reader)
  581. {
  582. int depth = reader.Depth;
  583. while (!reader.EOF && reader.Depth == depth) {
  584. string name = reader.Name;
  585. if (name == "configSections") {
  586. if (reader.HasAttributes)
  587. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  588. MoveToNextElement (reader);
  589. if (reader.Depth > depth)
  590. ReadSections (reader, null);
  591. } else if (name != null && name != "") {
  592. StorePending (name, reader);
  593. MoveToNextElement (reader);
  594. } else {
  595. MoveToNextElement (reader);
  596. }
  597. }
  598. }
  599. private void ThrowException (string text, XmlTextReader reader)
  600. {
  601. throw new ConfigurationException (text, fileName, reader.LineNumber);
  602. }
  603. #endif
  604. }
  605. }