WebConfigurationSettings.cs 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. //
  2. // System.Configuration.WebConfigurationSettings.cs
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (c) 2003,2004 Novell, Inc. (http://www.novell.com)
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Configuration;
  31. using System.Collections;
  32. using System.IO;
  33. using System.Reflection;
  34. using System.Runtime.Remoting;
  35. using System.Web.Util;
  36. using System.Xml;
  37. #if TARGET_J2EE
  38. using [email protected];
  39. using vmw.common;
  40. using System.Web.J2EE;
  41. #endif
  42. namespace System.Web.Configuration
  43. {
  44. class WebConfigurationSettings
  45. {
  46. #if TARGET_J2EE
  47. static private IConfigurationSystem oldConfig {
  48. get {
  49. return (IConfigurationSystem)AppDomain.CurrentDomain.GetData("WebConfigurationSettings.oldConfig");
  50. }
  51. set {
  52. AppDomain.CurrentDomain.SetData("WebConfigurationSettings.oldConfig", value);
  53. }
  54. }
  55. static private WebDefaultConfig config {
  56. get {
  57. return (WebDefaultConfig)AppDomain.CurrentDomain.GetData("WebConfigurationSettings.config");
  58. }
  59. set {
  60. AppDomain.CurrentDomain.SetData("WebConfigurationSettings.config", value);
  61. }
  62. }
  63. #else
  64. static IConfigurationSystem oldConfig;
  65. static WebDefaultConfig config;
  66. #endif
  67. static string machineConfigPath;
  68. const BindingFlags privStatic = BindingFlags.NonPublic | BindingFlags.Static;
  69. static readonly object lockobj = new object ();
  70. private WebConfigurationSettings ()
  71. {
  72. }
  73. public static void Init ()
  74. {
  75. lock (lockobj) {
  76. if (config != null)
  77. return;
  78. WebDefaultConfig settings = WebDefaultConfig.GetInstance ();
  79. Type t = typeof (ConfigurationSettings);
  80. MethodInfo changeConfig = t.GetMethod ("ChangeConfigurationSystem",
  81. privStatic);
  82. if (changeConfig == null)
  83. throw new ConfigurationException ("Cannot find method CCS");
  84. object [] args = new object [] {settings};
  85. oldConfig = (IConfigurationSystem) changeConfig.Invoke (null, args);
  86. config = settings;
  87. }
  88. }
  89. public static void Init (HttpContext context)
  90. {
  91. Init ();
  92. config.Init (context);
  93. }
  94. public static object GetConfig (string sectionName)
  95. {
  96. return config.GetConfig (sectionName);
  97. }
  98. public static object GetConfig (string sectionName, HttpContext context)
  99. {
  100. return config.GetConfig (sectionName, context);
  101. }
  102. public static string MachineConfigPath {
  103. get {
  104. lock (lockobj) {
  105. if (machineConfigPath != null)
  106. return machineConfigPath;
  107. if (config == null)
  108. Init ();
  109. Type t = oldConfig.GetType ();
  110. MethodInfo getMC = t.GetMethod ("GetMachineConfigPath",
  111. privStatic);
  112. if (getMC == null)
  113. throw new ConfigurationException ("Cannot find method GMC");
  114. machineConfigPath = (string) getMC.Invoke (null, null);
  115. return machineConfigPath;
  116. }
  117. }
  118. }
  119. }
  120. //
  121. // class WebDefaultConfig: read configuration from machine.config file and application
  122. // config file if available.
  123. //
  124. class WebDefaultConfig : IConfigurationSystem
  125. {
  126. #if TARGET_J2EE
  127. static private WebDefaultConfig instance {
  128. get {
  129. WebDefaultConfig val = (WebDefaultConfig)AppDomain.CurrentDomain.GetData("WebDefaultConfig.instance");
  130. if (val == null) {
  131. val = new WebDefaultConfig();
  132. AppDomain.CurrentDomain.SetData("WebDefaultConfig.instance", val);
  133. }
  134. return val;
  135. }
  136. set {
  137. AppDomain.CurrentDomain.SetData("WebDefaultConfig.instance", value);
  138. }
  139. }
  140. #else
  141. static WebDefaultConfig instance;
  142. #endif
  143. Hashtable fileToConfig;
  144. HttpContext firstContext;
  145. bool initCalled;
  146. static WebDefaultConfig ()
  147. {
  148. instance = new WebDefaultConfig ();
  149. }
  150. private WebDefaultConfig ()
  151. {
  152. fileToConfig = new Hashtable ();
  153. }
  154. public static WebDefaultConfig GetInstance ()
  155. {
  156. return instance;
  157. }
  158. public object GetConfig (string sectionName)
  159. {
  160. HttpContext current = HttpContext.Current;
  161. if (current == null)
  162. current = firstContext;
  163. return GetConfig (sectionName, current);
  164. }
  165. public object GetConfig (string sectionName, HttpContext context)
  166. {
  167. if (context == null)
  168. return null;
  169. ConfigurationData config = GetConfigFromFileName (context.Request.CurrentExecutionFilePath, context);
  170. if (config == null)
  171. return null;
  172. return config.GetConfig (sectionName, context);
  173. }
  174. ConfigurationData GetConfigFromFileName (string filepath, HttpContext context)
  175. {
  176. if (filepath == "")
  177. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  178. string dir = UrlUtils.GetDirectory (filepath);
  179. if (HttpRuntime.AppDomainAppVirtualPath.Length > dir.Length)
  180. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  181. ConfigurationData data = (ConfigurationData) fileToConfig [dir];
  182. if (data != null)
  183. return data;
  184. string realpath = null;
  185. try {
  186. realpath = context.Request.MapPath (dir);
  187. } catch {
  188. realpath = context.Request.MapPath (HttpRuntime.AppDomainAppVirtualPath);
  189. }
  190. string lower = Path.Combine (realpath, "web.config");
  191. bool isLower = File.Exists (lower);
  192. string wcfile = null;
  193. if (!isLower) {
  194. string upper = Path.Combine (realpath, "Web.config");
  195. bool isUpper = File.Exists (upper);
  196. if (isUpper)
  197. wcfile = upper;
  198. } else {
  199. wcfile = lower;
  200. }
  201. string tempDir = dir;
  202. if (tempDir == HttpRuntime.AppDomainAppVirtualPath ||
  203. tempDir + "/" == HttpRuntime.AppDomainAppVirtualPath) {
  204. tempDir = "";
  205. realpath = HttpRuntime.AppDomainAppPath;
  206. }
  207. ConfigurationData parent = GetConfigFromFileName (tempDir, context);
  208. if (wcfile == null) {
  209. data = new ConfigurationData (parent, null, realpath);
  210. data.DirName = dir;
  211. fileToConfig [dir] = data;
  212. }
  213. if (data == null) {
  214. data = new ConfigurationData (parent, wcfile);
  215. data.DirName = dir;
  216. data.LoadFromFile (wcfile);
  217. fileToConfig [dir] = data;
  218. RemotingConfiguration.Configure (wcfile);
  219. }
  220. return data;
  221. }
  222. public void Init ()
  223. {
  224. // nothing. We need a context.
  225. }
  226. public void Init (HttpContext context)
  227. {
  228. if (initCalled)
  229. return;
  230. lock (this) {
  231. if (initCalled)
  232. return;
  233. firstContext = context;
  234. ConfigurationData data = new ConfigurationData ();
  235. if (!data.LoadFromFile (WebConfigurationSettings.MachineConfigPath))
  236. throw new ConfigurationException ("Cannot find " + WebConfigurationSettings.MachineConfigPath);
  237. fileToConfig [WebConfigurationSettings.MachineConfigPath] = data;
  238. initCalled = true;
  239. }
  240. }
  241. }
  242. class FileWatcherCache
  243. {
  244. Hashtable cacheTable;
  245. string path;
  246. string filename;
  247. #if !TARGET_JVM // no file watcher support yet in Grasshopper
  248. FileSystemWatcher watcher;
  249. #endif
  250. ConfigurationData data;
  251. public FileWatcherCache (ConfigurationData data)
  252. {
  253. this.data = data;
  254. cacheTable = new Hashtable ();
  255. this.path = Path.GetDirectoryName (data.FileName);
  256. this.filename = Path.GetFileName (data.FileName);
  257. if (!Directory.Exists (path))
  258. return;
  259. #if !TARGET_JVM
  260. watcher = new FileSystemWatcher (this.path, this.filename);
  261. FileSystemEventHandler handler = new FileSystemEventHandler (SetChanged);
  262. watcher.Created += handler;
  263. watcher.Changed += handler;
  264. watcher.Deleted += handler;
  265. watcher.EnableRaisingEvents = true;
  266. #endif
  267. }
  268. #if !TARGET_JVM
  269. void SetChanged (object o, FileSystemEventArgs args)
  270. {
  271. lock (data) {
  272. cacheTable.Clear ();
  273. data.Reset ();
  274. if (args.ChangeType == WatcherChangeTypes.Created)
  275. RemotingConfiguration.Configure (args.FullPath);
  276. if (args.ChangeType != WatcherChangeTypes.Deleted)
  277. data.LoadFromFile (args.FullPath);
  278. }
  279. }
  280. #endif
  281. public object this [string key] {
  282. get {
  283. lock (data)
  284. return cacheTable [key];
  285. }
  286. set {
  287. lock (data)
  288. cacheTable [key] = value;
  289. }
  290. }
  291. public void Close ()
  292. {
  293. #if !TARGET_JVM
  294. if (watcher != null)
  295. watcher.EnableRaisingEvents = false;
  296. #endif
  297. }
  298. }
  299. enum AllowDefinition
  300. {
  301. Everywhere,
  302. MachineOnly,
  303. MachineToApplication
  304. }
  305. class SectionData
  306. {
  307. public readonly string SectionName;
  308. public readonly string TypeName;
  309. public readonly bool AllowLocation;
  310. public readonly AllowDefinition AllowDefinition;
  311. public string FileName;
  312. public SectionData (string sectionName, string typeName,
  313. bool allowLocation, AllowDefinition allowDefinition)
  314. {
  315. SectionName = sectionName;
  316. TypeName = typeName;
  317. AllowLocation = allowLocation;
  318. AllowDefinition = allowDefinition;
  319. }
  320. }
  321. class ConfigurationData
  322. {
  323. ConfigurationData parent;
  324. Hashtable factories;
  325. Hashtable pending;
  326. Hashtable locations;
  327. string fileName;
  328. string dirname;
  329. static object removedMark = new object ();
  330. static object groupMark = new object ();
  331. static object emptyMark = new object ();
  332. FileWatcherCache fileCache;
  333. static char [] forbiddenPathChars = new char [] {
  334. ';', '?', ':', '@', '&', '=', '+',
  335. '$', ',','\\', '*', '\"', '<', '>'
  336. };
  337. static string forbiddenStr = "';', '?', ':', '@', '&', '=', '+', '$', ',', '\\', '*', '\"', '<', '>'";
  338. internal FileWatcherCache FileCache {
  339. get {
  340. lock (this) {
  341. if (fileCache != null)
  342. return fileCache;
  343. fileCache = new FileWatcherCache (this);
  344. }
  345. return fileCache;
  346. }
  347. }
  348. internal string FileName {
  349. get { return fileName; }
  350. }
  351. internal ConfigurationData Parent {
  352. get { return parent; }
  353. }
  354. internal string DirName {
  355. get { return dirname; }
  356. set { dirname = value; }
  357. }
  358. internal void Reset ()
  359. {
  360. factories.Clear ();
  361. if (pending != null)
  362. pending.Clear ();
  363. if (locations != null)
  364. locations.Clear ();
  365. }
  366. public ConfigurationData () : this (null, null)
  367. {
  368. }
  369. public ConfigurationData (ConfigurationData parent, string filename)
  370. {
  371. this.parent = (parent == this) ? null : parent;
  372. this.fileName = filename;
  373. factories = new Hashtable ();
  374. }
  375. public ConfigurationData (ConfigurationData parent, string filename, string realdir)
  376. {
  377. this.parent = (parent == this) ? null : parent;
  378. if (filename == null) {
  379. this.fileName = Path.Combine (realdir, "*.config");
  380. } else {
  381. this.fileName = filename;
  382. }
  383. factories = new Hashtable ();
  384. }
  385. public bool LoadFromFile (string fileName)
  386. {
  387. this.fileName = fileName;
  388. Stream fs = null;
  389. if (fileName == null || !File.Exists (fileName)) {
  390. #if TARGET_J2EE
  391. if (fileName != null && fileName.EndsWith("machine.config"))
  392. {
  393. if (fileName.StartsWith("/"))
  394. fileName = fileName.Substring(1);
  395. java.lang.ClassLoader cl = (java.lang.ClassLoader)AppDomain.CurrentDomain.GetData("GH_ContextClassLoader");
  396. if (cl == null)
  397. return false;
  398. java.io.InputStream inputStream = cl.getResourceAsStream(fileName);
  399. fs = (Stream)IOUtils.getStream(inputStream);
  400. }
  401. else
  402. #endif
  403. return false;
  404. }
  405. XmlTextReader reader = null;
  406. try {
  407. if (fs == null)
  408. fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  409. reader = new XmlTextReader (fs);
  410. InitRead (reader);
  411. ReadConfig (reader, false);
  412. } catch (ConfigurationException) {
  413. throw;
  414. } catch (Exception e) {
  415. throw new ConfigurationException ("Error reading " + fileName, e);
  416. } finally {
  417. if (reader != null)
  418. reader.Close();
  419. }
  420. return true;
  421. }
  422. public void LoadFromReader (XmlTextReader reader, string fakeFileName, bool isLocation)
  423. {
  424. fileName = fakeFileName;
  425. MoveToNextElement (reader);
  426. ReadConfig (reader, isLocation);
  427. }
  428. object GetHandler (string sectionName)
  429. {
  430. lock (factories) {
  431. object o = factories [sectionName];
  432. if (o == null || o == removedMark) {
  433. if (parent != null)
  434. return parent.GetHandler (sectionName);
  435. return null;
  436. }
  437. if (o is IConfigurationSectionHandler)
  438. return (IConfigurationSectionHandler) o;
  439. o = CreateNewHandler (sectionName, (SectionData) o);
  440. factories [sectionName] = o;
  441. return o;
  442. }
  443. }
  444. object CreateNewHandler (string sectionName, SectionData section)
  445. {
  446. Type t = Type.GetType (section.TypeName);
  447. if (t == null)
  448. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  449. Type iconfig = typeof (IConfigurationSectionHandler);
  450. if (!iconfig.IsAssignableFrom (t))
  451. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  452. object o = Activator.CreateInstance (t, true);
  453. if (o == null)
  454. throw new ConfigurationException ("Cannot get instance for " + t);
  455. return o;
  456. }
  457. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  458. {
  459. if (++i >= sectionPath.Length)
  460. return doc;
  461. if (doc.DocumentElement == null)
  462. return null;
  463. XmlNode node = doc.DocumentElement.FirstChild;
  464. while (node != null) {
  465. if (node.Name == sectionPath [i]) {
  466. ConfigXmlDocument result = new ConfigXmlDocument ();
  467. result.Load (new StringReader (node.OuterXml));
  468. return GetInnerDoc (result, i, sectionPath);
  469. }
  470. node = node.NextSibling;
  471. }
  472. return null;
  473. }
  474. XmlDocument GetDocumentForSection (string sectionName)
  475. {
  476. ConfigXmlDocument doc = new ConfigXmlDocument ();
  477. if (pending == null)
  478. return doc;
  479. string [] sectionPath = sectionName.Split ('/');
  480. string outerxml = pending [sectionPath [0]] as string;
  481. if (outerxml == null)
  482. return doc;
  483. StringReader reader = new StringReader (outerxml);
  484. XmlTextReader rd = new XmlTextReader (reader);
  485. rd.MoveToContent ();
  486. doc.LoadSingleElement (fileName, rd);
  487. return GetInnerDoc (doc, 0, sectionPath);
  488. }
  489. object GetConfigInternal (string sectionName, HttpContext context, bool useLoc)
  490. {
  491. object handler = GetHandler (sectionName);
  492. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  493. if (iconf == null)
  494. return handler;
  495. object parentConfig = null;
  496. if (parent != null) {
  497. if (useLoc)
  498. parentConfig = parent.GetConfig (sectionName, context);
  499. else
  500. parentConfig = parent.GetConfigOptLocation (sectionName, context, false);
  501. }
  502. XmlDocument doc = GetDocumentForSection (sectionName);
  503. if (doc == null || doc.DocumentElement == null)
  504. return parentConfig;
  505. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  506. }
  507. string MakeRelative (string fullUrl, string relativeTo)
  508. {
  509. if (fullUrl == relativeTo)
  510. return String.Empty;
  511. if (fullUrl.IndexOf (relativeTo) != 0)
  512. return null;
  513. string leftOver = fullUrl.Substring (relativeTo.Length);
  514. if (leftOver.Length > 0 && leftOver [0] == '/')
  515. leftOver = leftOver.Substring (1);
  516. leftOver = UrlUtils.Canonic (leftOver);
  517. if (leftOver.Length > 0 && leftOver [0] == '/')
  518. leftOver = leftOver.Substring (1);
  519. return leftOver;
  520. }
  521. public object GetConfig (string sectionName, HttpContext context)
  522. {
  523. if (locations != null && dirname != null) {
  524. string reduced = MakeRelative (context.Request.CurrentExecutionFilePath, dirname);
  525. string [] parts = reduced.Split ('/');
  526. Location location = null;
  527. string target = null;
  528. for (int i = 0; i < parts.Length; i++) {
  529. if (target == null)
  530. target = parts [i];
  531. else
  532. target = target + "/" + parts [i];
  533. if (locations.ContainsKey (target)) {
  534. location = locations [target] as Location;
  535. } else if (locations.ContainsKey (target + "/*")) {
  536. location = locations [target + "/*"] as Location;
  537. }
  538. }
  539. if (location == null) {
  540. location = locations ["*"] as Location;
  541. }
  542. if (location != null && location.Config != null) {
  543. object o = location.Config.GetConfigOptLocation (sectionName, context, false);
  544. if (o != null) {
  545. return o;
  546. }
  547. }
  548. }
  549. return GetConfigOptLocation (sectionName, context, true);
  550. }
  551. object GetConfigOptLocation (string sectionName, HttpContext context, bool useLoc)
  552. {
  553. object config = this.FileCache [sectionName];
  554. if (config == emptyMark)
  555. return null;
  556. if (config != null)
  557. return config;
  558. lock (this) {
  559. config = GetConfigInternal (sectionName, context, useLoc);
  560. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  561. }
  562. return config;
  563. }
  564. private object LookForFactory (string key)
  565. {
  566. object o = factories [key];
  567. if (o != null)
  568. return o;
  569. if (parent != null)
  570. return parent.LookForFactory (key);
  571. return null;
  572. }
  573. private void InitRead (XmlTextReader reader)
  574. {
  575. reader.MoveToContent ();
  576. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  577. ThrowException ("Configuration file does not have a valid root element", reader);
  578. if (reader.HasAttributes)
  579. ThrowException ("Unrecognized attribute in root element", reader);
  580. MoveToNextElement (reader);
  581. }
  582. internal void MoveToNextElement (XmlTextReader reader)
  583. {
  584. while (reader.Read ()) {
  585. XmlNodeType ntype = reader.NodeType;
  586. if (ntype == XmlNodeType.Element)
  587. return;
  588. if (ntype != XmlNodeType.Whitespace &&
  589. ntype != XmlNodeType.Comment &&
  590. ntype != XmlNodeType.SignificantWhitespace &&
  591. ntype != XmlNodeType.EndElement)
  592. ThrowException ("Unrecognized element", reader);
  593. }
  594. }
  595. private void ReadSection (XmlTextReader reader, string sectionName)
  596. {
  597. string attName;
  598. string nameValue = null;
  599. string typeValue = null;
  600. string allowLoc = null, allowDef = null;
  601. bool allowLocation = true;
  602. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  603. while (reader.MoveToNextAttribute ()) {
  604. attName = reader.Name;
  605. if (attName == null)
  606. continue;
  607. if (attName == "allowLocation") {
  608. if (allowLoc != null)
  609. ThrowException ("Duplicated allowLocation attribute.", reader);
  610. allowLoc = reader.Value;
  611. allowLocation = (allowLoc == "true");
  612. if (!allowLocation && allowLoc != "false")
  613. ThrowException ("Invalid attribute value", reader);
  614. continue;
  615. }
  616. if (attName == "allowDefinition") {
  617. if (allowDef != null)
  618. ThrowException ("Duplicated allowDefinition attribute.", reader);
  619. allowDef = reader.Value;
  620. try {
  621. allowDefinition = (AllowDefinition) Enum.Parse (
  622. typeof (AllowDefinition), allowDef);
  623. } catch {
  624. ThrowException ("Invalid attribute value", reader);
  625. }
  626. continue;
  627. }
  628. if (attName == "type") {
  629. if (typeValue != null)
  630. ThrowException ("Duplicated type attribute.", reader);
  631. typeValue = reader.Value;
  632. continue;
  633. }
  634. if (attName == "name") {
  635. if (nameValue != null)
  636. ThrowException ("Duplicated name attribute.", reader);
  637. nameValue = reader.Value;
  638. if (nameValue == "location")
  639. ThrowException ("location is a reserved section name", reader);
  640. continue;
  641. }
  642. ThrowException ("Unrecognized attribute.", reader);
  643. }
  644. if (nameValue == null || typeValue == null)
  645. ThrowException ("Required attribute missing", reader);
  646. if (sectionName != null)
  647. nameValue = sectionName + '/' + nameValue;
  648. reader.MoveToElement();
  649. object o = LookForFactory (nameValue);
  650. if (o != null && o != removedMark)
  651. ThrowException ("Already have a factory for " + nameValue, reader);
  652. SectionData section = new SectionData (nameValue, typeValue, allowLocation, allowDefinition);
  653. section.FileName = fileName;
  654. factories [nameValue] = section;
  655. MoveToNextElement (reader);
  656. }
  657. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  658. {
  659. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  660. ThrowException ("Unrecognized attribute.", reader);
  661. string removeValue = reader.Value;
  662. if (removeValue == null || removeValue.Length == 0)
  663. ThrowException ("Empty name to remove", reader);
  664. reader.MoveToElement ();
  665. if (sectionName != null)
  666. removeValue = sectionName + '/' + removeValue;
  667. object o = LookForFactory (removeValue);
  668. if (o != null && o == removedMark)
  669. ThrowException ("No factory for " + removeValue, reader);
  670. factories [removeValue] = removedMark;
  671. MoveToNextElement (reader);
  672. }
  673. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  674. {
  675. if (!reader.MoveToNextAttribute ())
  676. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  677. string value = null;
  678. #if NET_2_0
  679. do {
  680. if (reader.Name == "name") {
  681. if (value != null)
  682. ThrowException ("Duplicate 'name' attribute.", reader);
  683. value = reader.Value;
  684. }
  685. else if (reader.Name != "type")
  686. ThrowException ("Unrecognized attribute.", reader);
  687. } while (reader.MoveToNextAttribute ());
  688. #else
  689. if (reader.Name != "name")
  690. ThrowException ("Unrecognized attribute.", reader);
  691. if (reader.MoveToNextAttribute ())
  692. ThrowException ("Unrecognized attribute.", reader);
  693. value = reader.Value;
  694. #endif
  695. if (value == null)
  696. ThrowException ("No 'name' attribute.", reader);
  697. if (value == "location")
  698. ThrowException ("location is a reserved section name", reader);
  699. if (configSection != null)
  700. value = configSection + '/' + value;
  701. object o = LookForFactory (value);
  702. if (o != null && o != removedMark && o != groupMark)
  703. ThrowException ("Already have a factory for " + value, reader);
  704. factories [value] = groupMark;
  705. MoveToNextElement (reader);
  706. ReadSections (reader, value);
  707. }
  708. private void ReadSections (XmlTextReader reader, string configSection)
  709. {
  710. int depth = reader.Depth;
  711. while (reader.Depth == depth) {
  712. string name = reader.Name;
  713. if (name == "section") {
  714. ReadSection (reader, configSection);
  715. continue;
  716. }
  717. if (name == "remove") {
  718. ReadRemoveSection (reader, configSection);
  719. continue;
  720. }
  721. if (name == "clear") {
  722. if (reader.HasAttributes)
  723. ThrowException ("Unrecognized attribute.", reader);
  724. factories.Clear ();
  725. MoveToNextElement (reader);
  726. continue;
  727. }
  728. if (name == "sectionGroup") {
  729. ReadSectionGroup (reader, configSection);
  730. continue;
  731. }
  732. ThrowException ("Unrecognized element: " + reader.Name, reader);
  733. }
  734. }
  735. void StoreLocation (string name, XmlTextReader reader)
  736. {
  737. string path = null;
  738. bool haveAllow = false;
  739. bool allowOverride = true;
  740. string att = null;
  741. while (reader.MoveToNextAttribute ()) {
  742. att = reader.Name;
  743. if (att == "path") {
  744. if (path != null)
  745. ThrowException ("Duplicate path attribute", reader);
  746. path = reader.Value;
  747. if (path.StartsWith ("."))
  748. ThrowException ("Path cannot begin with '.'", reader);
  749. if (path.IndexOfAny (forbiddenPathChars) != -1)
  750. ThrowException ("Path cannot contain " + forbiddenStr, reader);
  751. continue;
  752. }
  753. if (att == "allowOverride") {
  754. if (haveAllow)
  755. ThrowException ("Duplicate allowOverride attribute", reader);
  756. haveAllow = true;
  757. allowOverride = (reader.Value == "true");
  758. if (!allowOverride && reader.Value != "false")
  759. ThrowException ("allowOverride must be either true or false", reader);
  760. continue;
  761. }
  762. ThrowException ("Unrecognized attribute.", reader);
  763. }
  764. if (att == null)
  765. return; // empty location tag
  766. Location loc = new Location (this, path, allowOverride);
  767. if (locations == null)
  768. locations = new Hashtable ();
  769. else if (locations.ContainsKey (loc.Path))
  770. ThrowException ("Duplicated location path: " + loc.Path, reader);
  771. reader.MoveToElement ();
  772. loc.LoadFromString (reader.ReadOuterXml ());
  773. locations [loc.Path] = loc;
  774. if (!loc.AllowOverride) {
  775. XmlTextReader inner = loc.GetReader ();
  776. if (inner != null) {
  777. MoveToNextElement (inner);
  778. ReadConfig (loc.GetReader (), true);
  779. }
  780. }
  781. loc.XmlStr = null;
  782. }
  783. void StorePending (string name, XmlTextReader reader)
  784. {
  785. if (pending == null)
  786. pending = new Hashtable ();
  787. if (pending.ContainsKey (name))
  788. ThrowException ("Sections can only appear once: " + name, reader);
  789. pending [name] = reader.ReadOuterXml ();
  790. }
  791. void ReadConfig (XmlTextReader reader, bool isLocation)
  792. {
  793. int depth = reader.Depth;
  794. while (!reader.EOF && reader.Depth == depth) {
  795. string name = reader.Name;
  796. if (name == "configSections") {
  797. if (isLocation)
  798. ThrowException ("<configSections> inside <location>", reader);
  799. if (reader.HasAttributes)
  800. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  801. MoveToNextElement (reader);
  802. if (reader.Depth > depth)
  803. ReadSections (reader, null);
  804. } else if (name == "location") {
  805. if (isLocation)
  806. ThrowException ("<location> inside <location>", reader);
  807. StoreLocation (name, reader);
  808. MoveToNextElement (reader);
  809. } else if (name != null && name != ""){
  810. StorePending (name, reader);
  811. MoveToNextElement (reader);
  812. } else {
  813. MoveToNextElement (reader);
  814. }
  815. }
  816. }
  817. void ThrowException (string text, XmlTextReader reader)
  818. {
  819. throw new ConfigurationException (text, fileName, reader.LineNumber);
  820. }
  821. }
  822. class Location
  823. {
  824. string path;
  825. bool allowOverride;
  826. ConfigurationData parent;
  827. ConfigurationData thisOne;
  828. string xmlstr;
  829. public Location (ConfigurationData parent, string path, bool allowOverride)
  830. {
  831. this.parent = parent;
  832. this.allowOverride = allowOverride;
  833. this.path = (path == null || path == "") ? "*" : path;
  834. }
  835. public bool AllowOverride {
  836. get { return (path != "*" || allowOverride); }
  837. }
  838. public string Path {
  839. get { return path; }
  840. }
  841. public string XmlStr {
  842. set { xmlstr = value; }
  843. }
  844. public void LoadFromString (string str)
  845. {
  846. if (str == null)
  847. throw new ArgumentNullException ("str");
  848. if (thisOne != null)
  849. throw new InvalidOperationException ();
  850. this.xmlstr = str.Trim ();
  851. if (xmlstr == "")
  852. return;
  853. XmlTextReader reader = GetReader ();
  854. thisOne = new ConfigurationData (parent, parent.FileName);
  855. thisOne.LoadFromReader (reader, parent.FileName, true);
  856. }
  857. public XmlTextReader GetReader ()
  858. {
  859. if (xmlstr == "")
  860. return null;
  861. XmlTextReader reader = new XmlTextReader (new StringReader (xmlstr));
  862. reader.ReadStartElement ("location");
  863. return reader;
  864. }
  865. public ConfigurationData Config {
  866. get { return thisOne; }
  867. }
  868. }
  869. }