ChunkStream.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. var 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 => (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None);
  158. public bool DataAvailable
  159. {
  160. get
  161. {
  162. int count = _chunks.Count;
  163. for (int i = 0; i < count; i++)
  164. {
  165. var ch = _chunks[i];
  166. if (ch == null || ch.Bytes == null)
  167. continue;
  168. if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
  169. return (_state != State.Body);
  170. }
  171. return false;
  172. }
  173. }
  174. public int TotalDataSize => _totalWritten;
  175. public int ChunkLeft => _chunkSize - _chunkRead;
  176. private State ReadBody(byte[] buffer, ref int offset, int size)
  177. {
  178. if (_chunkSize == 0)
  179. return State.BodyFinished;
  180. int diff = size - offset;
  181. if (diff + _chunkRead > _chunkSize)
  182. diff = _chunkSize - _chunkRead;
  183. byte[] chunk = new byte[diff];
  184. Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
  185. _chunks.Add(new Chunk(chunk));
  186. offset += diff;
  187. _chunkRead += diff;
  188. _totalWritten += diff;
  189. return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body;
  190. }
  191. private State GetChunkSize(byte[] buffer, ref int offset, int size)
  192. {
  193. _chunkRead = 0;
  194. _chunkSize = 0;
  195. char c = '\0';
  196. while (offset < size)
  197. {
  198. c = (char)buffer[offset++];
  199. if (c == '\r')
  200. {
  201. if (_sawCR)
  202. ThrowProtocolViolation("2 CR found");
  203. _sawCR = true;
  204. continue;
  205. }
  206. if (_sawCR && c == '\n')
  207. break;
  208. if (c == ' ')
  209. _gotit = true;
  210. if (!_gotit)
  211. _saved.Append(c);
  212. if (_saved.Length > 20)
  213. ThrowProtocolViolation("chunk size too long.");
  214. }
  215. if (!_sawCR || c != '\n')
  216. {
  217. if (offset < size)
  218. ThrowProtocolViolation("Missing \\n");
  219. try
  220. {
  221. if (_saved.Length > 0)
  222. {
  223. _chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  224. }
  225. }
  226. catch (Exception)
  227. {
  228. ThrowProtocolViolation("Cannot parse chunk size.");
  229. }
  230. return State.PartialSize;
  231. }
  232. _chunkRead = 0;
  233. try
  234. {
  235. _chunkSize = int.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  236. }
  237. catch (Exception)
  238. {
  239. ThrowProtocolViolation("Cannot parse chunk size.");
  240. }
  241. if (_chunkSize == 0)
  242. {
  243. _trailerState = 2;
  244. return State.Trailer;
  245. }
  246. return State.Body;
  247. }
  248. private static string RemoveChunkExtension(string input)
  249. {
  250. int idx = input.IndexOf(';');
  251. if (idx == -1)
  252. return input;
  253. return input.Substring(0, idx);
  254. }
  255. private State ReadCRLF(byte[] buffer, ref int offset, int size)
  256. {
  257. if (!_sawCR)
  258. {
  259. if ((char)buffer[offset++] != '\r')
  260. ThrowProtocolViolation("Expecting \\r");
  261. _sawCR = true;
  262. if (offset == size)
  263. return State.BodyFinished;
  264. }
  265. if (_sawCR && (char)buffer[offset++] != '\n')
  266. ThrowProtocolViolation("Expecting \\n");
  267. return State.None;
  268. }
  269. private State ReadTrailer(byte[] buffer, ref int offset, int size)
  270. {
  271. char c = '\0';
  272. // short path
  273. if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0)
  274. {
  275. offset++;
  276. if (offset < size && (char)buffer[offset] == '\n')
  277. {
  278. offset++;
  279. return State.None;
  280. }
  281. offset--;
  282. }
  283. int st = _trailerState;
  284. string stString = "\r\n\r";
  285. while (offset < size && st < 4)
  286. {
  287. c = (char)buffer[offset++];
  288. if ((st == 0 || st == 2) && c == '\r')
  289. {
  290. st++;
  291. continue;
  292. }
  293. if ((st == 1 || st == 3) && c == '\n')
  294. {
  295. st++;
  296. continue;
  297. }
  298. if (st > 0)
  299. {
  300. _saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st));
  301. st = 0;
  302. if (_saved.Length > 4196)
  303. ThrowProtocolViolation("Error reading trailer (too long).");
  304. }
  305. }
  306. if (st < 4)
  307. {
  308. _trailerState = st;
  309. if (offset < size)
  310. ThrowProtocolViolation("Error reading trailer.");
  311. return State.Trailer;
  312. }
  313. var reader = new StringReader(_saved.ToString());
  314. string line;
  315. while ((line = reader.ReadLine()) != null && line != "")
  316. _headers.Add(line);
  317. return State.None;
  318. }
  319. private static void ThrowProtocolViolation(string message)
  320. {
  321. var we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
  322. throw we;
  323. }
  324. }
  325. }