SymlinkFollowingPhysicalFileResultExecutor.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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 Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength)
  66. {
  67. if (context == null)
  68. {
  69. throw new ArgumentNullException(nameof(context));
  70. }
  71. if (result == null)
  72. {
  73. throw new ArgumentNullException(nameof(result));
  74. }
  75. if (range != null && rangeLength == 0)
  76. {
  77. return Task.CompletedTask;
  78. }
  79. // It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code
  80. if (!IsSymLink(result.FileName))
  81. {
  82. return base.WriteFileAsync(context, result, range, rangeLength);
  83. }
  84. var response = context.HttpContext.Response;
  85. if (range != null)
  86. {
  87. return SendFileAsync(
  88. result.FileName,
  89. response,
  90. offset: range.From ?? 0L,
  91. count: rangeLength);
  92. }
  93. return SendFileAsync(
  94. result.FileName,
  95. response,
  96. offset: 0,
  97. count: null);
  98. }
  99. private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count)
  100. {
  101. var fileInfo = GetFileInfo(filePath);
  102. if (offset < 0 || offset > fileInfo.Length)
  103. {
  104. throw new ArgumentOutOfRangeException(nameof(offset), offset, string.Empty);
  105. }
  106. if (count.HasValue
  107. && (count.Value < 0 || count.Value > fileInfo.Length - offset))
  108. {
  109. throw new ArgumentOutOfRangeException(nameof(count), count, string.Empty);
  110. }
  111. // Copied from SendFileFallback.SendFileAsync
  112. const int BufferSize = 1024 * 16;
  113. var fileStream = new FileStream(
  114. filePath,
  115. FileMode.Open,
  116. FileAccess.Read,
  117. FileShare.ReadWrite,
  118. bufferSize: BufferSize,
  119. options: FileOptions.Asynchronous | FileOptions.SequentialScan);
  120. await using (fileStream.ConfigureAwait(false))
  121. {
  122. fileStream.Seek(offset, SeekOrigin.Begin);
  123. await StreamCopyOperation
  124. .CopyToAsync(fileStream, response.Body, count, BufferSize, CancellationToken.None)
  125. .ConfigureAwait(true);
  126. }
  127. }
  128. private static bool IsSymLink(string path) => (File.GetAttributes(path) & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
  129. }
  130. }