ChunkStream.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //
  2. // ChunkStream.cs
  3. // Copied from System.Net.ChunkStream
  4. //
  5. // Authors:
  6. // Gonzalo Paniagua Javier (gonzalo@ximian.com)
  7. //
  8. // (C) 2003 Ximian, Inc (http://www.ximian.com)
  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.Globalization;
  32. using System.IO;
  33. using System.Net;
  34. using System.Text;
  35. namespace WebSocketSharp.Net {
  36. class ChunkStream {
  37. enum State {
  38. None,
  39. Body,
  40. BodyFinished,
  41. Trailer
  42. }
  43. class Chunk {
  44. public byte [] Bytes;
  45. public int Offset;
  46. public Chunk (byte [] chunk)
  47. {
  48. this.Bytes = chunk;
  49. }
  50. public int Read (byte [] buffer, int offset, int size)
  51. {
  52. int nread = (size > Bytes.Length - Offset) ? Bytes.Length - Offset : size;
  53. Buffer.BlockCopy (Bytes, Offset, buffer, offset, nread);
  54. Offset += nread;
  55. return nread;
  56. }
  57. }
  58. internal WebHeaderCollection headers;
  59. int chunkSize;
  60. int chunkRead;
  61. State state;
  62. //byte [] waitBuffer;
  63. StringBuilder saved;
  64. bool sawCR;
  65. bool gotit;
  66. int trailerState;
  67. ArrayList chunks;
  68. public ChunkStream (byte [] buffer, int offset, int size, WebHeaderCollection headers)
  69. : this (headers)
  70. {
  71. Write (buffer, offset, size);
  72. }
  73. public ChunkStream (WebHeaderCollection headers)
  74. {
  75. this.headers = headers;
  76. saved = new StringBuilder ();
  77. chunks = new ArrayList ();
  78. chunkSize = -1;
  79. }
  80. public void ResetBuffer ()
  81. {
  82. chunkSize = -1;
  83. chunkRead = 0;
  84. chunks.Clear ();
  85. }
  86. public void WriteAndReadBack (byte [] buffer, int offset, int size, ref int read)
  87. {
  88. if (offset + read > 0)
  89. Write (buffer, offset, offset+read);
  90. read = Read (buffer, offset, size);
  91. }
  92. public int Read (byte [] buffer, int offset, int size)
  93. {
  94. return ReadFromChunks (buffer, offset, size);
  95. }
  96. int ReadFromChunks (byte [] buffer, int offset, int size)
  97. {
  98. int count = chunks.Count;
  99. int nread = 0;
  100. for (int i = 0; i < count; i++) {
  101. Chunk chunk = (Chunk) chunks [i];
  102. if (chunk == null)
  103. continue;
  104. if (chunk.Offset == chunk.Bytes.Length) {
  105. chunks [i] = null;
  106. continue;
  107. }
  108. nread += chunk.Read (buffer, offset + nread, size - nread);
  109. if (nread == size)
  110. break;
  111. }
  112. return nread;
  113. }
  114. public void Write (byte [] buffer, int offset, int size)
  115. {
  116. InternalWrite (buffer, ref offset, size);
  117. }
  118. void InternalWrite (byte [] buffer, ref int offset, int size)
  119. {
  120. if (state == State.None) {
  121. state = GetChunkSize (buffer, ref offset, size);
  122. if (state == State.None)
  123. return;
  124. saved.Length = 0;
  125. sawCR = false;
  126. gotit = false;
  127. }
  128. if (state == State.Body && offset < size) {
  129. state = ReadBody (buffer, ref offset, size);
  130. if (state == State.Body)
  131. return;
  132. }
  133. if (state == State.BodyFinished && offset < size) {
  134. state = ReadCRLF (buffer, ref offset, size);
  135. if (state == State.BodyFinished)
  136. return;
  137. sawCR = false;
  138. }
  139. if (state == State.Trailer && offset < size) {
  140. state = ReadTrailer (buffer, ref offset, size);
  141. if (state == State.Trailer)
  142. return;
  143. saved.Length = 0;
  144. sawCR = false;
  145. gotit = false;
  146. }
  147. if (offset < size)
  148. InternalWrite (buffer, ref offset, size);
  149. }
  150. public bool WantMore {
  151. get { return (chunkRead != chunkSize || chunkSize != 0 || state != State.None); }
  152. }
  153. public int ChunkLeft {
  154. get { return chunkSize - chunkRead; }
  155. }
  156. State ReadBody (byte [] buffer, ref int offset, int size)
  157. {
  158. if (chunkSize == 0)
  159. return State.BodyFinished;
  160. int diff = size - offset;
  161. if (diff + chunkRead > chunkSize)
  162. diff = chunkSize - chunkRead;
  163. byte [] chunk = new byte [diff];
  164. Buffer.BlockCopy (buffer, offset, chunk, 0, diff);
  165. chunks.Add (new Chunk (chunk));
  166. offset += diff;
  167. chunkRead += diff;
  168. return (chunkRead == chunkSize) ? State.BodyFinished : State.Body;
  169. }
  170. State GetChunkSize (byte [] buffer, ref int offset, int size)
  171. {
  172. char c = '\0';
  173. while (offset < size) {
  174. c = (char) buffer [offset++];
  175. if (c == '\r') {
  176. if (sawCR)
  177. ThrowProtocolViolation ("2 CR found");
  178. sawCR = true;
  179. continue;
  180. }
  181. if (sawCR && c == '\n')
  182. break;
  183. if (c == ' ')
  184. gotit = true;
  185. if (!gotit)
  186. saved.Append (c);
  187. if (saved.Length > 20)
  188. ThrowProtocolViolation ("chunk size too long.");
  189. }
  190. if (!sawCR || c != '\n') {
  191. if (offset < size)
  192. ThrowProtocolViolation ("Missing \\n");
  193. try {
  194. if (saved.Length > 0) {
  195. chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
  196. }
  197. } catch (Exception) {
  198. ThrowProtocolViolation ("Cannot parse chunk size.");
  199. }
  200. return State.None;
  201. }
  202. chunkRead = 0;
  203. try {
  204. chunkSize = Int32.Parse (RemoveChunkExtension (saved.ToString ()), NumberStyles.HexNumber);
  205. } catch (Exception) {
  206. ThrowProtocolViolation ("Cannot parse chunk size.");
  207. }
  208. if (chunkSize == 0) {
  209. trailerState = 2;
  210. return State.Trailer;
  211. }
  212. return State.Body;
  213. }
  214. static string RemoveChunkExtension (string input)
  215. {
  216. int idx = input.IndexOf (';');
  217. if (idx == -1)
  218. return input;
  219. return input.Substring (0, idx);
  220. }
  221. State ReadCRLF (byte [] buffer, ref int offset, int size)
  222. {
  223. if (!sawCR) {
  224. if ((char) buffer [offset++] != '\r')
  225. ThrowProtocolViolation ("Expecting \\r");
  226. sawCR = true;
  227. if (offset == size)
  228. return State.BodyFinished;
  229. }
  230. if (sawCR && (char) buffer [offset++] != '\n')
  231. ThrowProtocolViolation ("Expecting \\n");
  232. return State.None;
  233. }
  234. State ReadTrailer (byte [] buffer, ref int offset, int size)
  235. {
  236. char c = '\0';
  237. // short path
  238. if (trailerState == 2 && (char) buffer [offset] == '\r' && saved.Length == 0) {
  239. offset++;
  240. if (offset < size && (char) buffer [offset] == '\n') {
  241. offset++;
  242. return State.None;
  243. }
  244. offset--;
  245. }
  246. int st = trailerState;
  247. string stString = "\r\n\r";
  248. while (offset < size && st < 4) {
  249. c = (char) buffer [offset++];
  250. if ((st == 0 || st == 2) && c == '\r') {
  251. st++;
  252. continue;
  253. }
  254. if ((st == 1 || st == 3) && c == '\n') {
  255. st++;
  256. continue;
  257. }
  258. if (st > 0) {
  259. saved.Append (stString.Substring (0, saved.Length == 0? st-2: st));
  260. st = 0;
  261. if (saved.Length > 4196)
  262. ThrowProtocolViolation ("Error reading trailer (too long).");
  263. }
  264. }
  265. if (st < 4) {
  266. trailerState = st;
  267. if (offset < size)
  268. ThrowProtocolViolation ("Error reading trailer.");
  269. return State.Trailer;
  270. }
  271. StringReader reader = new StringReader (saved.ToString ());
  272. string line;
  273. while ((line = reader.ReadLine ()) != null && line != "")
  274. headers.Add (line);
  275. return State.None;
  276. }
  277. static void ThrowProtocolViolation (string message)
  278. {
  279. WebException we = new WebException (message, null, WebExceptionStatus.ServerProtocolViolation, null);
  280. throw we;
  281. }
  282. }
  283. }