SymlinkFollowingPhysicalFileResultExecutor.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // The MIT License (MIT)
  2. //
  3. // Copyright (c) .NET Foundation and Contributors
  4. //
  5. // All rights reserved.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in all
  15. // copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. // SOFTWARE.
  24. using System;
  25. using System.IO;
  26. using System.Threading;
  27. using System.Threading.Tasks;
  28. using MediaBrowser.Model.IO;
  29. using Microsoft.AspNetCore.Http;
  30. using Microsoft.AspNetCore.Http.Extensions;
  31. using Microsoft.AspNetCore.Mvc;
  32. using Microsoft.AspNetCore.Mvc.Infrastructure;
  33. using Microsoft.Extensions.Logging;
  34. using Microsoft.Net.Http.Headers;
  35. namespace Jellyfin.Server.Infrastructure
  36. {
  37. /// <inheritdoc />
  38. public class SymlinkFollowingPhysicalFileResultExecutor : PhysicalFileResultExecutor
  39. {
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="SymlinkFollowingPhysicalFileResultExecutor"/> class.
  42. /// </summary>
  43. /// <param name="loggerFactory">An instance of the <see cref="ILoggerFactory"/> interface.</param>
  44. public SymlinkFollowingPhysicalFileResultExecutor(ILoggerFactory loggerFactory) : base(loggerFactory)
  45. {
  46. }
  47. /// <inheritdoc />
  48. protected override FileMetadata GetFileInfo(string path)
  49. {
  50. var fileInfo = new FileInfo(path);
  51. var length = fileInfo.Length;
  52. // This may or may not be fixed in .NET 6, but looks like it will not https://github.com/dotnet/aspnetcore/issues/34371
  53. if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
  54. {
  55. using Stream thisFileStream = File.OpenRead(path);
  56. length = thisFileStream.Length;
  57. }
  58. return new FileMetadata
  59. {
  60. Exists = fileInfo.Exists,
  61. Length = length,
  62. LastModified = fileInfo.LastWriteTimeUtc
  63. };
  64. }
  65. /// <inheritdoc />
  66. protected override Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength)
  67. {
  68. if (context == null)
  69. {
  70. throw new ArgumentNullException(nameof(context));
  71. }
  72. if (result == null)
  73. {
  74. throw new ArgumentNullException(nameof(result));
  75. }
  76. if (range != null && rangeLength == 0)
  77. {
  78. return Task.CompletedTask;
  79. }
  80. // It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code
  81. if (!IsSymLink(result.FileName))
  82. {
  83. return base.WriteFileAsync(context, result, range, rangeLength);
  84. }
  85. var response = context.HttpContext.Response;
  86. if (range != null)
  87. {
  88. return SendFileAsync(
  89. result.FileName,
  90. response,
  91. offset: range.From ?? 0L,
  92. count: rangeLength);
  93. }
  94. return SendFileAsync(
  95. result.FileName,
  96. response,
  97. offset: 0,
  98. count: null);
  99. }
  100. private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count)
  101. {
  102. var fileInfo = GetFileInfo(filePath);
  103. if (offset < 0 || offset > fileInfo.Length)
  104. {
  105. throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
  106. }
  107. if (count.HasValue
  108. && (count.Value < 0 || count.Value > fileInfo.Length - offset))
  109. {
  110. throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
  111. }
  112. // Copied from SendFileFallback.SendFileAsync
  113. const int BufferSize = 1024 * 16;
  114. await using var fileStream = new FileStream(
  115. filePath,
  116. FileMode.Open,
  117. FileAccess.Read,
  118. FileShare.ReadWrite,
  119. bufferSize: BufferSize,
  120. options: (AsyncFile.UseAsyncIO ? FileOptions.Asynchronous : FileOptions.None) | FileOptions.SequentialScan);
  121. fileStream.Seek(offset, SeekOrigin.Begin);
  122. await StreamCopyOperation
  123. .CopyToAsync(fileStream, response.Body, count, BufferSize, CancellationToken.None)
  124. .ConfigureAwait(true);
  125. }
  126. private static bool IsSymLink(string path) => (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
  127. }
  128. }