SymlinkFollowingPhysicalFileResultExecutor.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 Microsoft.AspNetCore.Http;
  29. using Microsoft.AspNetCore.Http.Extensions;
  30. using Microsoft.AspNetCore.Mvc;
  31. using Microsoft.AspNetCore.Mvc.Infrastructure;
  32. using Microsoft.Extensions.Logging;
  33. using Microsoft.Net.Http.Headers;
  34. namespace Jellyfin.Server.Infrastructure
  35. {
  36. /// <inheritdoc />
  37. public class SymlinkFollowingPhysicalFileResultExecutor : PhysicalFileResultExecutor
  38. {
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="SymlinkFollowingPhysicalFileResultExecutor"/> class.
  41. /// </summary>
  42. /// <param name="loggerFactory">An instance of the <see cref="ILoggerFactory"/> interface.</param>
  43. public SymlinkFollowingPhysicalFileResultExecutor(ILoggerFactory loggerFactory) : base(loggerFactory)
  44. {
  45. }
  46. /// <inheritdoc />
  47. protected override FileMetadata GetFileInfo(string path)
  48. {
  49. var fileInfo = new FileInfo(path);
  50. var length = fileInfo.Length;
  51. // This may or may not be fixed in .NET 6, but looks like it will not https://github.com/dotnet/aspnetcore/issues/34371
  52. if ((fileInfo.Attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
  53. {
  54. using var fileHandle = File.OpenHandle(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
  55. length = RandomAccess.GetLength(fileHandle);
  56. }
  57. return new FileMetadata
  58. {
  59. Exists = fileInfo.Exists,
  60. Length = length,
  61. LastModified = fileInfo.LastWriteTimeUtc
  62. };
  63. }
  64. /// <inheritdoc />
  65. protected override async Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength)
  66. {
  67. ArgumentNullException.ThrowIfNull(context);
  68. ArgumentNullException.ThrowIfNull(result);
  69. if (range is not null && rangeLength == 0)
  70. {
  71. return;
  72. }
  73. // It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code
  74. if (!IsSymLink(result.FileName))
  75. {
  76. await base.WriteFileAsync(context, result, range, rangeLength).ConfigureAwait(false);
  77. return;
  78. }
  79. var response = context.HttpContext.Response;
  80. if (range is not null)
  81. {
  82. await SendFileAsync(
  83. result.FileName,
  84. response,
  85. offset: range.From ?? 0L,
  86. count: rangeLength).ConfigureAwait(false);
  87. return;
  88. }
  89. await SendFileAsync(
  90. result.FileName,
  91. response,
  92. offset: 0,
  93. count: null).ConfigureAwait(false);
  94. }
  95. private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count)
  96. {
  97. var fileInfo = GetFileInfo(filePath);
  98. if (offset < 0 || offset > fileInfo.Length)
  99. {
  100. throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
  101. }
  102. if (count.HasValue
  103. && (count.Value < 0 || count.Value > fileInfo.Length - offset))
  104. {
  105. throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
  106. }
  107. // Copied from SendFileFallback.SendFileAsync
  108. const int BufferSize = 1024 * 16;
  109. var fileStream = new FileStream(
  110. filePath,
  111. FileMode.Open,
  112. FileAccess.Read,
  113. FileShare.ReadWrite,
  114. bufferSize: BufferSize,
  115. options: FileOptions.Asynchronous | FileOptions.SequentialScan);
  116. await using (fileStream.ConfigureAwait(false))
  117. {
  118. fileStream.Seek(offset, SeekOrigin.Begin);
  119. await StreamCopyOperation
  120. .CopyToAsync(fileStream, response.Body, count, BufferSize, CancellationToken.None)
  121. .ConfigureAwait(true);
  122. }
  123. }
  124. private static bool IsSymLink(string path) => (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
  125. }
  126. }