XmlMtomDictionaryReader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. //
  2. // XmlMtomDictionaryReader.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2009 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. using System;
  29. using System.Collections.Generic;
  30. using System.IO;
  31. using System.Net.Mime;
  32. using System.Reflection;
  33. using System.Text;
  34. using System.Xml;
  35. namespace System.Xml
  36. {
  37. internal class XmlMtomDictionaryReader : XmlDictionaryReader
  38. {
  39. public XmlMtomDictionaryReader (
  40. Stream stream, Encoding encoding,
  41. XmlDictionaryReaderQuotas quotas)
  42. {
  43. this.stream = stream;
  44. this.encoding = encoding;
  45. this.quotas = quotas;
  46. Initialize ();
  47. }
  48. public XmlMtomDictionaryReader (
  49. Stream stream, Encoding [] encodings, string contentType,
  50. XmlDictionaryReaderQuotas quotas,
  51. int maxBufferSize,
  52. OnXmlDictionaryReaderClose onClose)
  53. {
  54. this.stream = stream;
  55. this.encodings = encodings;
  56. content_type = contentType != null ? CreateContentType (contentType) : null;
  57. this.quotas = quotas;
  58. this.max_buffer_size = maxBufferSize;
  59. on_close = onClose;
  60. Initialize ();
  61. }
  62. Stream stream;
  63. Encoding encoding;
  64. Encoding [] encodings;
  65. ContentType content_type;
  66. XmlDictionaryReaderQuotas quotas;
  67. int max_buffer_size;
  68. OnXmlDictionaryReaderClose on_close;
  69. Dictionary<string,MimeEncodedStream> readers = new Dictionary<string,MimeEncodedStream> ();
  70. void Initialize ()
  71. {
  72. var nt = new NameTable ();
  73. initial_reader = new NonInteractiveStateXmlReader (String.Empty, nt, ReadState.Initial);
  74. eof_reader = new NonInteractiveStateXmlReader (String.Empty, nt, ReadState.EndOfFile);
  75. xml_reader = initial_reader;
  76. }
  77. ContentType CreateContentType (string contentTypeString)
  78. {
  79. ContentType c = null;
  80. foreach (var s_ in contentTypeString.Split (';')) {
  81. var s = s_.Trim ();
  82. if (c == null) {
  83. // first one
  84. c = new ContentType (s);
  85. continue;
  86. }
  87. int idx = s.IndexOf ('=');
  88. if (idx < 0)
  89. throw new XmlException ("Invalid content type header");
  90. var val = StripBraces (s.Substring (idx + 1));
  91. c.Parameters [s.Substring (0, idx)] = val;
  92. }
  93. return c;
  94. }
  95. XmlReader xml_reader, initial_reader, eof_reader, part_reader;
  96. XmlReader Reader {
  97. get { return part_reader ?? xml_reader; }
  98. }
  99. public override bool EOF {
  100. get { return Reader == eof_reader; }
  101. }
  102. public override void Close ()
  103. {
  104. if (!EOF && on_close != null)
  105. on_close (this);
  106. xml_reader = eof_reader;
  107. }
  108. public override bool Read ()
  109. {
  110. if (EOF)
  111. return false;
  112. if (Reader == initial_reader)
  113. SetupPrimaryReader ();
  114. if (part_reader != null)
  115. part_reader = null;
  116. if (!Reader.Read ()) {
  117. xml_reader = eof_reader;
  118. return false;
  119. }
  120. if (Reader.LocalName == "Include" && Reader.NamespaceURI == "http://www.w3.org/2004/08/xop/include") {
  121. string cid = Reader.GetAttribute ("href");
  122. if (!cid.StartsWith ("cid:"))
  123. throw new XmlException ("Cannot resolve non-cid href attribute value in XOP Include element");
  124. cid = cid.Substring (4);
  125. if (!readers.ContainsKey (cid))
  126. ReadToIdentifiedStream (cid);
  127. part_reader = new MultiPartedXmlReader (Reader, readers [cid]);
  128. }
  129. return true;
  130. }
  131. void SetupPrimaryReader ()
  132. {
  133. ReadOptionalMimeHeaders ();
  134. if (current_content_type != null)
  135. content_type = current_content_type;
  136. if (content_type == null)
  137. throw new XmlException ("Content-Type header for the MTOM message was not found");
  138. if (content_type.Boundary == null)
  139. throw new XmlException ("Content-Type header for the MTOM message must contain 'boundary' parameter");
  140. if (encoding == null && content_type.CharSet != null)
  141. encoding = Encoding.GetEncoding (content_type.CharSet);
  142. if (encoding == null && encodings == null)
  143. throw new XmlException ("Encoding specification is required either in the constructor argument or the content-type header");
  144. // consume the first identifier.
  145. string ident = "--" + content_type.Boundary;
  146. string idline;
  147. while (true) {
  148. idline = ReadAsciiLine ().Trim ();
  149. if (idline == null)
  150. return;
  151. if (idline.Length != 0)
  152. break;
  153. }
  154. if (!idline.StartsWith (ident, StringComparison.Ordinal))
  155. throw new XmlException (String.Format ("Unexpected boundary line was found. Expected boundary is '{0}' but it was '{1}'", content_type.Boundary, idline));
  156. string start = content_type.Parameters ["start"];
  157. ReadToIdentifiedStream (start);
  158. xml_reader = XmlReader.Create (readers [start].CreateTextReader ());
  159. }
  160. int buffer_length;
  161. byte [] buffer;
  162. int peek_char;
  163. ContentType current_content_type;
  164. int content_index;
  165. string current_content_id, current_content_encoding;
  166. void ReadToIdentifiedStream (string id)
  167. {
  168. while (true) {
  169. if (!ReadNextStream ())
  170. throw new XmlException (String.Format ("The stream '{0}' did not appear", id));
  171. if (current_content_id == id || id == null)
  172. break;
  173. }
  174. }
  175. bool ReadNextStream ()
  176. {
  177. ReadOptionalMimeHeaders ();
  178. string ident = "--" + content_type.Boundary;
  179. StringBuilder sb = new StringBuilder ();
  180. while (true) {
  181. string n = ReadAsciiLine ();
  182. if (n == null && sb.Length == 0)
  183. return false;
  184. else if (n == null || n.StartsWith (ident, StringComparison.Ordinal))
  185. break;
  186. sb.Append (n);
  187. }
  188. readers.Add (current_content_id, new MimeEncodedStream (current_content_id, current_content_encoding, sb.ToString ()));
  189. return true;
  190. }
  191. void ReadOptionalMimeHeaders ()
  192. {
  193. peek_char = stream.ReadByte ();
  194. if (peek_char == '-') // no header
  195. return;
  196. ReadMimeHeaders ();
  197. }
  198. string ReadAllHeaderLines ()
  199. {
  200. string s = String.Empty;
  201. while (true) {
  202. var n = ReadAsciiLine ();
  203. if (n.Length == 0)
  204. return s;
  205. n = n.TrimEnd ();
  206. s += n;
  207. if (n [n.Length - 1] != ';')
  208. s += '\n';
  209. }
  210. }
  211. void ReadMimeHeaders ()
  212. {
  213. foreach (var s in ReadAllHeaderLines ().Split ('\n')) {
  214. if (s.Length == 0)
  215. continue;
  216. int idx = s.IndexOf (':');
  217. if (idx < 0)
  218. throw new XmlException (String.Format ("Unexpected header string: {0}", s));
  219. string v = StripBraces (s.Substring (idx + 1).Trim ());
  220. switch (s.Substring (0, idx).ToLower ()) {
  221. case "content-type":
  222. current_content_type = CreateContentType (v);
  223. break;
  224. case "content-id":
  225. current_content_id = v;
  226. break;
  227. case "content-transfer-encoding":
  228. current_content_encoding = v;
  229. break;
  230. }
  231. }
  232. }
  233. string StripBraces (string s)
  234. {
  235. // could be foo, <foo>, "foo" and "<foo>".
  236. if (s.Length >= 2 && s [0] == '"' && s [s.Length - 1] == '"')
  237. s = s.Substring (1, s.Length - 2);
  238. if (s.Length >= 2 && s [0] == '<' && s [s.Length - 1] == '>')
  239. s = s.Substring (1, s.Length - 2);
  240. return s;
  241. }
  242. string ReadAsciiLine ()
  243. {
  244. if (buffer == null)
  245. buffer = new byte [1024];
  246. int bpos = 0;
  247. int b = peek_char;
  248. bool skipRead = b >= 0;
  249. peek_char = -1;
  250. while (true) {
  251. if (skipRead)
  252. skipRead = false;
  253. else
  254. b = stream.ReadByte ();
  255. if (b < 0) {
  256. if (bpos > 0)
  257. throw new XmlException ("The stream ends without end of line");
  258. return null;
  259. }
  260. if (b == '\r') {
  261. b = stream.ReadByte ();
  262. if (b < 0) {
  263. buffer [bpos++] = (byte) '\r';
  264. break;
  265. }
  266. else if (b == '\n')
  267. break;
  268. buffer [bpos++] = (byte) '\r';
  269. skipRead = true;
  270. }
  271. else
  272. buffer [bpos++] = (byte) b;
  273. if (bpos == buffer.Length) {
  274. var newbuf = new byte [buffer.Length << 1];
  275. Array.Copy (buffer, 0, newbuf, 0, buffer.Length);
  276. buffer = newbuf;
  277. }
  278. }
  279. return Encoding.ASCII.GetString (buffer, 0, bpos);
  280. }
  281. // The rest are just reader delegation.
  282. public override int AttributeCount {
  283. get { return Reader.AttributeCount; }
  284. }
  285. public override string BaseURI {
  286. get { return Reader.BaseURI; }
  287. }
  288. public override int Depth {
  289. get { return Reader.Depth; }
  290. }
  291. public override bool HasValue {
  292. get { return Reader.HasValue; }
  293. }
  294. public override bool IsEmptyElement {
  295. get { return Reader.IsEmptyElement; }
  296. }
  297. public override string LocalName {
  298. get { return Reader.LocalName; }
  299. }
  300. public override string NamespaceURI {
  301. get { return Reader.NamespaceURI; }
  302. }
  303. public override XmlNameTable NameTable {
  304. get { return Reader.NameTable; }
  305. }
  306. public override XmlNodeType NodeType {
  307. get { return Reader.NodeType; }
  308. }
  309. public override string Prefix {
  310. get { return Reader.Prefix; }
  311. }
  312. public override ReadState ReadState {
  313. get { return Reader.ReadState; }
  314. }
  315. public override string Value {
  316. get { return Reader.Value; }
  317. }
  318. public override bool MoveToElement ()
  319. {
  320. return Reader.MoveToElement ();
  321. }
  322. public override string GetAttribute (int index)
  323. {
  324. return Reader.GetAttribute (index);
  325. }
  326. public override string GetAttribute (string name)
  327. {
  328. return Reader.GetAttribute (name);
  329. }
  330. public override string GetAttribute (string localName, string namespaceURI)
  331. {
  332. return Reader.GetAttribute (localName, namespaceURI);
  333. }
  334. public override void MoveToAttribute (int index)
  335. {
  336. Reader.MoveToAttribute (index);
  337. }
  338. public override bool MoveToAttribute (string name)
  339. {
  340. return Reader.MoveToAttribute (name);
  341. }
  342. public override bool MoveToAttribute (string localName, string namespaceURI)
  343. {
  344. return Reader.MoveToAttribute (localName, namespaceURI);
  345. }
  346. public override bool MoveToFirstAttribute ()
  347. {
  348. return Reader.MoveToFirstAttribute ();
  349. }
  350. public override bool MoveToNextAttribute ()
  351. {
  352. return Reader.MoveToNextAttribute ();
  353. }
  354. public override string LookupNamespace (string prefix)
  355. {
  356. return Reader.LookupNamespace (prefix);
  357. }
  358. public override bool ReadAttributeValue ()
  359. {
  360. return Reader.ReadAttributeValue ();
  361. }
  362. public override void ResolveEntity ()
  363. {
  364. Reader.ResolveEntity ();
  365. }
  366. }
  367. class NonInteractiveStateXmlReader : DummyStateXmlReader
  368. {
  369. public NonInteractiveStateXmlReader (string baseUri, XmlNameTable nameTable, ReadState readState)
  370. : base (baseUri, nameTable, readState)
  371. {
  372. }
  373. public override int Depth {
  374. get { return 0; }
  375. }
  376. public override bool HasValue {
  377. get { return false; }
  378. }
  379. public override string Value {
  380. get { return String.Empty; }
  381. }
  382. public override XmlNodeType NodeType {
  383. get { return XmlNodeType.None; }
  384. }
  385. }
  386. class MultiPartedXmlReader : DummyStateXmlReader
  387. {
  388. public MultiPartedXmlReader (XmlReader reader, MimeEncodedStream value)
  389. : base (reader.BaseURI, reader.NameTable, reader.ReadState)
  390. {
  391. this.owner = reader;
  392. this.value = value.CreateTextReader ().ReadToEnd ();
  393. }
  394. XmlReader owner;
  395. string value;
  396. public override int Depth {
  397. get { return owner.Depth; }
  398. }
  399. public override bool HasValue {
  400. get { return true; }
  401. }
  402. public override string Value {
  403. get { return value; }
  404. }
  405. public override XmlNodeType NodeType {
  406. get { return XmlNodeType.Text; }
  407. }
  408. }
  409. abstract class DummyStateXmlReader : XmlReader
  410. {
  411. protected DummyStateXmlReader (string baseUri, XmlNameTable nameTable, ReadState readState)
  412. {
  413. base_uri = baseUri;
  414. name_table = nameTable;
  415. read_state = readState;
  416. }
  417. string base_uri;
  418. XmlNameTable name_table;
  419. ReadState read_state;
  420. public override string BaseURI {
  421. get { return base_uri; }
  422. }
  423. public override bool EOF {
  424. get { return false; }
  425. }
  426. public override void Close ()
  427. {
  428. throw new NotSupportedException ();
  429. }
  430. public override bool Read ()
  431. {
  432. throw new NotSupportedException ();
  433. }
  434. // The rest are just reader delegation.
  435. public override int AttributeCount {
  436. get { return 0; }
  437. }
  438. public override bool IsEmptyElement {
  439. get { return false; }
  440. }
  441. public override string LocalName {
  442. get { return String.Empty; }
  443. }
  444. public override string NamespaceURI {
  445. get { return String.Empty; }
  446. }
  447. public override XmlNameTable NameTable {
  448. get { return name_table; }
  449. }
  450. public override string Prefix {
  451. get { return String.Empty; }
  452. }
  453. public override ReadState ReadState {
  454. get { return read_state; }
  455. }
  456. public override bool MoveToElement ()
  457. {
  458. return false;
  459. }
  460. public override string GetAttribute (int index)
  461. {
  462. return null;
  463. }
  464. public override string GetAttribute (string name)
  465. {
  466. return null;
  467. }
  468. public override string GetAttribute (string localName, string namespaceURI)
  469. {
  470. return null;
  471. }
  472. public override void MoveToAttribute (int index)
  473. {
  474. throw new ArgumentOutOfRangeException ();
  475. }
  476. public override bool MoveToAttribute (string name)
  477. {
  478. return false;
  479. }
  480. public override bool MoveToAttribute (string localName, string namespaceURI)
  481. {
  482. return false;
  483. }
  484. public override bool MoveToFirstAttribute ()
  485. {
  486. return false;
  487. }
  488. public override bool MoveToNextAttribute ()
  489. {
  490. return false;
  491. }
  492. public override string LookupNamespace (string prefix)
  493. {
  494. return null;
  495. }
  496. public override bool ReadAttributeValue ()
  497. {
  498. return false;
  499. }
  500. public override void ResolveEntity ()
  501. {
  502. throw new InvalidOperationException ();
  503. }
  504. }
  505. class MimeEncodedStream
  506. {
  507. public MimeEncodedStream (string id, string contentEncoding, string value)
  508. {
  509. Id = id;
  510. ContentEncoding = contentEncoding;
  511. EncodedString = value;
  512. }
  513. public string Id { get; set; }
  514. public string ContentEncoding { get; set; }
  515. public string EncodedString { get; set; }
  516. public string DecodedBase64String {
  517. get { return Convert.ToBase64String (Encoding.ASCII.GetBytes (EncodedString)); }
  518. }
  519. public TextReader CreateTextReader ()
  520. {
  521. switch (ContentEncoding) {
  522. case "7bit":
  523. case "8bit":
  524. return new StringReader (EncodedString);
  525. default:
  526. return new StringReader (DecodedBase64String);
  527. }
  528. }
  529. }
  530. }