aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/ResourceFileManager.cs
blob: 8c1f765e2790c91b50e8cf4ec73aea69824a355c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.IO;
using System.Threading.Tasks;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.Services;
using Microsoft.Extensions.Logging;

namespace Emby.Server.Implementations
{
    public class ResourceFileManager : IResourceFileManager
    {
        private readonly IFileSystem _fileSystem;
        private readonly ILogger _logger;
        private readonly IHttpResultFactory _resultFactory;

        public ResourceFileManager(
            IHttpResultFactory resultFactory,
            ILoggerFactory loggerFactory,
            IFileSystem fileSystem)
        {
            _resultFactory = resultFactory;
            _logger = loggerFactory.CreateLogger("ResourceManager");
            _fileSystem = fileSystem;
        }

        public Stream GetResourceFileStream(string basePath, string virtualPath)
        {
            return _fileSystem.GetFileStream(GetResourcePath(basePath, virtualPath), FileOpenMode.Open, FileAccessMode.Read, FileShareMode.ReadWrite, true);
        }

        public Task<object> GetStaticFileResult(IRequest request, string basePath, string virtualPath, string contentType, TimeSpan? cacheDuration)
        {
            return _resultFactory.GetStaticFileResult(request, GetResourcePath(basePath, virtualPath));
        }

        public string ReadAllText(string basePath, string virtualPath)
        {
            return _fileSystem.ReadAllText(GetResourcePath(basePath, virtualPath));
        }

        private string GetResourcePath(string basePath, string virtualPath)
        {
            var fullPath = Path.Combine(basePath, virtualPath.Replace('/', Path.DirectorySeparatorChar));

            try
            {
                fullPath = Path.GetFullPath(fullPath);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in Path.GetFullPath");
            }

            // Don't allow file system access outside of the source folder
            if (!_fileSystem.ContainsSubPath(basePath, fullPath))
            {
                throw new SecurityException("Access denied");
            }

            return fullPath;
        }
    }
}