WebConfigurationSettings.cs 27 KB

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