ChunkStream.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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(byte[] buffer, int offset, int size, WebHeaderCollection headers)
  76. : this(headers)
  77. {
  78. Write(buffer, offset, size);
  79. }
  80. public ChunkStream(WebHeaderCollection headers)
  81. {
  82. _headers = headers;
  83. _saved = new StringBuilder();
  84. _chunks = new List<Chunk>();
  85. _chunkSize = -1;
  86. _totalWritten = 0;
  87. }
  88. public void ResetBuffer()
  89. {
  90. _chunkSize = -1;
  91. _chunkRead = 0;
  92. _totalWritten = 0;
  93. _chunks.Clear();
  94. }
  95. public void WriteAndReadBack(byte[] buffer, int offset, int size, ref int read)
  96. {
  97. if (offset + read > 0)
  98. Write(buffer, offset, offset + read);
  99. read = Read(buffer, offset, size);
  100. }
  101. public int Read(byte[] buffer, int offset, int size)
  102. {
  103. return ReadFromChunks(buffer, offset, size);
  104. }
  105. private int ReadFromChunks(byte[] buffer, int offset, int size)
  106. {
  107. int count = _chunks.Count;
  108. int nread = 0;
  109. var chunksForRemoving = new List<Chunk>(count);
  110. for (int i = 0; i < count; i++)
  111. {
  112. Chunk chunk = _chunks[i];
  113. if (chunk.Offset == chunk.Bytes.Length)
  114. {
  115. chunksForRemoving.Add(chunk);
  116. continue;
  117. }
  118. nread += chunk.Read(buffer, offset + nread, size - nread);
  119. if (nread == size)
  120. break;
  121. }
  122. foreach (var chunk in chunksForRemoving)
  123. _chunks.Remove(chunk);
  124. return nread;
  125. }
  126. public void Write(byte[] buffer, int offset, int size)
  127. {
  128. if (offset < size)
  129. InternalWrite(buffer, ref offset, size);
  130. }
  131. private void InternalWrite(byte[] buffer, ref int offset, int size)
  132. {
  133. if (_state == State.None || _state == State.PartialSize)
  134. {
  135. _state = GetChunkSize(buffer, ref offset, size);
  136. if (_state == State.PartialSize)
  137. return;
  138. _saved.Length = 0;
  139. _sawCR = false;
  140. _gotit = false;
  141. }
  142. if (_state == State.Body && offset < size)
  143. {
  144. _state = ReadBody(buffer, ref offset, size);
  145. if (_state == State.Body)
  146. return;
  147. }
  148. if (_state == State.BodyFinished && offset < size)
  149. {
  150. _state = ReadCRLF(buffer, ref offset, size);
  151. if (_state == State.BodyFinished)
  152. return;
  153. _sawCR = false;
  154. }
  155. if (_state == State.Trailer && offset < size)
  156. {
  157. _state = ReadTrailer(buffer, ref offset, size);
  158. if (_state == State.Trailer)
  159. return;
  160. _saved.Length = 0;
  161. _sawCR = false;
  162. _gotit = false;
  163. }
  164. if (offset < size)
  165. InternalWrite(buffer, ref offset, size);
  166. }
  167. public bool WantMore
  168. {
  169. get { return (_chunkRead != _chunkSize || _chunkSize != 0 || _state != State.None); }
  170. }
  171. public bool DataAvailable
  172. {
  173. get
  174. {
  175. int count = _chunks.Count;
  176. for (int i = 0; i < count; i++)
  177. {
  178. Chunk ch = _chunks[i];
  179. if (ch == null || ch.Bytes == null)
  180. continue;
  181. if (ch.Bytes.Length > 0 && ch.Offset < ch.Bytes.Length)
  182. return (_state != State.Body);
  183. }
  184. return false;
  185. }
  186. }
  187. public int TotalDataSize
  188. {
  189. get { return _totalWritten; }
  190. }
  191. public int ChunkLeft
  192. {
  193. get { return _chunkSize - _chunkRead; }
  194. }
  195. private State ReadBody(byte[] buffer, ref int offset, int size)
  196. {
  197. if (_chunkSize == 0)
  198. return State.BodyFinished;
  199. int diff = size - offset;
  200. if (diff + _chunkRead > _chunkSize)
  201. diff = _chunkSize - _chunkRead;
  202. byte[] chunk = new byte[diff];
  203. Buffer.BlockCopy(buffer, offset, chunk, 0, diff);
  204. _chunks.Add(new Chunk(chunk));
  205. offset += diff;
  206. _chunkRead += diff;
  207. _totalWritten += diff;
  208. return (_chunkRead == _chunkSize) ? State.BodyFinished : State.Body;
  209. }
  210. private State GetChunkSize(byte[] buffer, ref int offset, int size)
  211. {
  212. _chunkRead = 0;
  213. _chunkSize = 0;
  214. char c = '\0';
  215. while (offset < size)
  216. {
  217. c = (char)buffer[offset++];
  218. if (c == '\r')
  219. {
  220. if (_sawCR)
  221. ThrowProtocolViolation("2 CR found");
  222. _sawCR = true;
  223. continue;
  224. }
  225. if (_sawCR && c == '\n')
  226. break;
  227. if (c == ' ')
  228. _gotit = true;
  229. if (!_gotit)
  230. _saved.Append(c);
  231. if (_saved.Length > 20)
  232. ThrowProtocolViolation("chunk size too long.");
  233. }
  234. if (!_sawCR || c != '\n')
  235. {
  236. if (offset < size)
  237. ThrowProtocolViolation("Missing \\n");
  238. try
  239. {
  240. if (_saved.Length > 0)
  241. {
  242. _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  243. }
  244. }
  245. catch (Exception)
  246. {
  247. ThrowProtocolViolation("Cannot parse chunk size.");
  248. }
  249. return State.PartialSize;
  250. }
  251. _chunkRead = 0;
  252. try
  253. {
  254. _chunkSize = Int32.Parse(RemoveChunkExtension(_saved.ToString()), NumberStyles.HexNumber);
  255. }
  256. catch (Exception)
  257. {
  258. ThrowProtocolViolation("Cannot parse chunk size.");
  259. }
  260. if (_chunkSize == 0)
  261. {
  262. _trailerState = 2;
  263. return State.Trailer;
  264. }
  265. return State.Body;
  266. }
  267. private static string RemoveChunkExtension(string input)
  268. {
  269. int idx = input.IndexOf(';');
  270. if (idx == -1)
  271. return input;
  272. return input.Substring(0, idx);
  273. }
  274. private State ReadCRLF(byte[] buffer, ref int offset, int size)
  275. {
  276. if (!_sawCR)
  277. {
  278. if ((char)buffer[offset++] != '\r')
  279. ThrowProtocolViolation("Expecting \\r");
  280. _sawCR = true;
  281. if (offset == size)
  282. return State.BodyFinished;
  283. }
  284. if (_sawCR && (char)buffer[offset++] != '\n')
  285. ThrowProtocolViolation("Expecting \\n");
  286. return State.None;
  287. }
  288. private State ReadTrailer(byte[] buffer, ref int offset, int size)
  289. {
  290. char c = '\0';
  291. // short path
  292. if (_trailerState == 2 && (char)buffer[offset] == '\r' && _saved.Length == 0)
  293. {
  294. offset++;
  295. if (offset < size && (char)buffer[offset] == '\n')
  296. {
  297. offset++;
  298. return State.None;
  299. }
  300. offset--;
  301. }
  302. int st = _trailerState;
  303. string stString = "\r\n\r";
  304. while (offset < size && st < 4)
  305. {
  306. c = (char)buffer[offset++];
  307. if ((st == 0 || st == 2) && c == '\r')
  308. {
  309. st++;
  310. continue;
  311. }
  312. if ((st == 1 || st == 3) && c == '\n')
  313. {
  314. st++;
  315. continue;
  316. }
  317. if (st > 0)
  318. {
  319. _saved.Append(stString.Substring(0, _saved.Length == 0 ? st - 2 : st));
  320. st = 0;
  321. if (_saved.Length > 4196)
  322. ThrowProtocolViolation("Error reading trailer (too long).");
  323. }
  324. }
  325. if (st < 4)
  326. {
  327. _trailerState = st;
  328. if (offset < size)
  329. ThrowProtocolViolation("Error reading trailer.");
  330. return State.Trailer;
  331. }
  332. StringReader reader = new StringReader(_saved.ToString());
  333. string line;
  334. while ((line = reader.ReadLine()) != null && line != "")
  335. _headers.Add(line);
  336. return State.None;
  337. }
  338. private static void ThrowProtocolViolation(string message)
  339. {
  340. WebException we = new WebException(message, null, WebExceptionStatus.ServerProtocolViolation, null);
  341. throw we;
  342. }
  343. }
  344. }