XmlReaderBinarySupport.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. //
  2. // System.Xml.XmlReaderBinarySupport.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto ([email protected])
  6. //
  7. // (C)2004 Novell Inc,
  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.Text;
  32. namespace System.Xml
  33. {
  34. internal class XmlReaderBinarySupport
  35. {
  36. public delegate int CharGetter (
  37. char [] buffer, int offset, int length);
  38. public enum CommandState {
  39. None,
  40. ReadElementContentAsBase64,
  41. ReadContentAsBase64,
  42. ReadElementContentAsBinHex,
  43. ReadContentAsBinHex
  44. }
  45. public XmlReaderBinarySupport (XmlReader reader)
  46. {
  47. this.reader = reader;
  48. Reset ();
  49. }
  50. XmlReader reader;
  51. CharGetter getter;
  52. byte [] base64Cache = new byte [3];
  53. int base64CacheStartsAt;
  54. CommandState state;
  55. StringBuilder textCache;
  56. bool hasCache;
  57. bool dontReset;
  58. public CharGetter Getter {
  59. get { return getter; }
  60. set { getter = value; }
  61. }
  62. public void Reset ()
  63. {
  64. if (!dontReset) {
  65. dontReset = true;
  66. if (hasCache) {
  67. reader.Read ();
  68. switch (state) {
  69. case CommandState.ReadElementContentAsBase64:
  70. case CommandState.ReadElementContentAsBinHex:
  71. reader.Read ();
  72. break;
  73. }
  74. }
  75. base64CacheStartsAt = -1;
  76. state = CommandState.None;
  77. hasCache = false;
  78. dontReset = false;
  79. }
  80. }
  81. InvalidOperationException StateError (CommandState action)
  82. {
  83. return new InvalidOperationException (
  84. String.Format ("Invalid attempt to read binary content by {0}, while once binary reading was started by {1}", action, state));
  85. }
  86. private void CheckState (bool element, CommandState action)
  87. {
  88. if (state == CommandState.None) {
  89. if (textCache == null)
  90. textCache = new StringBuilder ();
  91. else
  92. textCache.Length = 0;
  93. if (action == CommandState.None)
  94. return; // for ReadValueChunk()
  95. if (reader.ReadState != ReadState.Interactive)
  96. return;
  97. switch (reader.NodeType) {
  98. case XmlNodeType.Text:
  99. case XmlNodeType.CDATA:
  100. case XmlNodeType.SignificantWhitespace:
  101. case XmlNodeType.Whitespace:
  102. if (!element) {
  103. state = action;
  104. return;
  105. }
  106. break;
  107. case XmlNodeType.Element:
  108. if (element) {
  109. if (!reader.IsEmptyElement)
  110. reader.Read ();
  111. state = action;
  112. return;
  113. }
  114. break;
  115. }
  116. throw new XmlException ((element ?
  117. "Reader is not positioned on an element."
  118. : "Reader is not positioned on a text node."));
  119. }
  120. if (state == action)
  121. return;
  122. throw StateError (action);
  123. }
  124. public int ReadElementContentAsBase64 (
  125. byte [] buffer, int offset, int length)
  126. {
  127. CheckState (true, CommandState.ReadElementContentAsBase64);
  128. return ReadBase64 (buffer, offset, length);
  129. }
  130. public int ReadContentAsBase64 (
  131. byte [] buffer, int offset, int length)
  132. {
  133. CheckState (false, CommandState.ReadContentAsBase64);
  134. return ReadBase64 (buffer, offset, length);
  135. }
  136. public int ReadElementContentAsBinHex (
  137. byte [] buffer, int offset, int length)
  138. {
  139. CheckState (true, CommandState.ReadElementContentAsBinHex);
  140. return ReadBinHex (buffer, offset, length);
  141. }
  142. public int ReadContentAsBinHex (
  143. byte [] buffer, int offset, int length)
  144. {
  145. CheckState (false, CommandState.ReadContentAsBinHex);
  146. return ReadBinHex (buffer, offset, length);
  147. }
  148. public int ReadBase64 (byte [] buffer, int offset, int length)
  149. {
  150. if (offset < 0)
  151. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  152. else if (length < 0)
  153. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  154. else if (buffer.Length < offset + length)
  155. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  156. if (reader.IsEmptyElement)
  157. return 0;
  158. if (length == 0) // It does not raise an error.
  159. return 0;
  160. int bufIndex = offset;
  161. int bufLast = offset + length;
  162. if (base64CacheStartsAt >= 0) {
  163. for (int i = base64CacheStartsAt; i < 3; i++) {
  164. buffer [bufIndex++] = base64Cache [base64CacheStartsAt++];
  165. if (bufIndex == bufLast)
  166. return bufLast - offset;
  167. }
  168. }
  169. for (int i = 0; i < 3; i++)
  170. base64Cache [i] = 0;
  171. base64CacheStartsAt = -1;
  172. int max = (int) System.Math.Ceiling (4.0 / 3 * length);
  173. int additional = max % 4;
  174. if (additional > 0)
  175. max += 4 - additional;
  176. char [] chars = new char [max];
  177. int charsLength = getter != null ?
  178. getter (chars, 0, max) :
  179. ReadValueChunk (chars, 0, max);
  180. byte b = 0;
  181. byte work = 0;
  182. for (int i = 0; i < charsLength - 3; i++) {
  183. if ((i = SkipIgnorableBase64Chars (chars, charsLength, i)) == charsLength)
  184. break;
  185. b = (byte) (GetBase64Byte (chars [i]) << 2);
  186. if (bufIndex < bufLast)
  187. buffer [bufIndex] = b;
  188. else {
  189. if (base64CacheStartsAt < 0)
  190. base64CacheStartsAt = 0;
  191. base64Cache [0] = b;
  192. }
  193. // charsLength mod 4 might not equals to 0.
  194. if (++i == charsLength)
  195. break;
  196. if ((i = SkipIgnorableBase64Chars (chars, charsLength, i)) == charsLength)
  197. break;
  198. b = GetBase64Byte (chars [i]);
  199. work = (byte) (b >> 4);
  200. if (bufIndex < bufLast) {
  201. buffer [bufIndex] += work;
  202. bufIndex++;
  203. }
  204. else
  205. base64Cache [0] += work;
  206. work = (byte) ((b & 0xf) << 4);
  207. if (bufIndex < bufLast) {
  208. buffer [bufIndex] = work;
  209. }
  210. else {
  211. if (base64CacheStartsAt < 0)
  212. base64CacheStartsAt = 1;
  213. base64Cache [1] = work;
  214. }
  215. if (++i == charsLength)
  216. break;
  217. if ((i = SkipIgnorableBase64Chars (chars, charsLength, i)) == charsLength)
  218. break;
  219. b = GetBase64Byte (chars [i]);
  220. work = (byte) (b >> 2);
  221. if (bufIndex < bufLast) {
  222. buffer [bufIndex] += work;
  223. bufIndex++;
  224. }
  225. else
  226. base64Cache [1] += work;
  227. work = (byte) ((b & 3) << 6);
  228. if (bufIndex < bufLast)
  229. buffer [bufIndex] = work;
  230. else {
  231. if (base64CacheStartsAt < 0)
  232. base64CacheStartsAt = 2;
  233. base64Cache [2] = work;
  234. }
  235. if (++i == charsLength)
  236. break;
  237. if ((i = SkipIgnorableBase64Chars (chars, charsLength, i)) == charsLength)
  238. break;
  239. work = GetBase64Byte (chars [i]);
  240. if (bufIndex < bufLast) {
  241. buffer [bufIndex] += work;
  242. bufIndex++;
  243. }
  244. else
  245. base64Cache [2] += work;
  246. }
  247. int ret = System.Math.Min (bufLast - offset, bufIndex - offset);
  248. if (ret < length && charsLength > 0)
  249. return ret + ReadBase64 (buffer, offset + ret, length - ret);
  250. else
  251. return ret;
  252. }
  253. // Since ReadBase64() is processed for every 4 chars, it does
  254. // not handle '=' here.
  255. private byte GetBase64Byte (char ch)
  256. {
  257. switch (ch) {
  258. case '+':
  259. return 62;
  260. case '/':
  261. return 63;
  262. default:
  263. if (ch >= 'A' && ch <= 'Z')
  264. return (byte) (ch - 'A');
  265. else if (ch >= 'a' && ch <= 'z')
  266. return (byte) (ch - 'a' + 26);
  267. else if (ch >= '0' && ch <= '9')
  268. return (byte) (ch - '0' + 52);
  269. else
  270. throw new XmlException ("Invalid Base64 character was found.");
  271. }
  272. }
  273. private int SkipIgnorableBase64Chars (char [] chars, int charsLength, int i)
  274. {
  275. while (chars [i] == '=' || XmlChar.IsWhitespace (chars [i]))
  276. if (charsLength == ++i)
  277. break;
  278. return i;
  279. }
  280. public int ReadBinHex (byte [] buffer, int offset, int length)
  281. {
  282. if (offset < 0)
  283. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  284. else if (length < 0)
  285. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  286. else if (buffer.Length < offset + length)
  287. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  288. if (length == 0)
  289. return 0;
  290. char [] chars = new char [length * 2];
  291. int charsLength = getter != null ?
  292. getter (chars, 0, length * 2) :
  293. ReadValueChunk (chars, 0, length * 2);
  294. return XmlConvert.FromBinHexString (chars, offset, charsLength, buffer);
  295. }
  296. public int ReadValueChunk (
  297. char [] buffer, int offset, int length)
  298. {
  299. CommandState backup = state;
  300. if (state == CommandState.None)
  301. CheckState (false, CommandState.None);
  302. if (offset < 0)
  303. throw new ArgumentOutOfRangeException ("offset", offset, "Offset must be non-negative integer.");
  304. else if (length < 0)
  305. throw new ArgumentOutOfRangeException ("length", length, "Length must be non-negative integer.");
  306. else if (buffer.Length < offset + length)
  307. throw new ArgumentOutOfRangeException ("buffer length is smaller than the sum of offset and length.");
  308. if (length == 0)
  309. return 0;
  310. if (!hasCache) {
  311. if (reader.IsEmptyElement)
  312. return 0;
  313. }
  314. bool consumeToEnd = false;
  315. while (!consumeToEnd && textCache.Length < length) {
  316. switch (reader.NodeType) {
  317. case XmlNodeType.Text:
  318. case XmlNodeType.CDATA:
  319. case XmlNodeType.SignificantWhitespace:
  320. case XmlNodeType.Whitespace:
  321. if (hasCache) {
  322. switch (reader.NodeType) {
  323. case XmlNodeType.Text:
  324. case XmlNodeType.CDATA:
  325. case XmlNodeType.SignificantWhitespace:
  326. case XmlNodeType.Whitespace:
  327. Read ();
  328. break;
  329. default:
  330. consumeToEnd = true;
  331. break;
  332. }
  333. }
  334. textCache.Append (reader.Value);
  335. hasCache = true;
  336. break;
  337. }
  338. }
  339. state = backup;
  340. int min = textCache.Length;
  341. if (min > length)
  342. min = length;
  343. string str = textCache.ToString (0, min);
  344. textCache.Remove (0, str.Length);
  345. str.CopyTo (0, buffer, offset, str.Length);
  346. if (min < length)
  347. return min + ReadValueChunk (buffer, offset + min, length - min);
  348. else
  349. return min;
  350. }
  351. private bool Read ()
  352. {
  353. dontReset = true;
  354. bool b = reader.Read ();
  355. dontReset = false;
  356. return b;
  357. }
  358. }
  359. }