WebConfigurationSettings.cs 27 KB

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