HttpResponseStream.Managed.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Runtime.ExceptionServices;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using MediaBrowser.Model.IO;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.System;
  13. namespace SocketHttpListener.Net
  14. {
  15. // Licensed to the .NET Foundation under one or more agreements.
  16. // See the LICENSE file in the project root for more information.
  17. //
  18. // System.Net.ResponseStream
  19. //
  20. // Author:
  21. // Gonzalo Paniagua Javier (gonzalo@novell.com)
  22. //
  23. // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
  24. //
  25. // Permission is hereby granted, free of charge, to any person obtaining
  26. // a copy of this software and associated documentation files (the
  27. // "Software"), to deal in the Software without restriction, including
  28. // without limitation the rights to use, copy, modify, merge, publish,
  29. // distribute, sublicense, and/or sell copies of the Software, and to
  30. // permit persons to whom the Software is furnished to do so, subject to
  31. // the following conditions:
  32. //
  33. // The above copyright notice and this permission notice shall be
  34. // included in all copies or substantial portions of the Software.
  35. //
  36. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  37. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  38. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  39. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  40. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  41. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  42. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  43. //
  44. internal partial class HttpResponseStream : Stream
  45. {
  46. private HttpListenerResponse _response;
  47. private bool _ignore_errors;
  48. private bool _trailer_sent;
  49. private Stream _stream;
  50. private readonly IStreamHelper _streamHelper;
  51. private readonly Socket _socket;
  52. private readonly bool _supportsDirectSocketAccess;
  53. private readonly IEnvironmentInfo _environment;
  54. private readonly IFileSystem _fileSystem;
  55. private readonly ILogger _logger;
  56. internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors, IStreamHelper streamHelper, Socket socket, bool supportsDirectSocketAccess, IEnvironmentInfo environment, IFileSystem fileSystem, ILogger logger)
  57. {
  58. _response = response;
  59. _ignore_errors = ignore_errors;
  60. _streamHelper = streamHelper;
  61. _socket = socket;
  62. _supportsDirectSocketAccess = supportsDirectSocketAccess;
  63. _environment = environment;
  64. _fileSystem = fileSystem;
  65. _logger = logger;
  66. _stream = stream;
  67. }
  68. private void DisposeCore()
  69. {
  70. byte[] bytes = null;
  71. MemoryStream ms = GetHeaders(true);
  72. bool chunked = _response.SendChunked;
  73. if (_stream.CanWrite)
  74. {
  75. try
  76. {
  77. if (ms != null)
  78. {
  79. long start = ms.Position;
  80. if (chunked && !_trailer_sent)
  81. {
  82. bytes = GetChunkSizeBytes(0, true);
  83. ms.Position = ms.Length;
  84. ms.Write(bytes, 0, bytes.Length);
  85. }
  86. InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
  87. _trailer_sent = true;
  88. }
  89. else if (chunked && !_trailer_sent)
  90. {
  91. bytes = GetChunkSizeBytes(0, true);
  92. InternalWrite(bytes, 0, bytes.Length);
  93. _trailer_sent = true;
  94. }
  95. }
  96. catch (HttpListenerException)
  97. {
  98. // Ignore error due to connection reset by peer
  99. }
  100. }
  101. _response.Close();
  102. }
  103. internal async Task WriteWebSocketHandshakeHeadersAsync()
  104. {
  105. if (_closed)
  106. throw new ObjectDisposedException(GetType().ToString());
  107. if (_stream.CanWrite)
  108. {
  109. MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true);
  110. bool chunked = _response.SendChunked;
  111. long start = ms.Position;
  112. if (chunked)
  113. {
  114. byte[] bytes = GetChunkSizeBytes(0, true);
  115. ms.Position = ms.Length;
  116. ms.Write(bytes, 0, bytes.Length);
  117. }
  118. await InternalWriteAsync(ms.GetBuffer(), (int)start, (int)(ms.Length - start)).ConfigureAwait(false);
  119. await _stream.FlushAsync().ConfigureAwait(false);
  120. }
  121. }
  122. private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false)
  123. {
  124. //// SendHeaders works on shared headers
  125. //lock (_response.headers_lock)
  126. //{
  127. // if (_response.HeadersSent)
  128. // return null;
  129. // var ms = CreateNew();
  130. // _response.SendHeaders(closing, ms);
  131. // return ms;
  132. //}
  133. // SendHeaders works on shared headers
  134. lock (_response._headersLock)
  135. {
  136. if (_response.SentHeaders)
  137. {
  138. return null;
  139. }
  140. MemoryStream ms = new MemoryStream();
  141. _response.SendHeaders(closing, ms, isWebSocketHandshake);
  142. return ms;
  143. }
  144. }
  145. private static byte[] s_crlf = new byte[] { 13, 10 };
  146. private static byte[] GetChunkSizeBytes(int size, bool final)
  147. {
  148. string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : "");
  149. return Encoding.ASCII.GetBytes(str);
  150. }
  151. internal void InternalWrite(byte[] buffer, int offset, int count)
  152. {
  153. if (_ignore_errors)
  154. {
  155. try
  156. {
  157. _stream.Write(buffer, offset, count);
  158. }
  159. catch { }
  160. }
  161. else
  162. {
  163. _stream.Write(buffer, offset, count);
  164. }
  165. }
  166. internal Task InternalWriteAsync(byte[] buffer, int offset, int count) =>
  167. _ignore_errors ? InternalWriteIgnoreErrorsAsync(buffer, offset, count) : _stream.WriteAsync(buffer, offset, count);
  168. private async Task InternalWriteIgnoreErrorsAsync(byte[] buffer, int offset, int count)
  169. {
  170. try { await _stream.WriteAsync(buffer, offset, count).ConfigureAwait(false); }
  171. catch { }
  172. }
  173. private void WriteCore(byte[] buffer, int offset, int size)
  174. {
  175. if (size == 0)
  176. return;
  177. byte[] bytes = null;
  178. MemoryStream ms = GetHeaders(false);
  179. bool chunked = _response.SendChunked;
  180. if (ms != null)
  181. {
  182. long start = ms.Position; // After the possible preamble for the encoding
  183. ms.Position = ms.Length;
  184. if (chunked)
  185. {
  186. bytes = GetChunkSizeBytes(size, false);
  187. ms.Write(bytes, 0, bytes.Length);
  188. }
  189. int new_count = Math.Min(size, 16384 - (int)ms.Position + (int)start);
  190. ms.Write(buffer, offset, new_count);
  191. size -= new_count;
  192. offset += new_count;
  193. InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start));
  194. ms.SetLength(0);
  195. ms.Capacity = 0; // 'dispose' the buffer in ms.
  196. }
  197. else if (chunked)
  198. {
  199. bytes = GetChunkSizeBytes(size, false);
  200. InternalWrite(bytes, 0, bytes.Length);
  201. }
  202. if (size > 0)
  203. InternalWrite(buffer, offset, size);
  204. if (chunked)
  205. InternalWrite(s_crlf, 0, 2);
  206. }
  207. private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state)
  208. {
  209. if (_closed)
  210. {
  211. HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this);
  212. ares._callback = cback;
  213. ares._state = state;
  214. ares.Complete();
  215. return ares;
  216. }
  217. byte[] bytes = null;
  218. MemoryStream ms = GetHeaders(false);
  219. bool chunked = _response.SendChunked;
  220. if (ms != null)
  221. {
  222. long start = ms.Position;
  223. ms.Position = ms.Length;
  224. if (chunked)
  225. {
  226. bytes = GetChunkSizeBytes(size, false);
  227. ms.Write(bytes, 0, bytes.Length);
  228. }
  229. ms.Write(buffer, offset, size);
  230. buffer = ms.GetBuffer();
  231. offset = (int)start;
  232. size = (int)(ms.Position - start);
  233. }
  234. else if (chunked)
  235. {
  236. bytes = GetChunkSizeBytes(size, false);
  237. InternalWrite(bytes, 0, bytes.Length);
  238. }
  239. return _stream.BeginWrite(buffer, offset, size, cback, state);
  240. }
  241. private void EndWriteCore(IAsyncResult asyncResult)
  242. {
  243. if (_closed)
  244. return;
  245. if (_ignore_errors)
  246. {
  247. try
  248. {
  249. _stream.EndWrite(asyncResult);
  250. if (_response.SendChunked)
  251. _stream.Write(s_crlf, 0, 2);
  252. }
  253. catch { }
  254. }
  255. else
  256. {
  257. _stream.EndWrite(asyncResult);
  258. if (_response.SendChunked)
  259. _stream.Write(s_crlf, 0, 2);
  260. }
  261. }
  262. public Task TransmitFile(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
  263. {
  264. return TransmitFileManaged(path, offset, count, fileShareMode, cancellationToken);
  265. }
  266. const int StreamCopyToBufferSize = 81920;
  267. private async Task TransmitFileManaged(string path, long offset, long count, FileShareMode fileShareMode, CancellationToken cancellationToken)
  268. {
  269. var allowAsync = _environment.OperatingSystem != MediaBrowser.Model.System.OperatingSystem.Windows;
  270. //if (count <= 0)
  271. //{
  272. // allowAsync = true;
  273. //}
  274. var fileOpenOptions = FileOpenOptions.SequentialScan;
  275. if (allowAsync)
  276. {
  277. fileOpenOptions |= FileOpenOptions.Asynchronous;
  278. }
  279. // use non-async filestream along with read due to https://github.com/dotnet/corefx/issues/6039
  280. using (var fs = _fileSystem.GetFileStream(path, FileOpenMode.Open, FileAccessMode.Read, fileShareMode, fileOpenOptions))
  281. {
  282. if (offset > 0)
  283. {
  284. fs.Position = offset;
  285. }
  286. var targetStream = this;
  287. if (count > 0)
  288. {
  289. await _streamHelper.CopyToAsync(fs, targetStream, count, cancellationToken).ConfigureAwait(false);
  290. }
  291. else
  292. {
  293. await fs.CopyToAsync(targetStream, StreamCopyToBufferSize, cancellationToken).ConfigureAwait(false);
  294. }
  295. }
  296. }
  297. }
  298. }