HttpResponseStream.Managed.cs 16 KB

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