HttpResponseStream.Managed.cs 12 KB

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