-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDokanFS.cs
680 lines (589 loc) · 27.1 KB
/
DokanFS.cs
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.AccessControl;
using System.Threading;
using DokanNet;
using DokanNet.Logging;
using static DokanNet.FormatProviders;
using FileAccess = DokanNet.FileAccess;
namespace NC.DokanFS
{
public class DokanFrontend : IDokanOperations
{
private const FileAccess DataAccess = FileAccess.ReadData | FileAccess.WriteData | FileAccess.AppendData |
FileAccess.Execute |
FileAccess.GenericExecute | FileAccess.GenericWrite |
FileAccess.GenericRead;
private const FileAccess DataWriteAccess = FileAccess.WriteData | FileAccess.AppendData |
FileAccess.Delete |
FileAccess.GenericWrite;
private ConsoleLogger _Logger;
private IDokanDisk _Backend;
/// <summary>
/// Create new Instance
/// </summary>
/// <param name="dd"></param>
/// <param name="loggingName"></param>
public DokanFrontend(IDokanDisk dd, string loggingName)
{
_Backend = dd;
_Logger = new ConsoleLogger(loggingName);
}
private string _LastMountPoint;
/// <summary>
/// Mount this file system
/// </summary>
/// <param name="mountPoint">Mount point, can be drive letter or folder</param>
/// <param name="readOnly">whether the drive will have WriteProtection flag set</param>
/// <param name="fixedDisk">whether the drive will have FixedDrive flag set</param>
/// <param name="useMountManager">whether to use MountManager option</param>
/// <param name="threads">number of threads, default is 64</param>
public void Mount( string mountPoint, bool readOnly = false, bool fixedDisk = false, bool useMountManager = false, int threads = 64 )
{
DokanOptions opt = fixedDisk ? DokanOptions.FixedDrive : DokanOptions.RemovableDrive;
if (readOnly)
{
opt &= DokanOptions.WriteProtection;
}
if (useMountManager)
{
opt &= DokanOptions.MountManager;
}
_LastMountPoint = mountPoint;
Thread t = new Thread((o) =>
{
this.Mount(mountPoint, opt, threads);
});
t.Start();
}
/// <summary>
/// Remove the last used mount point of this instance
/// </summary>
public void Unmount()
{
Dokan.RemoveMountPoint(_LastMountPoint);
}
/// <summary>
/// Convert OS path into Backend Path
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
protected string GetPath(string fileName)
{
return _Backend.GetPath(fileName);
}
protected NtStatus Trace(string method, string fileName, IDokanFileInfo info, NtStatus result,
params object[] parameters)
{
#if TRACE
var extraParameters = parameters != null && parameters.Length > 0
? ", " + string.Join(", ", parameters.Select(x => string.Format(DefaultFormatProvider, "{0}", x)))
: string.Empty;
if (result != NtStatus.Success)
{
_Logger.Debug(DokanFormat($"{method}('{fileName}', {info}{extraParameters}) -> {result}"));
}
#endif
return result;
}
private NtStatus Trace(string method, string fileName, IDokanFileInfo info,
FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
NtStatus result)
{
#if TRACE
if (result != NtStatus.Success)
{
_Logger.Debug(
DokanFormat(
$"{method}('{fileName}', {info}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}"));
}
#endif
return result;
}
#region Implementation of IDokanOperations
public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode,
FileOptions options, FileAttributes attributes, IDokanFileInfo info)
{
var result = DokanResult.Success;
var filePath = GetPath(fileName);
if (info.IsDirectory)
{
try
{
switch (mode)
{
case FileMode.Open:
if (!_Backend.DirectoryExists(filePath))
{
if (!_Backend.IsDirectory(filePath))
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
attributes, DokanResult.NotADirectory);
}
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
attributes, DokanResult.PathNotFound);
}
break;
case FileMode.CreateNew:
if (_Backend.DirectoryExists(filePath))
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
attributes, DokanResult.FileExists);
_Backend.CreateDirectory(GetPath(fileName));
break;
}
}
catch (UnauthorizedAccessException ex)
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.AccessDenied);
}
}
else
{
var pathExists = true;
var pathIsDirectory = false;
var readWriteAttributes = (access & DataAccess) == 0;
var readAccess = (access & DataWriteAccess) == 0;
pathExists = (_Backend.DirectoryExists(filePath) || _Backend.FileExists(filePath));
pathIsDirectory = pathExists ? _Backend.IsDirectory(filePath) : false;
switch (mode)
{
case FileMode.Open:
if (pathExists)
{
// check if driver only wants to read attributes, security info, or open directory
if (readWriteAttributes || pathIsDirectory)
{
if (pathIsDirectory && (access & FileAccess.Delete) == FileAccess.Delete
&& (access & FileAccess.Synchronize) != FileAccess.Synchronize)
{
//It is a DeleteFile request on a directory
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
attributes, DokanResult.AccessDenied);
}
info.IsDirectory = pathIsDirectory;
info.Context = new object();
// must set it to something if you return DokanError.Success
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options,
attributes, DokanResult.Success);
}
}
else
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.FileNotFound);
}
break;
case FileMode.CreateNew:
if (pathExists)
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.FileExists);
}
break;
case FileMode.Truncate:
if (!pathExists)
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.FileNotFound);
break;
}
try
{
bool fileCreated = mode == FileMode.CreateNew || mode == FileMode.Create || (!pathExists && mode == FileMode.OpenOrCreate);
if (fileCreated)
{
FileAttributes new_attributes = attributes;
new_attributes |= FileAttributes.Archive; // Files are always created as Archive
// FILE_ATTRIBUTE_NORMAL is override if any other attribute is set.
new_attributes &= ~FileAttributes.Normal;
_Backend.Touch(filePath, new_attributes);
}
info.Context = _Backend.CreateFileContext(filePath, mode,
readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite, share, options);
if (pathExists && (mode == FileMode.OpenOrCreate
|| mode == FileMode.Create))
{
result = DokanResult.AlreadyExists;
}
}
catch (UnauthorizedAccessException) // don't have access rights
{
if (info.Context is IDisposable mx)
{
// returning AccessDenied cleanup and close won't be called,
// so we have to take care of the stream now
mx.Dispose();
info.Context = null;
}
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.AccessDenied);
}
catch (DirectoryNotFoundException)
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.PathNotFound);
}
catch (Exception)
{
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
DokanResult.InternalError);
}
}
return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes,
result);
}
public void Cleanup(string fileName, IDokanFileInfo info)
{
#if TRACE
if (info.Context != null)
Console.WriteLine(DokanFormat($"{nameof(Cleanup)}('{fileName}', {info} - entering"));
#endif
(info.Context as IDokanFileContext)?.Dispose();
info.Context = null;
if (info.DeleteOnClose)
{
try
{
if (info.IsDirectory)
{
_Backend.DeleteDirectory(GetPath(fileName));
}
else
{
_Backend.DeleteFile(GetPath(fileName));
}
}
catch (UnauthorizedAccessException)
{
Trace(nameof(Cleanup), fileName, info, DokanResult.AccessDenied);
}
}
Trace(nameof(Cleanup), fileName, info, DokanResult.Success);
}
public void CloseFile(string fileName, IDokanFileInfo info)
{
#if TRACE
if (info.Context != null)
Console.WriteLine(DokanFormat($"{nameof(CloseFile)}('{fileName}', {info} - entering"));
#endif
(info.Context as IDokanFileContext)?.Dispose();
info.Context = null;
Trace(nameof(CloseFile), fileName, info, DokanResult.Success);
// could recreate cleanup code here but this is not called sometimes
}
public NtStatus ReadFile(string fileName, byte[] buffer, out int bytesRead, long offset, IDokanFileInfo info)
{
try
{
if (info.Context == null) // memory mapped read
{
using (var mx = _Backend.CreateFileContext(GetPath(fileName), FileMode.Open, System.IO.FileAccess.Read))
{
bytesRead = mx.Read(buffer, offset);
}
}
else // normal read
{
var mx = info.Context as IDokanFileContext;
lock (mx) //Protect from overlapped read
{
bytesRead = mx.Read(buffer, offset);
}
}
}
catch (Exception)
{
bytesRead = 0;
return Trace(nameof(ReadFile), fileName, info, DokanResult.InvalidParameter, "0",
offset.ToString(CultureInfo.InvariantCulture));
}
return Trace(nameof(ReadFile), fileName, info, DokanResult.Success, "out " + bytesRead.ToString(),
offset.ToString(CultureInfo.InvariantCulture));
}
public NtStatus WriteFile(string fileName, byte[] buffer, out int bytesWritten, long offset, IDokanFileInfo info)
{
var append = offset == -1;
if (info.Context == null)
{
using (var mx = _Backend.CreateFileContext(GetPath(fileName), append ? FileMode.Append : FileMode.Open, System.IO.FileAccess.Write))
{
if (!append) // Offset of -1 is an APPEND: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile
{
mx.Write(buffer, offset);
}
else
{
mx.Append(buffer);
}
bytesWritten = buffer.Length;
}
}
else
{
var mx = info.Context as IDokanFileContext;
lock (mx) //Protect from overlapped write
{
if (append)
{
mx.Append(buffer);
}
else
{
mx.Write(buffer, offset);
}
}
bytesWritten = buffer.Length;
}
return Trace(nameof(WriteFile), fileName, info, DokanResult.Success, "out " + bytesWritten.ToString(),
offset.ToString(CultureInfo.InvariantCulture));
}
public NtStatus FlushFileBuffers(string fileName, IDokanFileInfo info)
{
try
{
((IDokanFileContext)(info.Context)).Flush();
return Trace(nameof(FlushFileBuffers), fileName, info, DokanResult.Success);
}
catch (IOException)
{
return Trace(nameof(FlushFileBuffers), fileName, info, DokanResult.DiskFull);
}
}
public NtStatus GetFileInformation(string fileName, out FileInformation fileInfo, IDokanFileInfo info)
{
// may be called with info.Context == null, but usually it isn't
var filePath = GetPath(fileName);
var success =_Backend.GetFileInfo(filePath, out fileInfo);
if (success == false)
{
return Trace(nameof(GetFileInformation), fileName, info, info.IsDirectory ? DokanResult.PathNotFound : DokanResult.FileNotFound);
}
return Trace(nameof(GetFileInformation), fileName, info, DokanResult.Success);
}
public NtStatus FindFiles(string fileName, out IList<FileInformation> files, IDokanFileInfo info)
{
// This function is not called because FindFilesWithPattern is implemented
// Return DokanResult.NotImplemented in FindFilesWithPattern to make FindFiles called
files = _Backend.FindFiles(fileName, "*");
return Trace(nameof(FindFiles), fileName, info, DokanResult.Success);
}
public NtStatus SetFileAttributes(string fileName, FileAttributes attributes, IDokanFileInfo info)
{
if (attributes == 0)
{
return DokanResult.Success;
}
try
{
_Backend.SetFileAttribute(fileName, attributes);
}
catch (UnauthorizedAccessException)
{
return Trace(nameof(SetFileAttributes), fileName, info, DokanResult.AccessDenied, attributes.ToString());
}
catch (FileNotFoundException)
{
return Trace(nameof(SetFileAttributes), fileName, info, DokanResult.FileNotFound, attributes.ToString());
}
return Trace(nameof(SetFileAttributes), fileName, info, DokanResult.Success, attributes.ToString());
}
public NtStatus SetFileTime(string fileName, DateTime? creationTime, DateTime? lastAccessTime,
DateTime? lastWriteTime, IDokanFileInfo info)
{
try
{
var filePath = GetPath(fileName);
_Backend.SetFileTime(filePath, creationTime, lastAccessTime, lastWriteTime);
return Trace(nameof(SetFileTime), fileName, info, DokanResult.Success, creationTime, lastAccessTime,
lastWriteTime);
}
catch (UnauthorizedAccessException)
{
return Trace(nameof(SetFileTime), fileName, info, DokanResult.AccessDenied, creationTime, lastAccessTime,
lastWriteTime);
}
catch (FileNotFoundException)
{
return Trace(nameof(SetFileTime), fileName, info, DokanResult.FileNotFound, creationTime, lastAccessTime,
lastWriteTime);
}
}
public NtStatus DeleteFile(string fileName, IDokanFileInfo info)
{
var filePath = GetPath(fileName);
if (_Backend.DirectoryExists(filePath))
return Trace(nameof(DeleteFile), fileName, info, DokanResult.AccessDenied);
if (!_Backend.FileExists(filePath))
return Trace(nameof(DeleteFile), fileName, info, DokanResult.FileNotFound);
if (_Backend.IsDirectory(filePath))
return Trace(nameof(DeleteFile), fileName, info, DokanResult.AccessDenied);
return Trace(nameof(DeleteFile), fileName, info, DokanResult.Success);
// we just check here if we could delete the file - the true deletion is in Cleanup
}
public NtStatus DeleteDirectory(string fileName, IDokanFileInfo info)
{
return Trace(nameof(DeleteDirectory), fileName, info,
_Backend.IsDirectoryEmpty(fileName)
? DokanResult.DirectoryNotEmpty
: DokanResult.Success);
// if dir is not empty it can't be deleted
}
public NtStatus MoveFile(string oldName, string newName, bool replace, IDokanFileInfo info)
{
var oldpath = GetPath(oldName);
var newpath = GetPath(newName);
(info.Context as IDokanFileContext)?.Dispose();
info.Context = null;
var exist = info.IsDirectory ? _Backend.DirectoryExists(newpath) : _Backend.FileExists(newpath);
try
{
if (!exist)
{
info.Context = null;
if (info.IsDirectory)
{
_Backend.MoveDirectory(oldpath, newpath);
}
else
{
_Backend.MoveFile(oldpath, newpath);
}
return Trace(nameof(MoveFile), oldName, info, DokanResult.Success, newName,
replace.ToString(CultureInfo.InvariantCulture));
}
else if (replace)
{
info.Context = null;
if (info.IsDirectory) //Cannot replace directory destination - See MOVEFILE_REPLACE_EXISTING
return Trace(nameof(MoveFile), oldName, info, DokanResult.AccessDenied, newName,
replace.ToString(CultureInfo.InvariantCulture));
_Backend.DeleteFile(newpath);
_Backend.MoveFile(oldpath, newpath);
return Trace(nameof(MoveFile), oldName, info, DokanResult.Success, newName,
replace.ToString(CultureInfo.InvariantCulture));
}
}
catch (UnauthorizedAccessException)
{
return Trace(nameof(MoveFile), oldName, info, DokanResult.AccessDenied, newName,
replace.ToString(CultureInfo.InvariantCulture));
}
return Trace(nameof(MoveFile), oldName, info, DokanResult.FileExists, newName,
replace.ToString(CultureInfo.InvariantCulture));
}
public NtStatus SetEndOfFile(string fileName, long length, IDokanFileInfo info)
{
try
{
((IDokanFileContext)(info.Context)).SetLength(length);
return Trace(nameof(SetEndOfFile), fileName, info, DokanResult.Success,
length.ToString(CultureInfo.InvariantCulture));
}
catch (IOException)
{
return Trace(nameof(SetEndOfFile), fileName, info, DokanResult.DiskFull,
length.ToString(CultureInfo.InvariantCulture));
}
}
public NtStatus SetAllocationSize(string fileName, long length, IDokanFileInfo info)
{
try
{
((IDokanFileContext)(info.Context)).SetLength(length);
return Trace(nameof(SetAllocationSize), fileName, info, DokanResult.Success,
length.ToString(CultureInfo.InvariantCulture));
}
catch (IOException)
{
return Trace(nameof(SetAllocationSize), fileName, info, DokanResult.DiskFull,
length.ToString(CultureInfo.InvariantCulture));
}
}
public NtStatus LockFile(string fileName, long offset, long length, IDokanFileInfo info)
{
try
{
((IDokanFileContext)(info.Context)).Lock(offset, length);
return Trace(nameof(LockFile), fileName, info, DokanResult.Success,
offset.ToString(CultureInfo.InvariantCulture), length.ToString(CultureInfo.InvariantCulture));
}
catch (IOException)
{
return Trace(nameof(LockFile), fileName, info, DokanResult.AccessDenied,
offset.ToString(CultureInfo.InvariantCulture), length.ToString(CultureInfo.InvariantCulture));
}
}
public NtStatus UnlockFile(string fileName, long offset, long length, IDokanFileInfo info)
{
try
{
((IDokanFileContext)(info.Context)).Unlock(offset, length);
return Trace(nameof(UnlockFile), fileName, info, DokanResult.Success,
offset.ToString(CultureInfo.InvariantCulture), length.ToString(CultureInfo.InvariantCulture));
}
catch (IOException)
{
return Trace(nameof(UnlockFile), fileName, info, DokanResult.AccessDenied,
offset.ToString(CultureInfo.InvariantCulture), length.ToString(CultureInfo.InvariantCulture));
}
}
public NtStatus GetDiskFreeSpace(out long freeBytesAvailable, out long totalNumberOfBytes, out long totalNumberOfFreeBytes, IDokanFileInfo info)
{
_Backend.GetDiskFreeSpace(out freeBytesAvailable, out totalNumberOfBytes, out totalNumberOfFreeBytes);
return Trace(nameof(GetDiskFreeSpace), null, info, DokanResult.Success, "out " + freeBytesAvailable.ToString(),
"out " + totalNumberOfBytes.ToString(), "out " + totalNumberOfFreeBytes.ToString());
}
public NtStatus GetVolumeInformation(out string volumeLabel, out FileSystemFeatures features,
out string fileSystemName, out uint maximumComponentLength, IDokanFileInfo info)
{
volumeLabel = _Backend.VolumeLabel;
fileSystemName = _Backend.FileSystemName;
maximumComponentLength = _Backend.MaximumComponentLength;
features = _Backend.FileSystemFeatures;
return Trace(nameof(GetVolumeInformation), null, info, DokanResult.Success, "out " + volumeLabel,
"out " + features.ToString(), "out " + fileSystemName);
}
public NtStatus GetFileSecurity(string fileName, out FileSystemSecurity security, AccessControlSections sections,
IDokanFileInfo info)
{
security = null;
return DokanResult.NotImplemented;
}
public NtStatus SetFileSecurity(string fileName, FileSystemSecurity security, AccessControlSections sections,
IDokanFileInfo info)
{
return DokanResult.NotImplemented;
}
public NtStatus Mounted(IDokanFileInfo info)
{
return Trace(nameof(Mounted), null, info, DokanResult.Success);
}
public NtStatus Unmounted(IDokanFileInfo info)
{
return Trace(nameof(Unmounted), null, info, DokanResult.Success);
}
public NtStatus FindStreams(string fileName, IntPtr enumContext, out string streamName, out long streamSize,
IDokanFileInfo info)
{
streamName = string.Empty;
streamSize = 0;
return Trace(nameof(FindStreams), fileName, info, DokanResult.NotImplemented, enumContext.ToString(),
"out " + streamName, "out " + streamSize.ToString());
}
public NtStatus FindStreams(string fileName, out IList<FileInformation> streams, IDokanFileInfo info)
{
streams = new FileInformation[0];
return Trace(nameof(FindStreams), fileName, info, DokanResult.NotImplemented);
}
public NtStatus FindFilesWithPattern(string fileName, string searchPattern, out IList<FileInformation> files,
IDokanFileInfo info)
{
files = _Backend.FindFiles(fileName, searchPattern);
return Trace(nameof(FindFilesWithPattern), fileName, info, DokanResult.Success);
}
#endregion Implementation of IDokanOperations
}
}