ChunkStream.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Net;
  7. using System.Text;
  8. namespace SocketHttpListener.Net
  9. {
  10. // Licensed to the .NET Foundation under one or more agreements.
  11. // See the LICENSE file in the project root for more information.
  12. //
  13. // System.Net.ResponseStream
  14. //
  15. // Author:
  16. // Gonzalo Paniagua Javier (gonzalo@novell.com)
  17. //
  18. // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
  19. //
  20. // Permission is hereby granted, free of charge, to any person obtaining
  21. // a copy of this software and associated documentation files (the
  22. // "Software"), to deal in the Software without restriction, including
  23. // without limitation the rights to use, copy, modify, merge, publish,
  24. // distribute, sublicense, and/or sell copies of the Software, and to
  25. // permit persons to whom the Software is furnished to do so, subject to
  26. // the following conditions:
  27. //
  28. // The above copyright notice and this permission notice shall be
  29. // included in all copies or substantial portions of the Software.
  30. //
  31. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  32. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  33. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  34. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  35. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  36. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  37. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  38. //
  39. internal sealed class ChunkStream
  40. {
  41. private enum State
  42. {
  43. None,
  44. PartialSize,
  45. Body,
  46. BodyFinished,
  47. Trailer
  48. }
  49. private class Chunk
  50. {
  51. public byte[] Bytes;
  52. public int Offset;
  53. public Chunk(byte[] chunk)
  54. {
  55. Bytes = chunk;
  56. }
  57. public int Read(byte[] buffer, int offset, int size)
  58. {
  59. int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
  60. Buffer.BlockCopy(Bytes, Offset, buffer, offset, nread);
  61. Offset += nread;
  62. return nread;
  63. }
  64. }
  65. internal WebHeaderCollection _headers;
  66. private int _chunkSize;
  67. private int _chunkRead;
  68. private int _totalWritten;
  69. private State _state;
  70. private StringBuilder _saved;
  71. private bool _sawCR;
  72. private bool _gotit;
  73. private int _trailerState;
  74. private List<Chunk> _chunks;
  75. public ChunkStream(WebHeaderCollection headers)
  76. {
  77. _headers = headers;
  78. _saved = new StringBuilder();
  79. _chunks = new List<Chunk>();
  80. _chunkSize = -1;
  81. _totalWritten = 0;
  82. }
  83. public void ResetBuffer()
  84. {
  85. _chunkSize = -1;
  86. _chunkRead = 0;
  87. _totalWritten = 0;
  88. _chunks.Clear();
  89. }
  90. public int Read(byte[] buffer, int offset, int size)
  91. {
  92. return ReadFromChunks(buffer, offset, size);
  93. }
  94. private int ReadFromChunks(byte[] buffer, int offset, int size)
  95. {
  96. int count = _chunks.Count;
  97. int nread = 0;
  98. var chunksForRemoving = new List<Chunk>(count);
  99. for (int i = 0; i < count; i++)
  100. {
  101. Chunk chunk = _chunks[i];
  102. if (chunk.Offset == chunk.Bytes.Length)
  103. {
  104. chunksForRemoving.Add(chunk);
  105. continue;
  106. }
  107. nread += chunk.Read(buffer, offset + nread, size - nread);
  108. if (nread == size)
  109. break;
  110. }
  111. foreach (var chunk in chunksForRemoving)
  112. _chunks.Remove(chunk);
  113. return nread;
  114. }
  115. public void Write(byte[] buffer, int offset, int size)
  116. {
  117. // Note, the logic here only works when offset is 0 here.
  118. // Otherwise, it would treat "size" as the end offset instead of an actual byte count from offset.
  119. if (offset < size)
  120. InternalWrite(buffer, ref offset, size);
  121. }
  122. private void InternalWrite(byte[] buffer, ref int offset, int size)
  123. {
  124. if (_state == State.None || _state == State.PartialSize)
  125. {
  126. _state = GetChunkSize(buffer, ref offset, size);
  127. if (_state == State.PartialSize)
  128. return;
  129. _saved.Length = 0;
  130. _sawCR = false;
  131. _gotit = false;
  132. }
  133. if (_state == State.Body && offset < size)
  134. {
  135. _state = ReadBody(buffer, ref offset, size);
  136. if (_state == State.Body)
  137. return;
  138. }
  139. if (_state == State.BodyFinished && offset < size)
  140. {
  141. _state = ReadCRLF(buffer, ref offset, size);
  142. if (_state == State.BodyFinished)
  143. return;
  144. _sawCR = false;
  145. }
  146. if (_state == State.Trailer && offset < size)
  147. {
  148. _state = ReadTrailer(buffer, ref offset, size);
  149. if (_state == State.Trailer)
  150. return;
  151. _saved.Length = 0;
  152. _sawCR = false;
  153. _gotit = false;
  154. }
  155. if (offset < size)
  156. InternalWrite(buffer, ref offset, size);
  157. }
  158. public bool WantMore
  159. {
  160. get { return (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None); }
  161. }
  162. public bool DataAvailable
  163. {
  164. get
  165. {
  166. int count = _chunks.Count;
  167. for (int i = 0; i < count; i++)
  168. {
  169. Chunk ch = _chunks[i];
  170. if (ch == null || ch.Bytes == null)
  171. continue;
  172. if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
  173. return (_state != State.Body);
  174. }
  175. return false;
  176. }
  177. }
  178. public int TotalDataSize
  179. {
  180. get { return _totalWritten; }
  181. }
  182. public int ChunkLeft
  183. {
  184. get { return _chunkSize - _chunkRead; }
  185. }
  186. private State ReadBody(byte[] buffer, ref int offset, int size)
  187. {
  188. if (_chunkSize == 0)
  189. return State.BodyFinished;
  190. int diff = size - offset;
  191. if (diff + _chunkRead > _chunkSize)
  192. diff = _chunkSize - _chunkRead;
  193. byte[] chunk = new byte[diff];
  194. Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
  195. _chunks.Add(new Chunk(chunk));
  196. offset += diff;
  197. _chunkRead += diff;
  198. _totalWritten += diff;
  199. return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body;
  200. }
  201. private State GetChunkSize(byte[] buffer, ref int offset, int size)
  202. {
  203. _chunkRead = 0;
  204. _chunkSize = 0;
  205. char c = '\0';
  206. while (offset < size)
  207. {
  208. c = (char)buffer[offset++];
  209. if (c == '\r')
  210. {
  211. if (_sawCR)
  212. ThrowProtocolViolation("2 CR found");
  213. _sawCR = true;
  214. continue;
  215. }
  216. if (_sawCR && c == '\n')
  217. break;
  218. if (c == ' ')
  219. _gotit = true;
  220. if (!_gotit)
  221. _saved.Append(c);
  222. if (_saved.Length > 20)
  223. ThrowProtocolViolation("chunk size too long.");
  224. }
  225. if (!_sawCR || c != '\n')
  226. {
  227. if (offset < size)
  228. ThrowProtocolViolation("Missing \\n");
  229. try
  230. {
  231. if (_saved.Length > 0)
  232. {
  233. _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  234. }
  235. }
  236. catch (Exception)
  237. {
  238. ThrowProtocolViolation("Cannot parse chunk size.");
  239. }
  240. return State.PartialSize;
  241. }
  242. _chunkRead = 0;
  243. try
  244. {
  245. _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  246. }
  247. catch (Exception)
  248. {
  249. ThrowProtocolViolation("Cannot parse chunk size.");
  250. }
  251. if (_chunkSize == 0)
  252. {
  253. _trailerState = 2;
  254. return State.Trailer;
  255. }
  256. return State.Body;
  257. }
  258. private static string RemoveChunkExtension(string input)
  259. {
  260. int idx = input.IndexOf(';');
  261. if (idx == -1)
  262. return input;
  263. return input.Substring(0, idx);
  264. }
  265. private State ReadCRLF(byte[] buffer, ref int offset, int size)
  266. {
  267. if (!_sawCR)
  268. {
  269. if ((char)buffer[offset++] != '\r')
  270. ThrowProtocolViolation("Expecting \\r");
  271. _sawCR = true;
  272. if (offset == size)
  273. return State.BodyFinished;
  274. }
  275. if (_sawCR && (char)buffer[offset++] != '\n')
  276. ThrowProtocolViolation("Expecting \\n");
  277. return State.None;
  278. }
  279. private State ReadTrailer(byte[] buffer, ref int offset, int size)
  280. {
  281. char c = '\0';
  282. // short path
  283. if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0)
  284. {
  285. offset++;
  286. if (offset < size && (char)buffer[offset] == '\n')
  287. {
  288. offset++;
  289. return State.None;
  290. }
  291. offset--;
  292. }
  293. int st = _trailerState;
  294. string stString = "\r\n\r";
  295. while (offset < size && st < 4)
  296. {
  297. c = (char)buffer[offset++];
  298. if ((st == 0 || st == 2) && c == '\r')
  299. {
  300. st++;
  301. continue;
  302. }
  303. if ((st == 1 || st == 3) && c == '\n')
  304. {
  305. st++;
  306. continue;
  307. }
  308. if (st > 0)
  309. {
  310. _saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st));
  311. st = 0;
  312. if (_saved.Length > 4196)
  313. ThrowProtocolViolation("Error reading trailer (too long).");
  314. }
  315. }
  316. if (st < 4)
  317. {
  318. _trailerState = st;
  319. if (offset < size)
  320. ThrowProtocolViolation("Error reading trailer.");
  321. return State.Trailer;
  322. }
  323. StringReader reader = new StringReader(_saved.ToString());
  324. string line;
  325. while ((line = reader.ReadLine()) != null && line != "")
  326. _headers.Add(line);
  327. return State.None;
  328. }
  329. private static void ThrowProtocolViolation(string message)
  330. {
  331. WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
  332. throw we;
  333. }
  334. }
  335. }