WebConfigurationSettings.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. string value = null;
  675. #if CONFIGURATION_2_0
  676. do {
  677. if (reader.Name == "name") {
  678. if (value != null)
  679. ThrowException ("Duplicate 'name' attribute.", reader);
  680. value = reader.Value;
  681. }
  682. else if (reader.Name != "type")
  683. ThrowException ("Unrecognized attribute.", reader);
  684. } while (reader.MoveToNextAttribute ());
  685. #else
  686. if (reader.Name != "name")
  687. ThrowException ("Unrecognized attribute.", reader);
  688. if (reader.MoveToNextAttribute ())
  689. ThrowException ("Unrecognized attribute.", reader);
  690. value = reader.Value;
  691. #endif
  692. if (value == null)
  693. ThrowException ("No 'name' attribute.", reader);
  694. if (value == "location")
  695. ThrowException ("location is a reserved section name", reader);
  696. if (configSection != null)
  697. value = configSection + '/' + value;
  698. object o = LookForFactory (value);
  699. if (o != null && o != removedMark && o != groupMark)
  700. ThrowException ("Already have a factory for " + value, reader);
  701. factories [value] = groupMark;
  702. MoveToNextElement (reader);
  703. ReadSections (reader, value);
  704. }
  705. private void ReadSections (XmlTextReader reader, string configSection)
  706. {
  707. int depth = reader.Depth;
  708. while (reader.Depth == depth) {
  709. string name = reader.Name;
  710. if (name == "section") {
  711. ReadSection (reader, configSection);
  712. continue;
  713. }
  714. if (name == "remove") {
  715. ReadRemoveSection (reader, configSection);
  716. continue;
  717. }
  718. if (name == "clear") {
  719. if (reader.HasAttributes)
  720. ThrowException ("Unrecognized attribute.", reader);
  721. factories.Clear ();
  722. MoveToNextElement (reader);
  723. continue;
  724. }
  725. if (name == "sectionGroup") {
  726. ReadSectionGroup (reader, configSection);
  727. continue;
  728. }
  729. ThrowException ("Unrecognized element: " + reader.Name, reader);
  730. }
  731. }
  732. void StoreLocation (string name, XmlTextReader reader)
  733. {
  734. string path = null;
  735. bool haveAllow = false;
  736. bool allowOverride = true;
  737. string att = null;
  738. while (reader.MoveToNextAttribute ()) {
  739. att = reader.Name;
  740. if (att == "path") {
  741. if (path != null)
  742. ThrowException ("Duplicate path attribute", reader);
  743. path = reader.Value;
  744. if (path.StartsWith ("."))
  745. ThrowException ("Path cannot begin with '.'", reader);
  746. if (path.IndexOfAny (forbiddenPathChars) != -1)
  747. ThrowException ("Path cannot contain " + forbiddenStr, reader);
  748. continue;
  749. }
  750. if (att == "allowOverride") {
  751. if (haveAllow)
  752. ThrowException ("Duplicate allowOverride attribute", reader);
  753. haveAllow = true;
  754. allowOverride = (reader.Value == "true");
  755. if (!allowOverride && reader.Value != "false")
  756. ThrowException ("allowOverride must be either true or false", reader);
  757. continue;
  758. }
  759. ThrowException ("Unrecognized attribute.", reader);
  760. }
  761. if (att == null)
  762. return; // empty location tag
  763. Location loc = new Location (this, path, allowOverride);
  764. if (locations == null)
  765. locations = new Hashtable ();
  766. else if (locations.ContainsKey (loc.Path))
  767. ThrowException ("Duplicated location path: " + loc.Path, reader);
  768. reader.MoveToElement ();
  769. loc.LoadFromString (reader.ReadInnerXml ());
  770. locations [loc.Path] = loc;
  771. if (!loc.AllowOverride) {
  772. XmlTextReader inner = loc.GetReader ();
  773. if (inner != null) {
  774. MoveToNextElement (inner);
  775. ReadConfig (loc.GetReader (), true);
  776. }
  777. }
  778. loc.XmlStr = null;
  779. }
  780. void StorePending (string name, XmlTextReader reader)
  781. {
  782. if (pending == null)
  783. pending = new Hashtable ();
  784. if (pending.ContainsKey (name))
  785. ThrowException ("Sections can only appear once: " + name, reader);
  786. pending [name] = reader.ReadOuterXml ();
  787. }
  788. void ReadConfig (XmlTextReader reader, bool isLocation)
  789. {
  790. int depth = reader.Depth;
  791. while (!reader.EOF && reader.Depth == depth) {
  792. string name = reader.Name;
  793. if (name == "configSections") {
  794. if (isLocation)
  795. ThrowException ("<configSections> inside <location>", reader);
  796. if (reader.HasAttributes)
  797. ThrowException ("Unrecognized attribute in <configSections>.", reader);
  798. MoveToNextElement (reader);
  799. if (reader.Depth > depth)
  800. ReadSections (reader, null);
  801. } else if (name == "location") {
  802. if (isLocation)
  803. ThrowException ("<location> inside <location>", reader);
  804. StoreLocation (name, reader);
  805. MoveToNextElement (reader);
  806. } else if (name != null && name != ""){
  807. StorePending (name, reader);
  808. MoveToNextElement (reader);
  809. } else {
  810. MoveToNextElement (reader);
  811. }
  812. }
  813. }
  814. void ThrowException (string text, XmlTextReader reader)
  815. {
  816. throw new ConfigurationException (text, fileName, reader.LineNumber);
  817. }
  818. }
  819. class Location
  820. {
  821. string path;
  822. bool allowOverride;
  823. ConfigurationData parent;
  824. ConfigurationData thisOne;
  825. string xmlstr;
  826. public Location (ConfigurationData parent, string path, bool allowOverride)
  827. {
  828. this.parent = parent;
  829. this.allowOverride = allowOverride;
  830. this.path = (path == null || path == "") ? "*" : path;
  831. }
  832. public bool AllowOverride {
  833. get { return (path != "*" || allowOverride); }
  834. }
  835. public string Path {
  836. get { return path; }
  837. }
  838. public string XmlStr {
  839. set { xmlstr = value; }
  840. }
  841. public void LoadFromString (string str)
  842. {
  843. if (str == null)
  844. throw new ArgumentNullException ("str");
  845. if (thisOne != null)
  846. throw new InvalidOperationException ();
  847. this.xmlstr = str.Trim ();
  848. if (xmlstr == "")
  849. return;
  850. XmlTextReader reader = new XmlTextReader (new StringReader (str));
  851. thisOne = new ConfigurationData (parent, parent.FileName);
  852. thisOne.LoadFromReader (reader, parent.FileName, true);
  853. }
  854. public XmlTextReader GetReader ()
  855. {
  856. if (xmlstr == "")
  857. return null;
  858. XmlTextReader reader = new XmlTextReader (new StringReader (xmlstr));
  859. return reader;
  860. }
  861. public ConfigurationData Config {
  862. get { return thisOne; }
  863. }
  864. }
  865. }