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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
|
// <copyright file="FileService.cs" company="slskd Team">
// Copyright (c) slskd Team. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see https://www.gnu.org/licenses/.
// </copyright>
using Microsoft.Extensions.Options;
namespace slskd.Files
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security;
using System.Threading.Tasks;
using OneOf;
using Serilog;
/// <summary>
/// Manages files on disk.
/// </summary>
public class FileService : IFileService
{
/// <summary>
/// Initializes a new instance of the <see cref="FileService"/> class.
/// </summary>
public FileService(
IOptionsSnapshot<Options> optionsSnapshot)
{
OptionsSnapshot = optionsSnapshot;
}
private IEnumerable<string> AllowedDirectories => new[]
{
Path.GetFullPath(OptionsSnapshot.Value.Directories.Downloads),
Path.GetFullPath(OptionsSnapshot.Value.Directories.Incomplete),
};
private ILogger Log { get; } = Serilog.Log.ForContext<FileService>();
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
/// <summary>
/// Deletes the specified <paramref name="directories"/>.
/// </summary>
/// <remarks>
/// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are
/// contained in the result, and are not thrown.
/// </remarks>
/// <param name="directories">The directories to delete.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown if any of the specified directories have a relative path.</exception>
/// <exception cref="ArgumentException">
/// Thrown if any of the directories is an exact match for an application-controlled directory.
/// </exception>
/// <exception cref="NotFoundException">Thrown if a specified directory does not exist.</exception>
/// <exception cref="SecurityException">Thrown if a specified directory is restricted.</exception>
public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteDirectoriesAsync(params string[] directories)
{
if (directories.Any(directory => Path.GetFullPath(directory) != directory))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directories));
}
if (directories.Any(directory => AllowedDirectories.Contains(directory)))
{
throw new ArgumentException("Deletion of application-controlled directory roots is not supported");
}
// important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..'
bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed));
// if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request
if (!directories.All(directory => IsAllowed(directory)))
{
throw new SecurityException("Only application-controlled directories can be deleted");
}
await Task.Yield();
Dictionary<string, OneOf<bool, Exception>> results = new();
foreach (var directory in directories)
{
try
{
Directory.Delete(directory, recursive: true);
results.Add(directory, true);
Log.Information("Deleted directory '{Directory}'", directory);
}
catch (DirectoryNotFoundException)
{
results.Add(directory, new NotFoundException($"The directory '{directory}' does not exist"));
}
catch (UnauthorizedAccessException)
{
results.Add(directory, new SecurityException());
}
catch (Exception ex)
{
results.Add(directory, ex);
}
}
return results;
}
/// <summary>
/// Deletes the specified <paramref name="files"/>.
/// </summary>
/// <remarks>
/// Returns a dictionary keyed on directory name and containing a result for each specified directory. Exceptions are
/// contained in the result, and are not thrown.
/// </remarks>
/// <param name="files">The list of files to delete.</param>
/// <returns>The operation context.</returns>
/// <exception cref="ArgumentException">Thrown if any of the specified files have a relative path.</exception>
/// <exception cref="NotFoundException">Thrown if a specified file does not exist.</exception>
/// <exception cref="SecurityException">Thrown if a specified file is restricted.</exception>
public async Task<Dictionary<string, OneOf<bool, Exception>>> DeleteFilesAsync(params string[] files)
{
if (files.Any(file => Path.GetFullPath(file) != file))
{
throw new ArgumentException("Only absolute paths may be specified", nameof(files));
}
// important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..'
bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed));
// if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request
if (!files.All(file => IsAllowed(file)))
{
throw new SecurityException("Only files in application-controlled directories can be deleted");
}
await Task.Yield();
Dictionary<string, OneOf<bool, Exception>> results = new();
foreach (var file in files)
{
try
{
File.Delete(file);
results.Add(file, true);
}
catch (FileNotFoundException)
{
results.Add(file, new NotFoundException($"The file '{file}' does not exist"));
}
catch (UnauthorizedAccessException)
{
results.Add(file, new SecurityException());
}
catch (Exception ex)
{
results.Add(file, ex);
}
}
return results;
}
/// <summary>
/// Lists the contents in the specified <paramref name="directory"/>, optionally applying the specified <paramref name="enumerationOptions"/>.
/// </summary>
/// <param name="directory">The directory from which to start the listing.</param>
/// <param name="enumerationOptions">Optional enumeration options to apply.</param>
/// <returns>The list of found contents.</returns>
/// <exception cref="ArgumentException">Thrown if the specified directory has a relative path.</exception>
/// <exception cref="NotFoundException">Thrown if the specified directory does not exist.</exception>
/// <exception cref="SecurityException">Thrown if the specified root directory is restricted.</exception>
public async Task<FilesystemDirectory> ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null)
{
if (Path.GetFullPath(directory) != directory)
{
throw new ArgumentException("Only absolute paths may be specified", nameof(directory));
}
// important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..'
if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed)))
{
throw new SecurityException($"For security reasons, only application-controlled directories can be deleted");
}
if (!Directory.Exists(directory))
{
throw new NotFoundException($"The directory '{directory}' does not exist");
}
return await Task.Run(() =>
{
var dir = new DirectoryInfo(directory);
try
{
var contents = dir.GetFileSystemInfos("*", enumerationOptions);
var files = contents
.OfType<FileInfo>()
.Select(f => FilesystemFile.FromFileInfo(f) with
{
FullName = f.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'),
});
var dirs = contents
.OfType<DirectoryInfo>()
.Select(d => FilesystemDirectory.FromDirectoryInfo(d) with
{
FullName = d.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'),
});
var response = FilesystemDirectory.FromDirectoryInfo(dir) with
{
FullName = dir.FullName.ReplaceFirst(directory, string.Empty).TrimStart('\\', '/'),
Files = files,
Directories = dirs,
};
return response;
}
catch (UnauthorizedAccessException ex)
{
throw new SecurityException($"Access to '{directory}' was denied", ex);
}
});
}
}
}
|