SecurityElement.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.s
  4. using System.Collections;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Text;
  9. namespace System.Security
  10. {
  11. #if PROJECTN
  12. [Internal.Runtime.CompilerServices.RelocatedType("System.Runtime.Extensions")]
  13. #endif
  14. internal interface ISecurityElementFactory
  15. {
  16. SecurityElement CreateSecurityElement();
  17. object Copy();
  18. string GetTag();
  19. string? Attribute(string attributeName);
  20. }
  21. #if PROJECTN
  22. [Internal.Runtime.CompilerServices.RelocatedType("System.Runtime.Extensions")]
  23. #endif
  24. public sealed class SecurityElement : ISecurityElementFactory
  25. {
  26. internal string _tag = null!;
  27. internal string? _text;
  28. private ArrayList? _children;
  29. internal ArrayList? _attributes;
  30. private const int AttributesTypical = 4 * 2; // 4 attributes, times 2 strings per attribute
  31. private const int ChildrenTypical = 1;
  32. private const string Indent = " ";
  33. private static readonly char[] s_tagIllegalCharacters = new char[] { ' ', '<', '>' };
  34. private static readonly char[] s_textIllegalCharacters = new char[] { '<', '>' };
  35. private static readonly char[] s_valueIllegalCharacters = new char[] { '<', '>', '\"' };
  36. private static readonly char[] s_escapeChars = new char[] { '<', '>', '\"', '\'', '&' };
  37. private static readonly string[] s_escapeStringPairs = new string[]
  38. {
  39. // these must be all once character escape sequences or a new escaping algorithm is needed
  40. "<", "&lt;",
  41. ">", "&gt;",
  42. "\"", "&quot;",
  43. "\'", "&apos;",
  44. "&", "&amp;"
  45. };
  46. //-------------------------- Constructors ---------------------------
  47. internal SecurityElement()
  48. {
  49. }
  50. public SecurityElement(string tag)
  51. {
  52. if (tag == null)
  53. throw new ArgumentNullException(nameof(tag));
  54. if (!IsValidTag(tag))
  55. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag));
  56. _tag = tag;
  57. _text = null;
  58. }
  59. public SecurityElement(string tag, string? text)
  60. {
  61. if (tag == null)
  62. throw new ArgumentNullException(nameof(tag));
  63. if (!IsValidTag(tag))
  64. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag));
  65. if (text != null && !IsValidText(text))
  66. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementText, text));
  67. _tag = tag;
  68. _text = text;
  69. }
  70. //-------------------------- Properties -----------------------------
  71. public string Tag
  72. {
  73. get
  74. {
  75. return _tag;
  76. }
  77. set
  78. {
  79. if (value == null)
  80. throw new ArgumentNullException(nameof(Tag));
  81. if (!IsValidTag(value))
  82. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, value));
  83. _tag = value;
  84. }
  85. }
  86. public Hashtable? Attributes
  87. {
  88. get
  89. {
  90. if (_attributes == null || _attributes.Count == 0)
  91. {
  92. return null;
  93. }
  94. else
  95. {
  96. Hashtable hashtable = new Hashtable(_attributes.Count / 2);
  97. int iMax = _attributes.Count;
  98. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  99. for (int i = 0; i < iMax; i += 2)
  100. {
  101. hashtable.Add(_attributes[i]!, _attributes[i + 1]);
  102. }
  103. return hashtable;
  104. }
  105. }
  106. set
  107. {
  108. if (value == null || value.Count == 0)
  109. {
  110. _attributes = null;
  111. }
  112. else
  113. {
  114. ArrayList list = new ArrayList(value.Count);
  115. IDictionaryEnumerator enumerator = value.GetEnumerator();
  116. while (enumerator.MoveNext())
  117. {
  118. string attrName = (string)enumerator.Key;
  119. string? attrValue = (string?)enumerator.Value;
  120. if (!IsValidAttributeName(attrName))
  121. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, attrName));
  122. if (!IsValidAttributeValue(attrValue))
  123. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementValue, attrValue));
  124. list.Add(attrName);
  125. list.Add(attrValue);
  126. }
  127. _attributes = list;
  128. }
  129. }
  130. }
  131. public string? Text
  132. {
  133. get
  134. {
  135. return Unescape(_text);
  136. }
  137. set
  138. {
  139. if (value == null)
  140. {
  141. _text = null;
  142. }
  143. else
  144. {
  145. if (!IsValidText(value))
  146. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, value));
  147. _text = value;
  148. }
  149. }
  150. }
  151. public ArrayList? Children
  152. {
  153. get
  154. {
  155. ConvertSecurityElementFactories();
  156. return _children;
  157. }
  158. set
  159. {
  160. if (value != null && value.Contains(null))
  161. {
  162. throw new ArgumentException(SR.ArgumentNull_Child);
  163. }
  164. _children = value;
  165. }
  166. }
  167. internal void ConvertSecurityElementFactories()
  168. {
  169. if (_children == null)
  170. return;
  171. for (int i = 0; i < _children.Count; ++i)
  172. {
  173. ISecurityElementFactory? iseFactory = _children[i] as ISecurityElementFactory;
  174. if (iseFactory != null && !(_children[i] is SecurityElement))
  175. _children[i] = iseFactory.CreateSecurityElement();
  176. }
  177. }
  178. //-------------------------- Public Methods -----------------------------
  179. internal void AddAttributeSafe(string name, string value)
  180. {
  181. if (_attributes == null)
  182. {
  183. _attributes = new ArrayList(AttributesTypical);
  184. }
  185. else
  186. {
  187. int iMax = _attributes.Count;
  188. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  189. for (int i = 0; i < iMax; i += 2)
  190. {
  191. string? strAttrName = (string?)_attributes[i];
  192. if (string.Equals(strAttrName, name))
  193. throw new ArgumentException(SR.Argument_AttributeNamesMustBeUnique);
  194. }
  195. }
  196. _attributes.Add(name);
  197. _attributes.Add(value);
  198. }
  199. public void AddAttribute(string name, string value)
  200. {
  201. if (name == null)
  202. throw new ArgumentNullException(nameof(name));
  203. if (value == null)
  204. throw new ArgumentNullException(nameof(value));
  205. if (!IsValidAttributeName(name))
  206. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, name));
  207. if (!IsValidAttributeValue(value))
  208. throw new ArgumentException(SR.Format(SR.Argument_InvalidElementValue, value));
  209. AddAttributeSafe(name, value);
  210. }
  211. public void AddChild(SecurityElement child)
  212. {
  213. if (child == null)
  214. throw new ArgumentNullException(nameof(child));
  215. if (_children == null)
  216. _children = new ArrayList(ChildrenTypical);
  217. _children.Add(child);
  218. }
  219. public bool Equal(SecurityElement? other)
  220. {
  221. if (other == null)
  222. return false;
  223. // Check if the tags are the same
  224. if (!string.Equals(_tag, other._tag))
  225. return false;
  226. // Check if the text is the same
  227. if (!string.Equals(_text, other._text))
  228. return false;
  229. // Check if the attributes are the same and appear in the same
  230. // order.
  231. if (_attributes == null || other._attributes == null)
  232. {
  233. if (_attributes != other._attributes)
  234. return false;
  235. }
  236. else
  237. {
  238. int iMax = _attributes.Count;
  239. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  240. // Maybe we can get away by only checking the number of attributes
  241. if (iMax != other._attributes.Count)
  242. return false;
  243. for (int i = 0; i < iMax; i++)
  244. {
  245. string? lhs = (string?)_attributes[i];
  246. string? rhs = (string?)other._attributes[i];
  247. if (!string.Equals(lhs, rhs))
  248. return false;
  249. }
  250. }
  251. // Finally we must check the child and make sure they are
  252. // equal and in the same order
  253. if (_children == null || other._children == null)
  254. {
  255. if (_children != other._children)
  256. return false;
  257. }
  258. else
  259. {
  260. // Maybe we can get away by only checking the number of children
  261. if (_children.Count != other._children.Count)
  262. return false;
  263. ConvertSecurityElementFactories();
  264. other.ConvertSecurityElementFactories();
  265. IEnumerator lhs = _children.GetEnumerator();
  266. IEnumerator rhs = other._children.GetEnumerator();
  267. SecurityElement? e1, e2;
  268. while (lhs.MoveNext())
  269. {
  270. rhs.MoveNext();
  271. e1 = (SecurityElement?)lhs.Current;
  272. e2 = (SecurityElement?)rhs.Current;
  273. if (e1 == null || !e1.Equal(e2))
  274. return false;
  275. }
  276. }
  277. return true;
  278. }
  279. public SecurityElement Copy()
  280. {
  281. SecurityElement element = new SecurityElement(_tag, _text);
  282. element._children = _children == null ? null : new ArrayList(_children);
  283. element._attributes = _attributes == null ? null : new ArrayList(_attributes);
  284. return element;
  285. }
  286. public static bool IsValidTag(string? tag)
  287. {
  288. if (tag == null)
  289. return false;
  290. return tag.IndexOfAny(s_tagIllegalCharacters) == -1;
  291. }
  292. public static bool IsValidText(string? text)
  293. {
  294. if (text == null)
  295. return false;
  296. return text.IndexOfAny(s_textIllegalCharacters) == -1;
  297. }
  298. public static bool IsValidAttributeName(string? name)
  299. {
  300. return IsValidTag(name);
  301. }
  302. public static bool IsValidAttributeValue(string? value)
  303. {
  304. if (value == null)
  305. return false;
  306. return value.IndexOfAny(s_valueIllegalCharacters) == -1;
  307. }
  308. private static string GetEscapeSequence(char c)
  309. {
  310. int iMax = s_escapeStringPairs.Length;
  311. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  312. for (int i = 0; i < iMax; i += 2)
  313. {
  314. string strEscSeq = s_escapeStringPairs[i];
  315. string strEscValue = s_escapeStringPairs[i + 1];
  316. if (strEscSeq[0] == c)
  317. return strEscValue;
  318. }
  319. Debug.Fail("Unable to find escape sequence for this character");
  320. return c.ToString();
  321. }
  322. public static string? Escape(string? str)
  323. {
  324. if (str == null)
  325. return null;
  326. StringBuilder? sb = null;
  327. int strLen = str.Length;
  328. int index; // Pointer into the string that indicates the location of the current '&' character
  329. int newIndex = 0; // Pointer into the string that indicates the start index of the "remaining" string (that still needs to be processed).
  330. while (true)
  331. {
  332. index = str.IndexOfAny(s_escapeChars, newIndex);
  333. if (index == -1)
  334. {
  335. if (sb == null)
  336. return str;
  337. else
  338. {
  339. sb.Append(str, newIndex, strLen - newIndex);
  340. return sb.ToString();
  341. }
  342. }
  343. else
  344. {
  345. if (sb == null)
  346. sb = new StringBuilder();
  347. sb.Append(str, newIndex, index - newIndex);
  348. sb.Append(GetEscapeSequence(str[index]));
  349. newIndex = (index + 1);
  350. }
  351. }
  352. // no normal exit is possible
  353. }
  354. private static string GetUnescapeSequence(string str, int index, out int newIndex)
  355. {
  356. int maxCompareLength = str.Length - index;
  357. int iMax = s_escapeStringPairs.Length;
  358. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  359. for (int i = 0; i < iMax; i += 2)
  360. {
  361. string strEscSeq = s_escapeStringPairs[i];
  362. string strEscValue = s_escapeStringPairs[i + 1];
  363. int length = strEscValue.Length;
  364. if (length <= maxCompareLength && string.Compare(strEscValue, 0, str, index, length, StringComparison.Ordinal) == 0)
  365. {
  366. newIndex = index + strEscValue.Length;
  367. return strEscSeq;
  368. }
  369. }
  370. newIndex = index + 1;
  371. return str[index].ToString();
  372. }
  373. private static string? Unescape(string? str)
  374. {
  375. if (str == null)
  376. return null;
  377. StringBuilder? sb = null;
  378. int strLen = str.Length;
  379. int index; // Pointer into the string that indicates the location of the current '&' character
  380. int newIndex = 0; // Pointer into the string that indicates the start index of the "remainging" string (that still needs to be processed).
  381. do
  382. {
  383. index = str.IndexOf('&', newIndex);
  384. if (index == -1)
  385. {
  386. if (sb == null)
  387. return str;
  388. else
  389. {
  390. sb.Append(str, newIndex, strLen - newIndex);
  391. return sb.ToString();
  392. }
  393. }
  394. else
  395. {
  396. if (sb == null)
  397. sb = new StringBuilder();
  398. sb.Append(str, newIndex, index - newIndex);
  399. sb.Append(GetUnescapeSequence(str, index, out newIndex)); // updates the newIndex too
  400. }
  401. }
  402. while (true);
  403. }
  404. public override string ToString()
  405. {
  406. StringBuilder sb = new StringBuilder();
  407. ToString("", sb, (obj, str) => ((StringBuilder)obj).Append(str));
  408. return sb.ToString();
  409. }
  410. private void ToString(string indent, object obj, Action<object, string?> write)
  411. {
  412. write(obj, "<");
  413. write(obj, _tag);
  414. // If there are any attributes, plop those in.
  415. if (_attributes != null && _attributes.Count > 0)
  416. {
  417. write(obj, " ");
  418. int iMax = _attributes.Count;
  419. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  420. for (int i = 0; i < iMax; i += 2)
  421. {
  422. string? strAttrName = (string?)_attributes[i];
  423. string? strAttrValue = (string?)_attributes[i + 1];
  424. write(obj, strAttrName);
  425. write(obj, "=\"");
  426. write(obj, strAttrValue);
  427. write(obj, "\"");
  428. if (i != _attributes.Count - 2)
  429. {
  430. write(obj, Environment.NewLine);
  431. }
  432. }
  433. }
  434. if (_text == null && (_children == null || _children.Count == 0))
  435. {
  436. // If we are a single tag with no children, just add the end of tag text.
  437. write(obj, "/>");
  438. write(obj, Environment.NewLine);
  439. }
  440. else
  441. {
  442. // Close the current tag.
  443. write(obj, ">");
  444. // Output the text
  445. write(obj, _text);
  446. // Output any children.
  447. if (_children != null)
  448. {
  449. ConvertSecurityElementFactories();
  450. write(obj, Environment.NewLine);
  451. for (int i = 0; i < _children.Count; ++i)
  452. {
  453. ((SecurityElement)_children[i]!).ToString(string.Empty, obj, write);
  454. }
  455. }
  456. // Output the closing tag
  457. write(obj, "</");
  458. write(obj, _tag);
  459. write(obj, ">");
  460. write(obj, Environment.NewLine);
  461. }
  462. }
  463. public string? Attribute(string name)
  464. {
  465. if (name == null)
  466. throw new ArgumentNullException(nameof(name));
  467. // Note: we don't check for validity here because an
  468. // if an invalid name is passed we simply won't find it.
  469. if (_attributes == null)
  470. return null;
  471. // Go through all the attribute and see if we know about
  472. // the one we are asked for
  473. int iMax = _attributes.Count;
  474. Debug.Assert(iMax % 2 == 0, "Odd number of strings means the attr/value pairs were not added correctly");
  475. for (int i = 0; i < iMax; i += 2)
  476. {
  477. string? strAttrName = (string?)_attributes[i];
  478. if (string.Equals(strAttrName, name))
  479. {
  480. string? strAttrValue = (string?)_attributes[i + 1];
  481. return Unescape(strAttrValue);
  482. }
  483. }
  484. // In the case where we didn't find it, we are expected to
  485. // return null
  486. return null;
  487. }
  488. public SecurityElement? SearchForChildByTag(string tag)
  489. {
  490. // Go through all the children and see if we can
  491. // find the ones that are asked for (matching tags)
  492. if (tag == null)
  493. throw new ArgumentNullException(nameof(tag));
  494. // Note: we don't check for a valid tag here because
  495. // an invalid tag simply won't be found.
  496. if (_children == null)
  497. return null;
  498. foreach (SecurityElement? current in _children)
  499. {
  500. if (current != null && string.Equals(current.Tag, tag))
  501. return current;
  502. }
  503. return null;
  504. }
  505. public string? SearchForTextOfTag(string tag)
  506. {
  507. // Search on each child in order and each
  508. // child's child, depth-first
  509. if (tag == null)
  510. throw new ArgumentNullException(nameof(tag));
  511. // Note: we don't check for a valid tag here because
  512. // an invalid tag simply won't be found.
  513. if (string.Equals(_tag, tag))
  514. return Unescape(_text);
  515. if (_children == null)
  516. return null;
  517. foreach (SecurityElement? child in Children!)
  518. {
  519. string? text = child?.SearchForTextOfTag(tag);
  520. if (text != null)
  521. return text;
  522. }
  523. return null;
  524. }
  525. public static SecurityElement? FromString(string xml)
  526. {
  527. if (xml == null)
  528. throw new ArgumentNullException(nameof(xml));
  529. return default(SecurityElement);
  530. }
  531. //--------------- ISecurityElementFactory implementation -----------------
  532. SecurityElement ISecurityElementFactory.CreateSecurityElement()
  533. {
  534. return this;
  535. }
  536. string ISecurityElementFactory.GetTag()
  537. {
  538. return ((SecurityElement)this).Tag;
  539. }
  540. object ISecurityElementFactory.Copy()
  541. {
  542. return ((SecurityElement)this).Copy();
  543. }
  544. string? ISecurityElementFactory.Attribute(string attributeName)
  545. {
  546. return ((SecurityElement)this).Attribute(attributeName);
  547. }
  548. }
  549. }