using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; namespace SlpModularCms.Core.Hosting.Website; /// /// Read-only access to the website files, confined to wwwroot/web. /// /// /// A file provider rather than Path.Combine with request data: /// refuses anything that resolves outside its root, which is the second line of defence behind /// . Exclusion filters are switched off on purpose, because the /// default ones hide every dot-prefixed name and would make /.well-known/ unreachable; dotfiles /// are refused earlier, by rule R3 of the resolver. /// /// The root is looked up on every call instead of once at startup: the website is delivered /// independently of the host (a CI copy, or a symlink switched to a new release) and may appear or /// be replaced while the process runs. A missing root, a vanished file or an IO error is "not /// found", never an exception. /// public sealed class WebsiteFileAccess : IFileProvider, IDisposable { private readonly string _root; private readonly ILogger _logger; private readonly Lock _gate = new(); private PhysicalFileProvider? _provider; private bool _warnedMissing; public WebsiteFileAccess(string root, ILogger logger) { _root = root; _logger = logger; } /// True when names an existing file (not a directory). public bool Exists(string relativePath) { try { var info = GetFileInfo(relativePath); return info.Exists && !info.IsDirectory; } catch (Exception ex) { _logger.LogWarning(ex, "Checking a website file failed; treating it as not found."); return false; } } /// The directory the website is served from (also where lives). public string RootPath => _root; public IFileInfo GetFileInfo(string subpath) { // The redirect map is data for the host, not a page of the site: it is never served to visitors. if (string.Equals(subpath.Trim('/'), WebsiteRedirectMap.FileName, StringComparison.OrdinalIgnoreCase)) { return new NotFoundFileInfo(subpath); } var provider = GetProvider(); return provider is null ? new NotFoundFileInfo(subpath) : provider.GetFileInfo(subpath); } public IDirectoryContents GetDirectoryContents(string subpath) => NotFoundDirectoryContents.Singleton; public IChangeToken Watch(string filter) => NullChangeToken.Singleton; public void Dispose() { lock (_gate) { _provider?.Dispose(); _provider = null; } } private PhysicalFileProvider? GetProvider() { lock (_gate) { if (_provider is not null && Directory.Exists(_root)) { return _provider; } _provider?.Dispose(); _provider = null; if (!Directory.Exists(_root)) { if (!_warnedMissing) { _warnedMissing = true; _logger.LogWarning( "The website directory {Root} does not exist; every website path answers 404 until it is delivered.", _root); } return null; } _warnedMissing = false; _provider = new PhysicalFileProvider(_root, Microsoft.Extensions.FileProviders.Physical.ExclusionFilters.None); return _provider; } } }