WebConfigurationSettings.cs 27 KB

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