ResponseStream.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. #region License
  2. /*
  3. * ResponseStream.cs
  4. *
  5. * This code is derived from ResponseStream.cs (System.Net) of Mono
  6. * (http://www.mono-project.com).
  7. *
  8. * The MIT License
  9. *
  10. * Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
  11. * Copyright (c) 2012-2020 sta.blockhead
  12. *
  13. * Permission is hereby granted, free of charge, to any person obtaining a copy
  14. * of this software and associated documentation files (the "Software"), to deal
  15. * in the Software without restriction, including without limitation the rights
  16. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  17. * copies of the Software, and to permit persons to whom the Software is
  18. * furnished to do so, subject to the following conditions:
  19. *
  20. * The above copyright notice and this permission notice shall be included in
  21. * all copies or substantial portions of the Software.
  22. *
  23. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  24. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  25. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  27. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  28. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29. * THE SOFTWARE.
  30. */
  31. #endregion
  32. #region Authors
  33. /*
  34. * Authors:
  35. * - Gonzalo Paniagua Javier <gonzalo@novell.com>
  36. */
  37. #endregion
  38. using System;
  39. using System.IO;
  40. using System.Text;
  41. namespace WebSocketSharp.Net
  42. {
  43. internal class ResponseStream : Stream
  44. {
  45. #region Private Fields
  46. private MemoryStream _bodyBuffer;
  47. private static readonly byte[] _crlf;
  48. private bool _disposed;
  49. private Stream _innerStream;
  50. private static readonly byte[] _lastChunk;
  51. private static readonly int _maxHeadersLength;
  52. private HttpListenerResponse _response;
  53. private bool _sendChunked;
  54. private Action<byte[], int, int> _write;
  55. private Action<byte[], int, int> _writeBody;
  56. private Action<byte[], int, int> _writeChunked;
  57. #endregion
  58. #region Static Constructor
  59. static ResponseStream ()
  60. {
  61. _crlf = new byte[] { 13, 10 }; // "\r\n"
  62. _lastChunk = new byte[] { 48, 13, 10, 13, 10 }; // "0\r\n\r\n"
  63. _maxHeadersLength = 32768;
  64. }
  65. #endregion
  66. #region Internal Constructors
  67. internal ResponseStream (
  68. Stream innerStream,
  69. HttpListenerResponse response,
  70. bool ignoreWriteExceptions
  71. )
  72. {
  73. _innerStream = innerStream;
  74. _response = response;
  75. if (ignoreWriteExceptions) {
  76. _write = writeWithoutThrowingException;
  77. _writeChunked = writeChunkedWithoutThrowingException;
  78. }
  79. else {
  80. _write = innerStream.Write;
  81. _writeChunked = writeChunked;
  82. }
  83. _bodyBuffer = new MemoryStream ();
  84. }
  85. #endregion
  86. #region Public Properties
  87. public override bool CanRead {
  88. get {
  89. return false;
  90. }
  91. }
  92. public override bool CanSeek {
  93. get {
  94. return false;
  95. }
  96. }
  97. public override bool CanWrite {
  98. get {
  99. return !_disposed;
  100. }
  101. }
  102. public override long Length {
  103. get {
  104. throw new NotSupportedException ();
  105. }
  106. }
  107. public override long Position {
  108. get {
  109. throw new NotSupportedException ();
  110. }
  111. set {
  112. throw new NotSupportedException ();
  113. }
  114. }
  115. #endregion
  116. #region Private Methods
  117. private bool flush (bool closing)
  118. {
  119. if (!_response.HeadersSent) {
  120. if (!flushHeaders ())
  121. return false;
  122. _response.HeadersSent = true;
  123. _sendChunked = _response.SendChunked;
  124. _writeBody = _sendChunked ? _writeChunked : _write;
  125. }
  126. flushBody (closing);
  127. return true;
  128. }
  129. private void flushBody (bool closing)
  130. {
  131. using (_bodyBuffer) {
  132. var len = _bodyBuffer.Length;
  133. if (len > Int32.MaxValue) {
  134. _bodyBuffer.Position = 0;
  135. var buffLen = 1024;
  136. var buff = new byte[buffLen];
  137. var nread = 0;
  138. while (true) {
  139. nread = _bodyBuffer.Read (buff, 0, buffLen);
  140. if (nread <= 0)
  141. break;
  142. _writeBody (buff, 0, nread);
  143. }
  144. }
  145. else if (len > 0) {
  146. _writeBody (_bodyBuffer.GetBuffer (), 0, (int) len);
  147. }
  148. }
  149. if (!closing) {
  150. _bodyBuffer = new MemoryStream ();
  151. return;
  152. }
  153. if (_sendChunked)
  154. _write (_lastChunk, 0, 5);
  155. _bodyBuffer = null;
  156. }
  157. private bool flushHeaders ()
  158. {
  159. if (!_response.SendChunked) {
  160. if (_response.ContentLength64 != _bodyBuffer.Length)
  161. return false;
  162. }
  163. var statusLine = _response.StatusLine;
  164. var headers = _response.FullHeaders;
  165. var buff = new MemoryStream ();
  166. var enc = Encoding.UTF8;
  167. using (var writer = new StreamWriter (buff, enc, 256)) {
  168. writer.Write (statusLine);
  169. writer.Write (headers.ToStringMultiValue (true));
  170. writer.Flush ();
  171. var start = enc.GetPreamble ().Length;
  172. var len = buff.Length - start;
  173. if (len > _maxHeadersLength)
  174. return false;
  175. _write (buff.GetBuffer (), start, (int) len);
  176. }
  177. _response.CloseConnection = headers["Connection"] == "close";
  178. return true;
  179. }
  180. private static byte[] getChunkSizeBytes (int size)
  181. {
  182. var chunkSize = String.Format ("{0:x}\r\n", size);
  183. return Encoding.ASCII.GetBytes (chunkSize);
  184. }
  185. private void writeChunked (byte[] buffer, int offset, int count)
  186. {
  187. var size = getChunkSizeBytes (count);
  188. _innerStream.Write (size, 0, size.Length);
  189. _innerStream.Write (buffer, offset, count);
  190. _innerStream.Write (_crlf, 0, 2);
  191. }
  192. private void writeChunkedWithoutThrowingException (
  193. byte[] buffer, int offset, int count
  194. )
  195. {
  196. try {
  197. writeChunked (buffer, offset, count);
  198. }
  199. catch {
  200. }
  201. }
  202. private void writeWithoutThrowingException (
  203. byte[] buffer, int offset, int count
  204. )
  205. {
  206. try {
  207. _innerStream.Write (buffer, offset, count);
  208. }
  209. catch {
  210. }
  211. }
  212. #endregion
  213. #region Internal Methods
  214. internal void Close (bool force)
  215. {
  216. if (_disposed)
  217. return;
  218. _disposed = true;
  219. if (!force) {
  220. if (flush (true)) {
  221. _response.Close ();
  222. _response = null;
  223. _innerStream = null;
  224. return;
  225. }
  226. _response.CloseConnection = true;
  227. }
  228. if (_sendChunked)
  229. _write (_lastChunk, 0, 5);
  230. _bodyBuffer.Dispose ();
  231. _response.Abort ();
  232. _bodyBuffer = null;
  233. _response = null;
  234. _innerStream = null;
  235. }
  236. internal void InternalWrite (byte[] buffer, int offset, int count)
  237. {
  238. _write (buffer, offset, count);
  239. }
  240. #endregion
  241. #region Public Methods
  242. public override IAsyncResult BeginRead (
  243. byte[] buffer,
  244. int offset,
  245. int count,
  246. AsyncCallback callback,
  247. object state
  248. )
  249. {
  250. throw new NotSupportedException ();
  251. }
  252. public override IAsyncResult BeginWrite (
  253. byte[] buffer,
  254. int offset,
  255. int count,
  256. AsyncCallback callback,
  257. object state
  258. )
  259. {
  260. if (_disposed) {
  261. var name = GetType ().ToString ();
  262. throw new ObjectDisposedException (name);
  263. }
  264. return _bodyBuffer.BeginWrite (buffer, offset, count, callback, state);
  265. }
  266. public override void Close ()
  267. {
  268. Close (false);
  269. }
  270. protected override void Dispose (bool disposing)
  271. {
  272. Close (!disposing);
  273. }
  274. public override int EndRead (IAsyncResult asyncResult)
  275. {
  276. throw new NotSupportedException ();
  277. }
  278. public override void EndWrite (IAsyncResult asyncResult)
  279. {
  280. if (_disposed) {
  281. var name = GetType ().ToString ();
  282. throw new ObjectDisposedException (name);
  283. }
  284. _bodyBuffer.EndWrite (asyncResult);
  285. }
  286. public override void Flush ()
  287. {
  288. if (_disposed)
  289. return;
  290. var sendChunked = _sendChunked || _response.SendChunked;
  291. if (!sendChunked)
  292. return;
  293. flush (false);
  294. }
  295. public override int Read (byte[] buffer, int offset, int count)
  296. {
  297. throw new NotSupportedException ();
  298. }
  299. public override long Seek (long offset, SeekOrigin origin)
  300. {
  301. throw new NotSupportedException ();
  302. }
  303. public override void SetLength (long value)
  304. {
  305. throw new NotSupportedException ();
  306. }
  307. public override void Write (byte[] buffer, int offset, int count)
  308. {
  309. if (_disposed) {
  310. var name = GetType ().ToString ();
  311. throw new ObjectDisposedException (name);
  312. }
  313. _bodyBuffer.Write (buffer, offset, count);
  314. }
  315. #endregion
  316. }
  317. }