SecurityElement.cs 21 KB

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