DTDObjectModel.cs 26 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. //
  2. // Mono.Xml.DTDObjectModel
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2003 Atsushi Enomoto
  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.Collections;
  31. //using System.Collections.Specialized;
  32. using System.Globalization;
  33. using System.IO;
  34. using System.Text;
  35. using System.Xml;
  36. using System.Xml.Schema;
  37. using Mono.Xml.Schema;
  38. namespace Mono.Xml
  39. {
  40. internal class DTDObjectModel
  41. {
  42. // This specifies the max number of dependent external entities
  43. // per a DTD can consume. A malicious external document server
  44. // might send users' document processing server a large number
  45. // of external entities.
  46. public const int AllowedExternalEntitiesMax = 256;
  47. DTDAutomataFactory factory;
  48. DTDElementAutomata rootAutomata;
  49. DTDEmptyAutomata emptyAutomata;
  50. DTDAnyAutomata anyAutomata;
  51. DTDInvalidAutomata invalidAutomata;
  52. DTDElementDeclarationCollection elementDecls;
  53. DTDAttListDeclarationCollection attListDecls;
  54. DTDParameterEntityDeclarationCollection peDecls;
  55. DTDEntityDeclarationCollection entityDecls;
  56. DTDNotationDeclarationCollection notationDecls;
  57. ArrayList validationErrors;
  58. XmlResolver resolver;
  59. XmlNameTable nameTable;
  60. Hashtable externalResources;
  61. string baseURI;
  62. string name;
  63. string publicId;
  64. string systemId;
  65. string intSubset;
  66. bool intSubsetHasPERef;
  67. bool isStandalone;
  68. int lineNumber;
  69. int linePosition;
  70. public DTDObjectModel (XmlNameTable nameTable)
  71. {
  72. this.nameTable = nameTable;
  73. elementDecls = new DTDElementDeclarationCollection (this);
  74. attListDecls = new DTDAttListDeclarationCollection (this);
  75. entityDecls = new DTDEntityDeclarationCollection (this);
  76. peDecls = new DTDParameterEntityDeclarationCollection (this);
  77. notationDecls = new DTDNotationDeclarationCollection (this);
  78. factory = new DTDAutomataFactory (this);
  79. validationErrors = new ArrayList ();
  80. externalResources = new Hashtable ();
  81. }
  82. public string BaseURI {
  83. get { return baseURI; }
  84. set { baseURI = value; }
  85. }
  86. public bool IsStandalone {
  87. get { return isStandalone; }
  88. set { isStandalone = value; }
  89. }
  90. public string Name {
  91. get { return name; }
  92. set { name = value; }
  93. }
  94. public XmlNameTable NameTable {
  95. get { return nameTable; }
  96. }
  97. public string PublicId {
  98. get { return publicId; }
  99. set { publicId = value; }
  100. }
  101. public string SystemId {
  102. get { return systemId; }
  103. set { systemId = value; }
  104. }
  105. public string InternalSubset {
  106. get { return intSubset; }
  107. set { intSubset = value; }
  108. }
  109. public bool InternalSubsetHasPEReference {
  110. get { return intSubsetHasPERef; }
  111. set { intSubsetHasPERef = value; }
  112. }
  113. public int LineNumber {
  114. get { return lineNumber; }
  115. set { lineNumber = value; }
  116. }
  117. public int LinePosition {
  118. get { return linePosition; }
  119. set { linePosition = value; }
  120. }
  121. public string ResolveEntity (string name)
  122. {
  123. DTDEntityDeclaration decl = EntityDecls [name]
  124. as DTDEntityDeclaration;
  125. if (decl == null) {
  126. AddError (new XmlSchemaException ("Required entity was not found.",
  127. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  128. return " ";
  129. }
  130. else
  131. return decl.EntityValue;
  132. }
  133. internal XmlResolver Resolver {
  134. get { return resolver; }
  135. }
  136. public XmlResolver XmlResolver {
  137. set { resolver = value; }
  138. }
  139. internal Hashtable ExternalResources {
  140. get { return externalResources; }
  141. }
  142. public DTDAutomataFactory Factory {
  143. get { return factory; }
  144. }
  145. public DTDElementDeclaration RootElement {
  146. get { return ElementDecls [Name]; }
  147. }
  148. public DTDElementDeclarationCollection ElementDecls {
  149. get { return elementDecls; }
  150. }
  151. public DTDAttListDeclarationCollection AttListDecls {
  152. get { return attListDecls; }
  153. }
  154. public DTDEntityDeclarationCollection EntityDecls {
  155. get { return entityDecls; }
  156. }
  157. public DTDParameterEntityDeclarationCollection PEDecls {
  158. get { return peDecls; }
  159. }
  160. public DTDNotationDeclarationCollection NotationDecls {
  161. get { return notationDecls; }
  162. }
  163. public DTDAutomata RootAutomata {
  164. get {
  165. if (rootAutomata == null)
  166. rootAutomata = new DTDElementAutomata (this, this.Name);
  167. return rootAutomata;
  168. }
  169. }
  170. public DTDEmptyAutomata Empty {
  171. get {
  172. if (emptyAutomata == null)
  173. emptyAutomata = new DTDEmptyAutomata (this);
  174. return emptyAutomata;
  175. }
  176. }
  177. public DTDAnyAutomata Any {
  178. get {
  179. if (anyAutomata == null)
  180. anyAutomata = new DTDAnyAutomata (this);
  181. return anyAutomata;
  182. }
  183. }
  184. public DTDInvalidAutomata Invalid {
  185. get {
  186. if (invalidAutomata == null)
  187. invalidAutomata = new DTDInvalidAutomata (this);
  188. return invalidAutomata;
  189. }
  190. }
  191. public XmlSchemaException [] Errors {
  192. get { return validationErrors.ToArray (typeof (XmlSchemaException)) as XmlSchemaException []; }
  193. }
  194. public void AddError (XmlSchemaException ex)
  195. {
  196. validationErrors.Add (ex);
  197. }
  198. }
  199. internal class DTDCollectionBase : DictionaryBase
  200. {
  201. DTDObjectModel root;
  202. protected DTDCollectionBase (DTDObjectModel root)
  203. {
  204. this.root = root;
  205. }
  206. protected DTDObjectModel Root {
  207. get { return root; }
  208. }
  209. public ICollection Keys {
  210. get { return InnerHashtable.Keys; }
  211. }
  212. public ICollection Values {
  213. get { return InnerHashtable.Values; }
  214. }
  215. }
  216. internal class DTDElementDeclarationCollection : DTDCollectionBase
  217. {
  218. public DTDElementDeclarationCollection (DTDObjectModel root) : base (root) {}
  219. public DTDElementDeclaration this [string name] {
  220. get { return Get (name); }
  221. }
  222. public DTDElementDeclaration Get (string name)
  223. {
  224. return InnerHashtable [name] as DTDElementDeclaration;
  225. }
  226. public void Add (string name, DTDElementDeclaration decl)
  227. {
  228. if (InnerHashtable.Contains (name)) {
  229. Root.AddError (new XmlSchemaException (String.Format (
  230. "Element declaration for {0} was already added.",
  231. name), null));
  232. return;
  233. }
  234. decl.SetRoot (Root);
  235. InnerHashtable.Add (name, decl);
  236. }
  237. }
  238. internal class DTDAttListDeclarationCollection : DTDCollectionBase
  239. {
  240. public DTDAttListDeclarationCollection (DTDObjectModel root) : base (root) {}
  241. public DTDAttListDeclaration this [string name] {
  242. get { return InnerHashtable [name] as DTDAttListDeclaration; }
  243. }
  244. public void Add (string name, DTDAttListDeclaration decl)
  245. {
  246. DTDAttListDeclaration existing = this [name];
  247. if (existing != null) {
  248. // It is valid, that is additive declaration.
  249. foreach (DTDAttributeDefinition def in decl.Definitions)
  250. if (decl.Get (def.Name) == null)
  251. existing.Add (def);
  252. } else {
  253. decl.SetRoot (Root);
  254. InnerHashtable.Add (name, decl);
  255. }
  256. }
  257. }
  258. internal class DTDEntityDeclarationCollection : DTDCollectionBase
  259. {
  260. public DTDEntityDeclarationCollection (DTDObjectModel root) : base (root) {}
  261. public DTDEntityDeclaration this [string name] {
  262. get { return InnerHashtable [name] as DTDEntityDeclaration; }
  263. }
  264. public void Add (string name, DTDEntityDeclaration decl)
  265. {
  266. if (InnerHashtable [name] != null)
  267. throw new InvalidOperationException (String.Format (
  268. "Entity declaration for {0} was already added.",
  269. name));
  270. decl.SetRoot (Root);
  271. InnerHashtable.Add (name, decl);
  272. }
  273. }
  274. internal class DTDNotationDeclarationCollection : DTDCollectionBase
  275. {
  276. public DTDNotationDeclarationCollection (DTDObjectModel root) : base (root) {}
  277. public DTDNotationDeclaration this [string name] {
  278. get { return InnerHashtable [name] as DTDNotationDeclaration; }
  279. }
  280. public void Add (string name, DTDNotationDeclaration decl)
  281. {
  282. if (InnerHashtable [name] != null)
  283. throw new InvalidOperationException (String.Format (
  284. "Notation declaration for {0} was already added.",
  285. name));
  286. decl.SetRoot (Root);
  287. InnerHashtable.Add (name, decl);
  288. }
  289. }
  290. // This class contains either ElementName or ChildModels.
  291. internal class DTDContentModel : DTDNode
  292. {
  293. DTDObjectModel root;
  294. DTDAutomata compiledAutomata;
  295. string ownerElementName;
  296. string elementName;
  297. DTDContentOrderType orderType = DTDContentOrderType.None;
  298. DTDContentModelCollection childModels = new DTDContentModelCollection ();
  299. DTDOccurence occurence = DTDOccurence.One;
  300. internal DTDContentModel (DTDObjectModel root, string ownerElementName)
  301. {
  302. this.root = root;
  303. this.ownerElementName = ownerElementName;
  304. }
  305. public DTDContentModelCollection ChildModels {
  306. get { return childModels; }
  307. set { childModels = value; }
  308. }
  309. public DTDElementDeclaration ElementDecl {
  310. get { return root.ElementDecls [ownerElementName]; }
  311. }
  312. public string ElementName {
  313. get { return elementName; }
  314. set { elementName = value; }
  315. }
  316. public DTDOccurence Occurence {
  317. get { return occurence; }
  318. set { occurence = value; }
  319. }
  320. public DTDContentOrderType OrderType {
  321. get { return orderType; }
  322. set { orderType = value; }
  323. }
  324. public DTDAutomata GetAutomata ()
  325. {
  326. if (compiledAutomata == null)
  327. Compile ();
  328. return compiledAutomata;
  329. }
  330. public DTDAutomata Compile ()
  331. {
  332. compiledAutomata = CompileInternal ();
  333. return compiledAutomata;
  334. }
  335. private DTDAutomata CompileInternal ()
  336. {
  337. if (ElementDecl.IsAny)
  338. return root.Any;
  339. if (ElementDecl.IsEmpty)
  340. return root.Empty;
  341. DTDAutomata basis = GetBasicContentAutomata ();
  342. switch (Occurence) {
  343. case DTDOccurence.One:
  344. return basis;
  345. case DTDOccurence.Optional:
  346. return Choice (root.Empty, basis);
  347. case DTDOccurence.OneOrMore:
  348. return new DTDOneOrMoreAutomata (root, basis);
  349. case DTDOccurence.ZeroOrMore:
  350. return Choice (root.Empty, new DTDOneOrMoreAutomata (root, basis));
  351. }
  352. throw new InvalidOperationException ();
  353. }
  354. private DTDAutomata GetBasicContentAutomata ()
  355. {
  356. if (ElementName != null)
  357. return new DTDElementAutomata (root, ElementName);
  358. switch (ChildModels.Count) {
  359. case 0:
  360. return root.Empty;
  361. case 1:
  362. return ChildModels [0].GetAutomata ();
  363. }
  364. DTDAutomata current = null;
  365. int childCount = ChildModels.Count;
  366. switch (OrderType) {
  367. case DTDContentOrderType.Seq:
  368. current = Sequence (
  369. ChildModels [childCount - 2].GetAutomata (),
  370. ChildModels [childCount - 1].GetAutomata ());
  371. for (int i = childCount - 2; i > 0; i--)
  372. current = Sequence (
  373. ChildModels [i - 1].GetAutomata (), current);
  374. return current;
  375. case DTDContentOrderType.Or:
  376. current = Choice (
  377. ChildModels [childCount - 2].GetAutomata (),
  378. ChildModels [childCount - 1].GetAutomata ());
  379. for (int i = childCount - 2; i > 0; i--)
  380. current = Choice (
  381. ChildModels [i - 1].GetAutomata (), current);
  382. return current;
  383. default:
  384. throw new InvalidOperationException ("Invalid pattern specification");
  385. }
  386. }
  387. private DTDAutomata Sequence (DTDAutomata l, DTDAutomata r)
  388. {
  389. return root.Factory.Sequence (l, r);
  390. }
  391. private DTDAutomata Choice (DTDAutomata l, DTDAutomata r)
  392. {
  393. return l.MakeChoice (r);
  394. }
  395. }
  396. internal class DTDContentModelCollection
  397. {
  398. ArrayList contentModel = new ArrayList ();
  399. public DTDContentModelCollection ()
  400. {
  401. }
  402. public DTDContentModel this [int i] {
  403. get { return contentModel [i] as DTDContentModel; }
  404. }
  405. public int Count {
  406. get { return contentModel.Count; }
  407. }
  408. public void Add (DTDContentModel model)
  409. {
  410. contentModel.Add (model);
  411. }
  412. }
  413. internal abstract class DTDNode : IXmlLineInfo
  414. {
  415. DTDObjectModel root;
  416. bool isInternalSubset;
  417. string baseURI;
  418. int lineNumber;
  419. int linePosition;
  420. public virtual string BaseURI {
  421. get { return baseURI; }
  422. set { baseURI = value; }
  423. }
  424. public bool IsInternalSubset {
  425. get { return isInternalSubset; }
  426. set { isInternalSubset = value; }
  427. }
  428. public int LineNumber {
  429. get { return lineNumber; }
  430. set { lineNumber = value; }
  431. }
  432. public int LinePosition {
  433. get { return linePosition; }
  434. set { linePosition = value; }
  435. }
  436. public bool HasLineInfo ()
  437. {
  438. return lineNumber != 0;
  439. }
  440. internal void SetRoot (DTDObjectModel root)
  441. {
  442. this.root = root;
  443. if (baseURI == null)
  444. this.BaseURI = root.BaseURI;
  445. }
  446. protected DTDObjectModel Root {
  447. get { return root; }
  448. }
  449. }
  450. internal class DTDElementDeclaration : DTDNode
  451. {
  452. DTDObjectModel root;
  453. DTDContentModel contentModel;
  454. string name;
  455. bool isEmpty;
  456. bool isAny;
  457. bool isMixedContent;
  458. internal DTDElementDeclaration (DTDObjectModel root)
  459. {
  460. this.root = root;
  461. }
  462. public string Name {
  463. get { return name; }
  464. set { name = value; }
  465. }
  466. public bool IsEmpty {
  467. get { return isEmpty; }
  468. set { isEmpty = value; }
  469. }
  470. public bool IsAny {
  471. get { return isAny; }
  472. set { isAny = value; }
  473. }
  474. public bool IsMixedContent {
  475. get { return isMixedContent; }
  476. set { isMixedContent = value; }
  477. }
  478. public DTDContentModel ContentModel {
  479. get {
  480. if (contentModel == null)
  481. contentModel = new DTDContentModel (root, Name);
  482. return contentModel;
  483. }
  484. }
  485. public DTDAttListDeclaration Attributes {
  486. get {
  487. return Root.AttListDecls [Name];
  488. }
  489. }
  490. }
  491. internal class DTDAttributeDefinition : DTDNode
  492. {
  493. string name;
  494. XmlSchemaDatatype datatype;
  495. ArrayList enumeratedLiterals;
  496. string unresolvedDefault;
  497. ArrayList enumeratedNotations;
  498. DTDAttributeOccurenceType occurenceType = DTDAttributeOccurenceType.None;
  499. string resolvedDefaultValue;
  500. string resolvedNormalizedDefaultValue;
  501. internal DTDAttributeDefinition (DTDObjectModel root)
  502. {
  503. this.SetRoot (root);
  504. }
  505. public string Name {
  506. get { return name; }
  507. set { name =value; }
  508. }
  509. public XmlSchemaDatatype Datatype {
  510. get { return datatype; }
  511. set { datatype = value; }
  512. }
  513. public DTDAttributeOccurenceType OccurenceType {
  514. get { return this.occurenceType; }
  515. set { this.occurenceType = value; }
  516. }
  517. // entity reference inside enumerated values are not allowed,
  518. // but on the other hand, they are allowed inside default value.
  519. // Then I decided to use string ArrayList for enumerated values,
  520. // and unresolved string value for DefaultValue.
  521. public ArrayList EnumeratedAttributeDeclaration {
  522. get {
  523. if (enumeratedLiterals == null)
  524. enumeratedLiterals = new ArrayList ();
  525. return this.enumeratedLiterals;
  526. }
  527. }
  528. public ArrayList EnumeratedNotations {
  529. get {
  530. if (enumeratedNotations == null)
  531. enumeratedNotations = new ArrayList ();
  532. return this.enumeratedNotations;
  533. }
  534. }
  535. public string DefaultValue {
  536. get {
  537. if (resolvedDefaultValue == null)
  538. resolvedDefaultValue = ComputeDefaultValue ();
  539. return resolvedDefaultValue;
  540. }
  541. }
  542. public string NormalizedDefaultValue {
  543. get {
  544. if (resolvedNormalizedDefaultValue == null) {
  545. string s = ComputeDefaultValue ();
  546. try {
  547. object o = Datatype.ParseValue (s, null, null);
  548. resolvedNormalizedDefaultValue =
  549. (o is string []) ?
  550. String.Join (" ", (string []) o) :
  551. o is IFormattable ? ((IFormattable) o).ToString (null, CultureInfo.InvariantCulture) : o.ToString ();
  552. } catch (Exception) {
  553. // This is for non-error-reporting reader
  554. resolvedNormalizedDefaultValue = Datatype.Normalize (s);
  555. }
  556. }
  557. return resolvedNormalizedDefaultValue;
  558. }
  559. }
  560. public string UnresolvedDefaultValue {
  561. get { return this.unresolvedDefault; }
  562. set { this.unresolvedDefault = value; }
  563. }
  564. public char QuoteChar {
  565. get {
  566. return UnresolvedDefaultValue.Length > 0 ?
  567. this.UnresolvedDefaultValue [0] :
  568. '"';
  569. }
  570. }
  571. internal string ComputeDefaultValue ()
  572. {
  573. if (UnresolvedDefaultValue == null)
  574. return null;
  575. StringBuilder sb = new StringBuilder ();
  576. int pos = 0;
  577. int next = 0;
  578. string value = this.UnresolvedDefaultValue;
  579. while ((next = value.IndexOf ('&', pos)) >= 0) {
  580. int semicolon = value.IndexOf (';', next);
  581. if (value [next + 1] == '#') {
  582. // character reference.
  583. char c = value [next + 2];
  584. NumberStyles style = NumberStyles.Integer;
  585. string spec;
  586. if (c == 'x' || c == 'X') {
  587. spec = value.Substring (next + 3, semicolon - next - 3);
  588. style |= NumberStyles.HexNumber;
  589. }
  590. else
  591. spec = value.Substring (next + 2, semicolon - next - 2);
  592. sb.Append ((char) int.Parse (spec, style, CultureInfo.InvariantCulture));
  593. } else {
  594. sb.Append (value.Substring (pos, next - 1));
  595. string name = value.Substring (next + 1, semicolon - 2);
  596. int predefined = XmlChar.GetPredefinedEntity (name);
  597. if (predefined >= 0)
  598. sb.Append (predefined);
  599. else
  600. sb.Append (Root.ResolveEntity (name));
  601. }
  602. pos = semicolon + 1;
  603. }
  604. sb.Append (value.Substring (pos));
  605. // strip quote chars
  606. string ret = sb.ToString (1, sb.Length - 2);
  607. sb.Length = 0;
  608. return ret;
  609. }
  610. }
  611. internal class DTDAttListDeclaration : DTDNode
  612. {
  613. string name;
  614. Hashtable attributeOrders = new Hashtable ();
  615. ArrayList attributes = new ArrayList ();
  616. internal DTDAttListDeclaration (DTDObjectModel root)
  617. {
  618. SetRoot (root);
  619. }
  620. public string Name {
  621. get { return name; }
  622. set { name = value; }
  623. }
  624. public DTDAttributeDefinition this [int i] {
  625. get { return Get (i); }
  626. }
  627. public DTDAttributeDefinition this [string name] {
  628. get { return Get (name); }
  629. }
  630. public DTDAttributeDefinition Get (int i)
  631. {
  632. return attributes [i] as DTDAttributeDefinition;
  633. }
  634. public DTDAttributeDefinition Get (string name)
  635. {
  636. object o = attributeOrders [name];
  637. if (o != null)
  638. return attributes [(int) o] as DTDAttributeDefinition;
  639. else
  640. return null;
  641. }
  642. public IList Definitions {
  643. get { return attributes; }
  644. }
  645. public void Add (DTDAttributeDefinition def)
  646. {
  647. if (attributeOrders [def.Name] != null)
  648. throw new InvalidOperationException (String.Format (
  649. "Attribute definition for {0} was already added at element {1}.",
  650. def.Name, this.Name));
  651. def.SetRoot (Root);
  652. attributeOrders.Add (def.Name, attributes.Count);
  653. attributes.Add (def);
  654. }
  655. public int Count {
  656. get { return attributeOrders.Count; }
  657. }
  658. }
  659. internal class DTDEntityBase : DTDNode
  660. {
  661. string name;
  662. string publicId;
  663. string systemId;
  664. string literalValue;
  665. string replacementText;
  666. bool isInvalid;
  667. Exception loadException;
  668. bool loadFailed;
  669. protected DTDEntityBase (DTDObjectModel root)
  670. {
  671. SetRoot (root);
  672. }
  673. internal bool IsInvalid {
  674. get { return isInvalid; }
  675. set { isInvalid = value; }
  676. }
  677. public bool LoadFailed {
  678. get { return loadFailed; }
  679. set { loadFailed = value; }
  680. }
  681. public string Name {
  682. get { return name; }
  683. set { name = value; }
  684. }
  685. public string PublicId {
  686. get { return publicId; }
  687. set { publicId = value; }
  688. }
  689. public string SystemId {
  690. get { return systemId; }
  691. set { systemId = value; }
  692. }
  693. public string LiteralEntityValue {
  694. get { return literalValue; }
  695. set { literalValue = value; }
  696. }
  697. public string ReplacementText {
  698. get { return replacementText; }
  699. set { replacementText = value; }
  700. }
  701. public void Resolve (XmlResolver resolver)
  702. {
  703. if (resolver == null || SystemId == null || SystemId.Length == 0) {
  704. LoadFailed = true;
  705. LiteralEntityValue = String.Empty;
  706. return;
  707. }
  708. Uri baseUri = null;
  709. try {
  710. if (BaseURI != null && BaseURI.Length > 0)
  711. baseUri = new Uri (BaseURI);
  712. } catch (UriFormatException) {
  713. }
  714. Uri absUri = resolver.ResolveUri (baseUri, SystemId);
  715. string absPath = absUri.ToString ();
  716. if (Root.ExternalResources.ContainsKey (absPath))
  717. LiteralEntityValue = (string) Root.ExternalResources [absPath];
  718. Stream s = null;
  719. try {
  720. s = resolver.GetEntity (absUri, null, typeof (Stream)) as Stream;
  721. XmlTextReader xtr = new XmlTextReader (s);
  722. // Don't skip Text declaration here. LiteralEntityValue contains it. See spec 4.5
  723. this.BaseURI = absPath;
  724. LiteralEntityValue = xtr.GetRemainder ().ReadToEnd ();
  725. Root.ExternalResources.Add (absPath, LiteralEntityValue);
  726. if (Root.ExternalResources.Count > DTDObjectModel.AllowedExternalEntitiesMax)
  727. throw new InvalidOperationException ("The total amount of external entities exceeded the allowed number.");
  728. } catch (Exception ex) {
  729. loadException = ex;
  730. LiteralEntityValue = String.Empty;
  731. LoadFailed = true;
  732. // throw new XmlException (this, "Cannot resolve external entity. URI is " + absPath + " .");
  733. } finally {
  734. if (s != null)
  735. s.Close ();
  736. }
  737. }
  738. }
  739. internal class DTDEntityDeclaration : DTDEntityBase
  740. {
  741. string entityValue;
  742. string notationName;
  743. ArrayList ReferencingEntities = new ArrayList ();
  744. bool scanned;
  745. bool recursed;
  746. bool hasExternalReference;
  747. internal DTDEntityDeclaration (DTDObjectModel root) : base (root)
  748. {
  749. }
  750. public string NotationName {
  751. get { return notationName; }
  752. set { notationName = value; }
  753. }
  754. public bool HasExternalReference {
  755. get {
  756. if (!scanned)
  757. ScanEntityValue (new ArrayList ());
  758. return hasExternalReference;
  759. }
  760. }
  761. public string EntityValue {
  762. get {
  763. if (this.IsInvalid)
  764. return String.Empty;
  765. if (PublicId == null && SystemId == null && LiteralEntityValue == null)
  766. return String.Empty;
  767. if (entityValue == null) {
  768. if (NotationName != null)
  769. entityValue = "";
  770. else if (SystemId == null || SystemId == String.Empty) {
  771. entityValue = ReplacementText;
  772. if (entityValue == null)
  773. entityValue = String.Empty;
  774. } else {
  775. entityValue = ReplacementText;
  776. }
  777. // Check illegal recursion.
  778. ScanEntityValue (new ArrayList ());
  779. }
  780. return entityValue;
  781. }
  782. }
  783. // It returns whether the entity contains references to external entities.
  784. public void ScanEntityValue (ArrayList refs)
  785. {
  786. // To modify this code, beware nesting between this and EntityValue.
  787. string value = EntityValue;
  788. if (this.SystemId != null)
  789. hasExternalReference = true;
  790. if (recursed)
  791. throw new XmlException ("Entity recursion was found.");
  792. recursed = true;
  793. if (scanned) {
  794. foreach (string referenced in refs)
  795. if (this.ReferencingEntities.Contains (referenced))
  796. throw new XmlException (String.Format (
  797. "Nested entity was found between {0} and {1}",
  798. referenced, Name));
  799. recursed = false;
  800. return;
  801. }
  802. int len = value.Length;
  803. int start = 0;
  804. for (int i=0; i<len; i++) {
  805. switch (value [i]) {
  806. case '&':
  807. start = i+1;
  808. break;
  809. case ';':
  810. if (start == 0)
  811. break;
  812. string name = value.Substring (start, i - start);
  813. if (name.Length == 0)
  814. throw new XmlException (this as IXmlLineInfo, "Entity reference name is missing.");
  815. if (name [0] == '#')
  816. break; // character reference
  817. if (XmlChar.GetPredefinedEntity (name) >= 0)
  818. break; // predefined reference
  819. this.ReferencingEntities.Add (name);
  820. DTDEntityDeclaration decl = Root.EntityDecls [name];
  821. if (decl != null) {
  822. if (decl.SystemId != null)
  823. hasExternalReference = true;
  824. refs.Add (Name);
  825. decl.ScanEntityValue (refs);
  826. foreach (string str in decl.ReferencingEntities)
  827. ReferencingEntities.Add (str);
  828. refs.Remove (Name);
  829. value = value.Remove (start - 1, name.Length + 2);
  830. value = value.Insert (start - 1, decl.EntityValue);
  831. i -= name.Length + 1; // not +2, because of immediate i++ .
  832. len = value.Length;
  833. }
  834. start = 0;
  835. break;
  836. }
  837. }
  838. if (start != 0)
  839. Root.AddError (new XmlSchemaException ("Invalid reference character '&' is specified.",
  840. this.LineNumber, this.LinePosition, null, this.BaseURI, null));
  841. scanned = true;
  842. recursed = false;
  843. }
  844. }
  845. internal class DTDNotationDeclaration : DTDNode
  846. {
  847. string name;
  848. string localName;
  849. string prefix;
  850. string publicId;
  851. string systemId;
  852. public string Name {
  853. get { return name; }
  854. set { name = value; }
  855. }
  856. public string PublicId {
  857. get { return publicId; }
  858. set { publicId = value; }
  859. }
  860. public string SystemId {
  861. get { return systemId; }
  862. set { systemId = value; }
  863. }
  864. public string LocalName {
  865. get { return localName; }
  866. set { localName = value; }
  867. }
  868. public string Prefix {
  869. get { return prefix; }
  870. set { prefix = value; }
  871. }
  872. internal DTDNotationDeclaration (DTDObjectModel root)
  873. {
  874. SetRoot (root);
  875. }
  876. }
  877. internal class DTDParameterEntityDeclarationCollection
  878. {
  879. Hashtable peDecls = new Hashtable ();
  880. DTDObjectModel root;
  881. public DTDParameterEntityDeclarationCollection (DTDObjectModel root)
  882. {
  883. this.root = root;
  884. }
  885. public DTDParameterEntityDeclaration this [string name] {
  886. get { return peDecls [name] as DTDParameterEntityDeclaration; }
  887. }
  888. public void Add (string name, DTDParameterEntityDeclaration decl)
  889. {
  890. // PEDecl can be overriden.
  891. if (peDecls [name] != null)
  892. return;
  893. decl.SetRoot (root);
  894. peDecls.Add (name, decl);
  895. }
  896. public ICollection Keys {
  897. get { return peDecls.Keys; }
  898. }
  899. public ICollection Values {
  900. get { return peDecls.Values; }
  901. }
  902. }
  903. internal class DTDParameterEntityDeclaration : DTDEntityBase
  904. {
  905. internal DTDParameterEntityDeclaration (DTDObjectModel root) : base (root)
  906. {
  907. }
  908. }
  909. internal enum DTDContentOrderType
  910. {
  911. None,
  912. Seq,
  913. Or
  914. }
  915. internal enum DTDAttributeOccurenceType
  916. {
  917. None,
  918. Required,
  919. Optional,
  920. Fixed
  921. }
  922. internal enum DTDOccurence
  923. {
  924. One,
  925. Optional,
  926. ZeroOrMore,
  927. OneOrMore
  928. }
  929. }