-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathBaseDokanyCallbacks.cs
More file actions
440 lines (364 loc) · 16.1 KB
/
BaseDokanyCallbacks.cs
File metadata and controls
440 lines (364 loc) · 16.1 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
using DokanNet;
using SecureFolderFS.Core.Dokany.Helpers;
using SecureFolderFS.Core.FileSystem;
using SecureFolderFS.Core.FileSystem.AppModels;
using SecureFolderFS.Core.FileSystem.Exceptions;
using SecureFolderFS.Core.FileSystem.OpenHandles;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using System.Security.Cryptography;
using FileAccess = DokanNet.FileAccess;
namespace SecureFolderFS.Core.Dokany.Callbacks
{
internal abstract class BaseDokanyCallbacks : IDokanOperationsUnsafe, IDisposable
{
protected readonly FileSystemSpecifics specifics;
protected readonly BaseHandlesManager handlesManager;
protected readonly VolumeModel volumeModel;
protected BaseDokanyCallbacks(FileSystemSpecifics specifics, BaseHandlesManager handlesManager, VolumeModel volumeModel)
{
this.specifics = specifics;
this.handlesManager = handlesManager;
this.volumeModel = volumeModel;
}
#region Unused
/// <inheritdoc/>
public NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, IDokanFileInfo info)
{
bytesWritten = 0;
return DokanResult.NotImplemented;
}
/// <inheritdoc/>
public NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, IDokanFileInfo info)
{
bytesRead = 0;
return DokanResult.NotImplemented;
}
#endregion
/// <inheritdoc/>
public virtual void CloseFile(string fileName, IDokanFileInfo info)
{
_ = fileName;
CloseHandle(info);
InvalidateContext(info);
}
/// <inheritdoc/>
public virtual NtStatus FlushFileBuffers(string fileName, IDokanFileInfo info)
{
if (handlesManager.GetHandle<FileHandle>(GetContextValue(info)) is not { } fileHandle)
return Trace(DokanResult.InvalidHandle, fileName, info);
try
{
fileHandle.Stream.Flush();
return Trace(DokanResult.Success, fileName, info);
}
catch (IOException)
{
return DokanResult.DiskFull;
}
}
/// <inheritdoc/>
public virtual NtStatus FindFiles(string fileName, out IList<FileInformation> files, IDokanFileInfo info)
{
return FindFilesWithPattern(fileName, "*", out files, info);
}
/// <inheritdoc/>
public virtual NtStatus SetEndOfFile(string fileName, long length, IDokanFileInfo info)
{
if (specifics.Options.IsReadOnly)
return Trace(DokanResult.AccessDenied, fileName, info);
if (handlesManager.GetHandle<FileHandle>(GetContextValue(info)) is not { } fileHandle)
return Trace(DokanResult.InvalidHandle, fileName, info);
fileHandle.Stream.SetLength(length);
return Trace(DokanResult.Success, fileName, info);
}
/// <inheritdoc/>
public virtual NtStatus SetAllocationSize(string fileName, long length, IDokanFileInfo info)
{
return SetEndOfFile(fileName, length, info);
}
/// <inheritdoc/>
public virtual NtStatus GetVolumeInformation(out string volumeLabel, out FileSystemFeatures features, out string fileSystemName,
out uint maximumComponentLength, IDokanFileInfo info)
{
volumeLabel = volumeModel.VolumeName;
fileSystemName = volumeModel.FileSystemName;
maximumComponentLength = Constants.Dokan.MAX_COMPONENT_LENGTH;
features = Constants.Dokan.FEATURES;
return Trace(DokanResult.Success, null, info);
}
/// <inheritdoc/>
public virtual NtStatus Mounted(string mountPoint, IDokanFileInfo info)
{
_ = mountPoint; // TODO: Check if mountPoint is different and update the RootFolder (?)
return Trace(DokanResult.Success, null, info);
}
/// <inheritdoc/>
public virtual NtStatus Unmounted(IDokanFileInfo info)
{
return Trace(DokanResult.Success, null, info);
}
/// <inheritdoc/>
public virtual NtStatus FindStreams(string fileName, out IList<FileInformation> streams, IDokanFileInfo info)
{
streams = Array.Empty<FileInformation>();
return Trace(DokanResult.NotImplemented, fileName, info);
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual unsafe NtStatus ReadFile(string fileName, IntPtr buffer, uint bufferLength, out int bytesRead, long offset,
IDokanFileInfo info)
{
var ciphertextPath = GetCiphertextPath(fileName);
var contextHandle = FileSystem.Constants.INVALID_HANDLE;
var openedNewHandle = false;
// Check if the path is correct
if (ciphertextPath is null)
{
bytesRead = 0;
return Trace(DokanResult.PathNotFound, fileName, info);
}
// Memory-mapped
if (handlesManager.GetHandle<FileHandle>(GetContextValue(info)) is not { } fileHandle)
{
// Invalid handle...
contextHandle = handlesManager.OpenFileHandle(ciphertextPath, FileMode.Open, System.IO.FileAccess.Read, FileShare.Read, FileOptions.None);
fileHandle = handlesManager.GetHandle<FileHandle>(contextHandle);
openedNewHandle = true;
}
// Re-check handle
if (fileHandle is null)
{
bytesRead = 0;
return Trace(DokanResult.AccessDenied, fileName, info);
}
try
{
// Check EOF
if (offset >= fileHandle.Stream.Length)
{
bytesRead = 0;
return NtStatus.EndOfFile;
}
// Align position
fileHandle.Stream.Position = offset;
// Read file
var bufferSpan = new Span<byte>(buffer.ToPointer(), (int)bufferLength);
bytesRead = fileHandle.Stream.Read(bufferSpan);
return Trace(DokanResult.Success, fileName, info);
}
catch (PathTooLongException)
{
bytesRead = 0;
return Trace(DokanResult.InvalidName, fileName, info);
}
catch (CryptographicException)
{
bytesRead = 0;
return Trace(NtStatus.CrcError, fileName, info);
}
catch (UnavailableStreamException)
{
bytesRead = 0;
return Trace(NtStatus.HandleNoLongerValid, fileName, info);
}
finally
{
if (openedNewHandle)
handlesManager.CloseHandle(contextHandle);
}
}
/// <inheritdoc/>
[MethodImpl(MethodImplOptions.Synchronized)]
public virtual unsafe NtStatus WriteFile(string fileName, IntPtr buffer, uint bufferLength, out int bytesWritten, long offset, IDokanFileInfo info)
{
if (specifics.Options.IsReadOnly)
{
bytesWritten = 0;
return Trace(DokanResult.AccessDenied, fileName, info);
}
var ciphertextPath = GetCiphertextPath(fileName);
var appendToFile = offset == -1;
var contextHandle = FileSystem.Constants.INVALID_HANDLE;
var openedNewHandle = false;
// Check if the path is correct
if (ciphertextPath is null)
{
bytesWritten = 0;
return Trace(DokanResult.PathNotFound, fileName, info);
}
// Memory-mapped
if (handlesManager.GetHandle<FileHandle>(GetContextValue(info)) is not { } fileHandle)
{
// Invalid handle...
contextHandle = handlesManager.OpenFileHandle(ciphertextPath, appendToFile ? FileMode.Append : FileMode.Open, System.IO.FileAccess.ReadWrite, FileShare.Read, FileOptions.None);
fileHandle = handlesManager.GetHandle<FileHandle>(contextHandle);
openedNewHandle = true;
}
// Re-check handle
if (fileHandle is null)
{
bytesWritten = 0;
return Trace(DokanResult.AccessDenied, fileName, info);
}
try
{
// Align for Paging I/O
var alignedBytesToCopy = AlignSizeForPagingIo((int)bufferLength, offset, fileHandle.Stream.Length, info);
// Align position for offset
var alignedPosition = appendToFile ? fileHandle.Stream.Length : offset;
// Align position
fileHandle.Stream.Position = alignedPosition;
// Write file
var bufferSpan = new ReadOnlySpan<byte>(buffer.ToPointer(), alignedBytesToCopy);
fileHandle.Stream.Write(bufferSpan);
bytesWritten = alignedBytesToCopy;
return Trace(DokanResult.Success, fileName, info);
}
catch (PathTooLongException)
{
bytesWritten = 0;
return Trace(DokanResult.InvalidName, fileName, info);
}
catch (CryptographicException)
{
bytesWritten = 0;
return Trace(NtStatus.CrcError, fileName, info);
}
catch (UnavailableStreamException)
{
bytesWritten = 0;
return Trace(NtStatus.HandleNoLongerValid, fileName, info);
}
catch (UnauthorizedAccessException)
{
bytesWritten = 0;
return Trace(DokanResult.AccessDenied, fileName, info);
}
catch (IOException ioEx)
{
if (DokanyErrorHelpers.NtStatusFromException(ioEx, out var ntStatus))
{
bytesWritten = 0;
return Trace((NtStatus)ntStatus, fileName, info);
}
throw;
}
finally
{
if (openedNewHandle)
handlesManager.CloseHandle(contextHandle);
}
}
/// <inheritdoc/>
public abstract NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, IDokanFileInfo info);
/// <inheritdoc/>
public abstract void Cleanup(string fileName, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus GetDiskFreeSpace(out long freeBytesAvailable, out long totalNumberOfBytes, out long totalNumberOfFreeBytes, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus GetFileInformation(string fileName, out FileInformation fileInfo, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus FindFilesWithPattern(string fileName, string searchPattern, out IList<FileInformation> files, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus SetFileAttributes(string fileName, FileAttributes attributes, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus SetFileTime(string fileName, DateTime? creationTime, DateTime? lastAccessTime, DateTime? lastWriteTime, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus DeleteFile(string fileName, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus DeleteDirectory(string fileName, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus MoveFile(string oldName, string newName, bool replace, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus LockFile(string fileName, long offset, long length, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus UnlockFile(string fileName, long offset, long length, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus GetFileSecurity(string fileName, out FileSystemSecurity? security, AccessControlSections sections, IDokanFileInfo info);
/// <inheritdoc/>
public abstract NtStatus SetFileSecurity(string fileName, FileSystemSecurity security, AccessControlSections sections, IDokanFileInfo info);
// TODO: Add checks for nullable in places where this function is called
protected abstract string? GetCiphertextPath(string plaintextName);
protected void CloseHandle(IDokanFileInfo info)
{
handlesManager.CloseHandle(GetContextValue(info));
}
/// <inheritdoc/>
public virtual void Dispose()
{
specifics.Dispose();
handlesManager.Dispose();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static bool IsContextInvalid(IDokanFileInfo info)
{
return info.Context is not ulong ctxUlong || ctxUlong == FileSystem.Constants.INVALID_HANDLE;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static void InvalidateContext(IDokanFileInfo info)
{
info.Context = FileSystem.Constants.INVALID_HANDLE;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected static ulong GetContextValue(IDokanFileInfo info)
{
return info.Context is ulong ctxUlong ? ctxUlong : FileSystem.Constants.INVALID_HANDLE;
}
protected static int AlignSizeForPagingIo(int bufferLength, long offset, long streamLength, IDokanFileInfo info)
{
if (!info.PagingIo)
return bufferLength;
var longDistanceToEnd = streamLength - offset;
if (longDistanceToEnd > int.MaxValue)
return bufferLength;
if (longDistanceToEnd < bufferLength)
return (int)longDistanceToEnd;
return bufferLength;
}
protected static NtStatus Trace(NtStatus result, string fileName, IDokanFileInfo info,
FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, [CallerMemberName] string methodName = "")
{
#if !DEBUG
return result;
#else
if (Debugger.IsAttached)
return result;
if (!Core.FileSystem.Constants.OPT_IN_FOR_OPTIONAL_DEBUG_TRACING)
return result;
if (DisallowedTraceMethods.Contains(methodName))
return result;
var message = FormatProviders.DokanFormat($"{methodName}('{fileName}', {info}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}");
Debug.WriteLine(message);
return result;
#endif
}
protected static NtStatus Trace(NtStatus result, string? fileName, IDokanFileInfo info, [CallerMemberName] string methodName = "", params object[]? args)
{
#if !DEBUG
return result;
#endif
if (!Core.FileSystem.Constants.OPT_IN_FOR_OPTIONAL_DEBUG_TRACING)
return result;
if (!Debugger.IsAttached)
return result;
if (DisallowedTraceMethods.Contains(methodName))
return result;
var extraParameters = args is not null && args.Length > 0
? ", " + string.Join(", ", args.Select(x => string.Format(FormatProviders.DefaultFormatProvider, "{0}", x)))
: string.Empty;
var message = FormatProviders.DokanFormat($"{methodName}('{fileName}', {info}{extraParameters}) -> {result}");
Debug.WriteLine(message);
return result;
}
private static string[] DisallowedTraceMethods { get; } =
{
"GetVolumeInformation"
};
}
}