ChunkStream.cs 12 KB

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