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.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. object this_lock = new object ();
  127. #if TARGET_J2EE
  128. static private WebDefaultConfig instance {
  129. get {
  130. WebDefaultConfig val = (WebDefaultConfig)AppDomain.CurrentDomain.GetData("WebDefaultConfig.instance");
  131. if (val == null) {
  132. val = new WebDefaultConfig();
  133. AppDomain.CurrentDomain.SetData("WebDefaultConfig.instance", val);
  134. }
  135. return val;
  136. }
  137. set {
  138. AppDomain.CurrentDomain.SetData("WebDefaultConfig.instance", value);
  139. }
  140. }
  141. #else
  142. static WebDefaultConfig instance;
  143. #endif
  144. Hashtable fileToConfig;
  145. HttpContext firstContext;
  146. bool initCalled;
  147. static WebDefaultConfig ()
  148. {
  149. instance = new WebDefaultConfig ();
  150. }
  151. private WebDefaultConfig ()
  152. {
  153. fileToConfig = new Hashtable ();
  154. }
  155. public static WebDefaultConfig GetInstance ()
  156. {
  157. return instance;
  158. }
  159. public object GetConfig (string sectionName)
  160. {
  161. HttpContext current = HttpContext.Current;
  162. if (current == null)
  163. current = firstContext;
  164. return GetConfig (sectionName, current);
  165. }
  166. public object GetConfig (string sectionName, HttpContext context)
  167. {
  168. if (context == null)
  169. return null;
  170. ConfigurationData config = GetConfigFromFileName (context.Request.CurrentExecutionFilePath, context);
  171. if (config == null)
  172. return null;
  173. return config.GetConfig (sectionName, context);
  174. }
  175. ConfigurationData GetConfigFromFileName (string filepath, HttpContext context)
  176. {
  177. if (filepath == "")
  178. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  179. string dir = UrlUtils.GetDirectory (filepath);
  180. if (HttpRuntime.AppDomainAppVirtualPath.Length > dir.Length)
  181. return (ConfigurationData) fileToConfig [WebConfigurationSettings.MachineConfigPath];
  182. ConfigurationData data = (ConfigurationData) fileToConfig [dir];
  183. if (data != null)
  184. return data;
  185. string realpath = null;
  186. try {
  187. realpath = context.Request.MapPath (dir);
  188. } catch {
  189. realpath = context.Request.MapPath (HttpRuntime.AppDomainAppVirtualPath);
  190. }
  191. string lower = Path.Combine (realpath, "web.config");
  192. bool isLower = File.Exists (lower);
  193. string wcfile = null;
  194. if (!isLower) {
  195. string upper = Path.Combine (realpath, "Web.config");
  196. bool isUpper = File.Exists (upper);
  197. if (isUpper)
  198. wcfile = upper;
  199. } else {
  200. wcfile = lower;
  201. }
  202. string tempDir = dir;
  203. if (tempDir.Length > 1)
  204. tempDir = tempDir.Substring (0, tempDir.Length - 1);
  205. if (tempDir == HttpRuntime.AppDomainAppVirtualPath) {
  206. tempDir = "";
  207. realpath = HttpRuntime.AppDomainAppPath;
  208. }
  209. ConfigurationData parent = GetConfigFromFileName (tempDir, context);
  210. if (wcfile == null) {
  211. data = new ConfigurationData (parent, null, realpath);
  212. data.DirName = dir;
  213. fileToConfig [dir] = data;
  214. }
  215. if (data == null) {
  216. data = new ConfigurationData (parent, wcfile);
  217. data.DirName = dir;
  218. data.LoadFromFile (wcfile);
  219. fileToConfig [dir] = data;
  220. RemotingConfiguration.Configure (wcfile);
  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.Created)
  278. RemotingConfiguration.Configure (args.FullPath);
  279. if (args.ChangeType != WatcherChangeTypes.Deleted)
  280. data.LoadFromFile (args.FullPath);
  281. }
  282. }
  283. #endif
  284. public object this [string key] {
  285. get {
  286. lock (data)
  287. return cacheTable [key];
  288. }
  289. set {
  290. lock (data)
  291. cacheTable [key] = value;
  292. }
  293. }
  294. public void Close ()
  295. {
  296. #if !TARGET_JVM
  297. if (watcher != null)
  298. watcher.EnableRaisingEvents = false;
  299. #endif
  300. }
  301. }
  302. enum AllowDefinition
  303. {
  304. Everywhere,
  305. MachineOnly,
  306. MachineToApplication
  307. }
  308. class SectionData
  309. {
  310. public readonly string SectionName;
  311. public readonly string TypeName;
  312. public readonly bool AllowLocation;
  313. public readonly AllowDefinition AllowDefinition;
  314. public string FileName;
  315. public SectionData (string sectionName, string typeName,
  316. bool allowLocation, AllowDefinition allowDefinition)
  317. {
  318. SectionName = sectionName;
  319. TypeName = typeName;
  320. AllowLocation = allowLocation;
  321. AllowDefinition = allowDefinition;
  322. }
  323. }
  324. class ConfigurationData
  325. {
  326. object this_lock = new object ();
  327. ConfigurationData parent;
  328. Hashtable factories;
  329. Hashtable pending;
  330. Hashtable locations;
  331. string fileName;
  332. string dirname;
  333. static object removedMark = new object ();
  334. static object groupMark = new object ();
  335. static object emptyMark = new object ();
  336. FileWatcherCache fileCache;
  337. static char [] forbiddenPathChars = new char [] {
  338. ';', '?', ':', '@', '&', '=', '+',
  339. '$', ',','\\', '*', '\"', '<', '>'
  340. };
  341. static string forbiddenStr = "';', '?', ':', '@', '&', '=', '+', '$', ',', '\\', '*', '\"', '<', '>'";
  342. internal FileWatcherCache FileCache {
  343. get {
  344. lock (this_lock) {
  345. if (fileCache != null)
  346. return fileCache;
  347. fileCache = new FileWatcherCache (this);
  348. }
  349. return fileCache;
  350. }
  351. }
  352. internal string FileName {
  353. get { return fileName; }
  354. }
  355. internal ConfigurationData Parent {
  356. get { return parent; }
  357. }
  358. internal string DirName {
  359. get { return dirname; }
  360. set { dirname = value; }
  361. }
  362. internal void Reset ()
  363. {
  364. factories.Clear ();
  365. if (pending != null)
  366. pending.Clear ();
  367. if (locations != null)
  368. locations.Clear ();
  369. }
  370. public ConfigurationData () : this (null, null)
  371. {
  372. }
  373. public ConfigurationData (ConfigurationData parent, string filename)
  374. {
  375. this.parent = (parent == this) ? null : parent;
  376. this.fileName = filename;
  377. factories = new Hashtable ();
  378. }
  379. public ConfigurationData (ConfigurationData parent, string filename, string realdir)
  380. {
  381. this.parent = (parent == this) ? null : parent;
  382. if (filename == null) {
  383. this.fileName = Path.Combine (realdir, "*.config");
  384. } else {
  385. this.fileName = filename;
  386. }
  387. factories = new Hashtable ();
  388. }
  389. public bool LoadFromFile (string fileName)
  390. {
  391. this.fileName = fileName;
  392. Stream fs = null;
  393. if (fileName == null || !File.Exists (fileName)) {
  394. #if TARGET_J2EE
  395. if (fileName != null && fileName.EndsWith("machine.config"))
  396. {
  397. if (fileName.StartsWith("/"))
  398. fileName = fileName.Substring(1);
  399. java.lang.ClassLoader cl = (java.lang.ClassLoader)AppDomain.CurrentDomain.GetData("GH_ContextClassLoader");
  400. if (cl == null)
  401. return false;
  402. java.io.InputStream inputStream = cl.getResourceAsStream(fileName);
  403. fs = (Stream)IOUtils.getStream(inputStream);
  404. }
  405. else
  406. #endif
  407. return false;
  408. }
  409. XmlTextReader reader = null;
  410. try {
  411. if (fs == null)
  412. fs = new FileStream (fileName, FileMode.Open, FileAccess.Read);
  413. reader = new XmlTextReader (fs);
  414. InitRead (reader);
  415. ReadConfig (reader, false);
  416. } catch (ConfigurationException) {
  417. throw;
  418. } catch (Exception e) {
  419. throw new ConfigurationException ("Error reading " + fileName, e);
  420. } finally {
  421. if (reader != null)
  422. reader.Close();
  423. }
  424. return true;
  425. }
  426. public void LoadFromReader (XmlTextReader reader, string fakeFileName, bool isLocation)
  427. {
  428. fileName = fakeFileName;
  429. MoveToNextElement (reader);
  430. ReadConfig (reader, isLocation);
  431. }
  432. object GetHandler (string sectionName)
  433. {
  434. lock (factories) {
  435. object o = factories [sectionName];
  436. if (o == null || o == removedMark) {
  437. if (parent != null)
  438. return parent.GetHandler (sectionName);
  439. return null;
  440. }
  441. if (o is IConfigurationSectionHandler)
  442. return (IConfigurationSectionHandler) o;
  443. o = CreateNewHandler (sectionName, (SectionData) o);
  444. factories [sectionName] = o;
  445. return o;
  446. }
  447. }
  448. object CreateNewHandler (string sectionName, SectionData section)
  449. {
  450. Type t = Type.GetType (section.TypeName);
  451. if (t == null)
  452. throw new ConfigurationException ("Cannot get Type for " + section.TypeName);
  453. Type iconfig = typeof (IConfigurationSectionHandler);
  454. if (!iconfig.IsAssignableFrom (t))
  455. throw new ConfigurationException (sectionName + " does not implement " + iconfig);
  456. object o = Activator.CreateInstance (t, true);
  457. if (o == null)
  458. throw new ConfigurationException ("Cannot get instance for " + t);
  459. return o;
  460. }
  461. XmlDocument GetInnerDoc (XmlDocument doc, int i, string [] sectionPath)
  462. {
  463. if (++i >= sectionPath.Length)
  464. return doc;
  465. if (doc.DocumentElement == null)
  466. return null;
  467. XmlNode node = doc.DocumentElement.FirstChild;
  468. while (node != null) {
  469. if (node.Name == sectionPath [i]) {
  470. ConfigXmlDocument result = new ConfigXmlDocument ();
  471. result.Load (new StringReader (node.OuterXml));
  472. return GetInnerDoc (result, i, sectionPath);
  473. }
  474. node = node.NextSibling;
  475. }
  476. return null;
  477. }
  478. XmlDocument GetDocumentForSection (string sectionName)
  479. {
  480. ConfigXmlDocument doc = new ConfigXmlDocument ();
  481. if (pending == null)
  482. return doc;
  483. string [] sectionPath = sectionName.Split ('/');
  484. string outerxml = pending [sectionPath [0]] as string;
  485. if (outerxml == null)
  486. return doc;
  487. StringReader reader = new StringReader (outerxml);
  488. XmlTextReader rd = new XmlTextReader (reader);
  489. rd.MoveToContent ();
  490. doc.LoadSingleElement (fileName, rd);
  491. return GetInnerDoc (doc, 0, sectionPath);
  492. }
  493. object GetConfigInternal (string sectionName, HttpContext context, bool useLoc)
  494. {
  495. object handler = GetHandler (sectionName);
  496. IConfigurationSectionHandler iconf = handler as IConfigurationSectionHandler;
  497. if (iconf == null)
  498. return handler;
  499. object parentConfig = null;
  500. if (parent != null) {
  501. if (useLoc)
  502. parentConfig = parent.GetConfig (sectionName, context);
  503. else
  504. parentConfig = parent.GetConfigOptLocation (sectionName, context, false);
  505. }
  506. XmlDocument doc = GetDocumentForSection (sectionName);
  507. if (doc == null || doc.DocumentElement == null)
  508. return parentConfig;
  509. return iconf.Create (parentConfig, fileName, doc.DocumentElement);
  510. }
  511. string MakeRelative (string fullUrl, string relativeTo)
  512. {
  513. if (fullUrl == relativeTo)
  514. return String.Empty;
  515. if (fullUrl.IndexOf (relativeTo) != 0)
  516. return null;
  517. string leftOver = fullUrl.Substring (relativeTo.Length);
  518. if (leftOver.Length > 0 && leftOver [0] == '/')
  519. leftOver = leftOver.Substring (1);
  520. leftOver = UrlUtils.Canonic (leftOver);
  521. if (leftOver.Length > 0 && leftOver [0] == '/')
  522. leftOver = leftOver.Substring (1);
  523. return leftOver;
  524. }
  525. public object GetConfig (string sectionName, HttpContext context)
  526. {
  527. if (locations != null && dirname != null) {
  528. string reduced = MakeRelative (context.Request.CurrentExecutionFilePath, dirname);
  529. string [] parts = reduced.Split ('/');
  530. Location location = null;
  531. string target = null;
  532. for (int i = 0; i < parts.Length; i++) {
  533. if (target == null)
  534. target = parts [i];
  535. else
  536. target = target + "/" + parts [i];
  537. if (locations.ContainsKey (target)) {
  538. location = locations [target] as Location;
  539. } else if (locations.ContainsKey (target + "/*")) {
  540. location = locations [target + "/*"] as Location;
  541. }
  542. }
  543. if (location == null) {
  544. location = locations ["*"] as Location;
  545. }
  546. if (location != null && location.Config != null) {
  547. object o = location.Config.GetConfigOptLocation (sectionName, context, false);
  548. if (o != null) {
  549. return o;
  550. }
  551. }
  552. }
  553. return GetConfigOptLocation (sectionName, context, true);
  554. }
  555. object GetConfigOptLocation (string sectionName, HttpContext context, bool useLoc)
  556. {
  557. object config = this.FileCache [sectionName];
  558. if (config == emptyMark)
  559. return null;
  560. if (config != null)
  561. return config;
  562. lock (this_lock) {
  563. config = GetConfigInternal (sectionName, context, useLoc);
  564. this.FileCache [sectionName] = (config == null) ? emptyMark : config;
  565. }
  566. return config;
  567. }
  568. private object LookForFactory (string key)
  569. {
  570. object o = factories [key];
  571. if (o != null)
  572. return o;
  573. if (parent != null)
  574. return parent.LookForFactory (key);
  575. return null;
  576. }
  577. private void InitRead (XmlTextReader reader)
  578. {
  579. reader.MoveToContent ();
  580. if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
  581. ThrowException ("Configuration file does not have a valid root element", reader);
  582. if (reader.HasAttributes)
  583. ThrowException ("Unrecognized attribute in root element", reader);
  584. MoveToNextElement (reader);
  585. }
  586. internal void MoveToNextElement (XmlTextReader reader)
  587. {
  588. while (reader.Read ()) {
  589. XmlNodeType ntype = reader.NodeType;
  590. if (ntype == XmlNodeType.Element)
  591. return;
  592. if (ntype != XmlNodeType.Whitespace &&
  593. ntype != XmlNodeType.Comment &&
  594. ntype != XmlNodeType.SignificantWhitespace &&
  595. ntype != XmlNodeType.EndElement)
  596. ThrowException ("Unrecognized element", reader);
  597. }
  598. }
  599. private void ReadSection (XmlTextReader reader, string sectionName)
  600. {
  601. string attName;
  602. string nameValue = null;
  603. string typeValue = null;
  604. string allowLoc = null, allowDef = null;
  605. bool allowLocation = true;
  606. AllowDefinition allowDefinition = AllowDefinition.Everywhere;
  607. while (reader.MoveToNextAttribute ()) {
  608. attName = reader.Name;
  609. if (attName == null)
  610. continue;
  611. if (attName == "allowLocation") {
  612. if (allowLoc != null)
  613. ThrowException ("Duplicated allowLocation attribute.", reader);
  614. allowLoc = reader.Value;
  615. allowLocation = (allowLoc == "true");
  616. if (!allowLocation && allowLoc != "false")
  617. ThrowException ("Invalid attribute value", reader);
  618. continue;
  619. }
  620. if (attName == "allowDefinition") {
  621. if (allowDef != null)
  622. ThrowException ("Duplicated allowDefinition attribute.", reader);
  623. allowDef = reader.Value;
  624. try {
  625. allowDefinition = (AllowDefinition) Enum.Parse (
  626. typeof (AllowDefinition), allowDef);
  627. } catch {
  628. ThrowException ("Invalid attribute value", reader);
  629. }
  630. continue;
  631. }
  632. if (attName == "type") {
  633. if (typeValue != null)
  634. ThrowException ("Duplicated type attribute.", reader);
  635. typeValue = reader.Value;
  636. continue;
  637. }
  638. if (attName == "name") {
  639. if (nameValue != null)
  640. ThrowException ("Duplicated name attribute.", reader);
  641. nameValue = reader.Value;
  642. if (nameValue == "location")
  643. ThrowException ("location is a reserved section name", reader);
  644. continue;
  645. }
  646. ThrowException ("Unrecognized attribute.", reader);
  647. }
  648. if (nameValue == null || typeValue == null)
  649. ThrowException ("Required attribute missing", reader);
  650. if (sectionName != null)
  651. nameValue = sectionName + '/' + nameValue;
  652. reader.MoveToElement();
  653. object o = LookForFactory (nameValue);
  654. if (o != null && o != removedMark)
  655. ThrowException ("Already have a factory for " + nameValue, reader);
  656. SectionData section = new SectionData (nameValue, typeValue, allowLocation, allowDefinition);
  657. section.FileName = fileName;
  658. factories [nameValue] = section;
  659. MoveToNextElement (reader);
  660. }
  661. private void ReadRemoveSection (XmlTextReader reader, string sectionName)
  662. {
  663. if (!reader.MoveToNextAttribute () || reader.Name != "name")
  664. ThrowException ("Unrecognized attribute.", reader);
  665. string removeValue = reader.Value;
  666. if (removeValue == null || removeValue.Length == 0)
  667. ThrowException ("Empty name to remove", reader);
  668. reader.MoveToElement ();
  669. if (sectionName != null)
  670. removeValue = sectionName + '/' + removeValue;
  671. object o = LookForFactory (removeValue);
  672. if (o != null && o == removedMark)
  673. ThrowException ("No factory for " + removeValue, reader);
  674. factories [removeValue] = removedMark;
  675. MoveToNextElement (reader);
  676. }
  677. private void ReadSectionGroup (XmlTextReader reader, string configSection)
  678. {
  679. if (!reader.MoveToNextAttribute ())
  680. ThrowException ("sectionGroup must have a 'name' attribute.", reader);
  681. string value = null;
  682. #if NET_2_0
  683. do {
  684. if (reader.Name == "name") {
  685. if (value != null)
  686. ThrowException ("Duplicate 'name' attribute.", reader);
  687. value = reader.Value;
  688. }
  689. else if (reader.Name != "type")
  690. ThrowException ("Unrecognized attribute.", reader);
  691. } while (reader.MoveToNextAttribute ());
  692. #else
  693. if (reader.Name != "name")
  694. ThrowException ("Unrecognized attribute.", reader);
  695. if (reader.MoveToNextAttribute ())
  696. ThrowException ("Unrecognized attribute.", reader);
  697. value = reader.Value;
  698. #endif
  699. if (value == null)
  700. ThrowException ("No 'name' attribute.", reader);
  701. if (value == "location")
  702. ThrowException ("location is a reserved section name", reader);
  703. if (configSection != null)
  704. value = configSection + '/' + value;
  705. object o = LookForFactory (value);
  706. if (o != null && o != removedMark && o != groupMark)
  707. ThrowException ("Already have a factory for " + value, reader);
  708. factories [value] = groupMark;
  709. MoveToNextElement (reader);
  710. ReadSections (reader, value);
  711. }
  712. private void ReadSections (XmlTextReader reader, string configSection)
  713. {
  714. int depth = reader.Depth;
  715. while (reader.Depth == depth) {
  716. string name = reader.Name;
  717. if (name == "section") {
  718. ReadSection (reader, configSection);
  719. continue;
  720. }
  721. if (name == "remove") {
  722. ReadRemoveSection (reader, configSection);
  723. continue;
  724. }
  725. if (name == "clear") {
  726. if (reader.HasAttributes)
  727. ThrowException ("Unrecognized attribute.", reader);
  728. factories.Clear ();
  729. MoveToNextElement (reader);
  730. continue;
  731. }
  732. if (name == "sectionGroup") {
  733. ReadSectionGroup (reader, configSection);
  734. continue;
  735. }
  736. ThrowException ("Unrecognized element: " + reader.Name, reader);
  737. }
  738. }
  739. void StoreLocation (string name, XmlTextReader reader)
  740. {
  741. string path = null;
  742. bool haveAllow = false;
  743. bool allowOverride = true;
  744. string att = null;
  745. while (reader.MoveToNextAttribute ()) {
  746. att = reader.Name;
  747. if (att == "path") {
  748. if (path != null)
  749. ThrowException ("Duplicate path attribute", reader);
  750. path = reader.Value;
  751. if (path.StartsWith ("."))
  752. ThrowException ("Path cannot begin with '.'", reader);
  753. if (path.IndexOfAny (forbiddenPathChars) != -1)
  754. ThrowException ("Path cannot contain " + forbiddenStr, reader);
  755. continue;
  756. }
  757. if (att == "allowOverride") {
  758. if (haveAllow)
  759. ThrowException ("Duplicate allowOverride attribute", reader);
  760. haveAllow = true;
  761. allowOverride = (reader.Value == "true");
  762. if (!allowOverride && reader.Value != "false")
  763. ThrowException ("allowOverride must be either true or false", reader);
  764. continue;
  765. }
  766. ThrowException ("Unrecognized attribute.", reader);
  767. }
  768. if (att == null)
  769. return; // empty location tag
  770. Location loc = new Location (this, path, allowOverride);
  771. if (locations == null)
  772. locations = new Hashtable ();
  773. else if (locations.ContainsKey (loc.Path))
  774. ThrowException ("Duplicated location path: " + loc.Path, reader);
  775. reader.MoveToElement ();
  776. loc.LoadFromString (reader.ReadOuterXml ());
  777. locations [loc.Path] = loc;
  778. if (!loc.AllowOverride) {
  779. XmlTextReader inner = loc.GetReader ();
  780. if (inner != null) {
  781. MoveToNextElement (inner);
  782. ReadConfig (loc.GetReader (), true);
  783. }
  784. }
  785. loc.XmlStr = null;
  786. }
  787. void StorePending (string name, XmlTextReader reader)
  788. {
  789. if (pending == null)
  790. pending = new Hashtable ();
  791. if (pending.ContainsKey (name))
  792. ThrowException ("Sections can only appear once: " + name, reader);
  793. pending [name] = reader.ReadOuterXml ();
  794. }
  795. void ReadConfig (XmlTextReader reader, bool isLocation)
  796. {
  797. int depth = reader.Depth;
  798. while (!reader.EOF && reader.Depth == depth) {
  799. string name = reader.Name;
  800. if (name == "configSections") {
  801. if (isLocation)
  802. ThrowException ("<configSections> inside <location>", reader);
  803. if (reader.HasAttributes)
  804. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  805. MoveToNextElement (reader);
  806. if (reader.Depth > depth)
  807. ReadSections (reader, null);
  808. } else if (name == "location") {
  809. if (isLocation)
  810. ThrowException ("<location> inside <location>", reader);
  811. StoreLocation (name, reader);
  812. MoveToNextElement (reader);
  813. } else if (name != null && name != ""){
  814. StorePending (name, reader);
  815. MoveToNextElement (reader);
  816. } else {
  817. MoveToNextElement (reader);
  818. }
  819. }
  820. }
  821. void ThrowException (string text, XmlTextReader reader)
  822. {
  823. throw new ConfigurationException (text, fileName, reader.LineNumber);
  824. }
  825. }
  826. class Location
  827. {
  828. string path;
  829. bool allowOverride;
  830. ConfigurationData parent;
  831. ConfigurationData thisOne;
  832. string xmlstr;
  833. public Location (ConfigurationData parent, string path, bool allowOverride)
  834. {
  835. this.parent = parent;
  836. this.allowOverride = allowOverride;
  837. this.path = (path == null || path == "") ? "*" : path;
  838. }
  839. public bool AllowOverride {
  840. get { return (path != "*" || allowOverride); }
  841. }
  842. public string Path {
  843. get { return path; }
  844. }
  845. public string XmlStr {
  846. set { xmlstr = value; }
  847. }
  848. public void LoadFromString (string str)
  849. {
  850. if (str == null)
  851. throw new ArgumentNullException ("str");
  852. if (thisOne != null)
  853. throw new InvalidOperationException ();
  854. this.xmlstr = str.Trim ();
  855. if (xmlstr == "")
  856. return;
  857. XmlTextReader reader = GetReader ();
  858. thisOne = new ConfigurationData (parent, parent.FileName);
  859. thisOne.LoadFromReader (reader, parent.FileName, true);
  860. }
  861. public XmlTextReader GetReader ()
  862. {
  863. if (xmlstr == "")
  864. return null;
  865. XmlTextReader reader = new XmlTextReader (new StringReader (xmlstr));
  866. reader.ReadStartElement ("location");
  867. return reader;
  868. }
  869. public ConfigurationData Config {
  870. get { return thisOne; }
  871. }
  872. }
  873. }