-
Notifications
You must be signed in to change notification settings - Fork 671
/
dokan.c
1521 lines (1353 loc) · 54.6 KB
/
dokan.c
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
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Dokan : user-mode file system library for Windows
Copyright (C) 2020 - 2023 Google, Inc.
Copyright (C) 2015 - 2019 Adrien J. <liryna.stark@gmail.com> and Maxime C. <maxime@islog.com>
Copyright (C) 2007 - 2011 Hiroki Asakawa <info@dokan-dev.net>
http://dokan-dev.github.io
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser 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 General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dokani.h"
#include "fileinfo.h"
#include "list.h"
#include "dokan_pool.h"
#include <conio.h>
#include <process.h>
#include <stdlib.h>
#include <tchar.h>
#include <strsafe.h>
#include <assert.h>
#define DokanMapKernelBit(dest, src, userBit, kernelBit) \
if (((src) & (kernelBit)) == (kernelBit)) \
(dest) |= (userBit)
// DokanOptions->DebugMode is ON?
BOOL g_DebugMode = TRUE;
// DokanOptions->UseStdErr is ON?
BOOL g_UseStdErr = FALSE;
// Dokan DLL critical section
CRITICAL_SECTION g_InstanceCriticalSection;
// Global linked list of mounted Dokan instances
LIST_ENTRY g_InstanceList;
volatile LONG g_DokanInitialized = 0;
VOID DOKANAPI DokanUseStdErr(BOOL Status) { g_UseStdErr = Status; }
VOID DOKANAPI DokanDebugMode(BOOL Status) { g_DebugMode = Status; }
VOID DispatchDriverLogs(PDOKAN_IO_EVENT IoEvent) {
UNREFERENCED_PARAMETER(IoEvent);
PDOKAN_LOG_MESSAGE log_message =
(PDOKAN_LOG_MESSAGE)((PCHAR)IoEvent->EventContext +
sizeof(EVENT_CONTEXT));
if (log_message->MessageLength) {
ULONG paquet_size = FIELD_OFFSET(DOKAN_LOG_MESSAGE, Message[0]) +
log_message->MessageLength;
if (((PCHAR)log_message + paquet_size) <=
((PCHAR)IoEvent->EventContext + IoEvent->EventContext->Length)) {
DbgPrint("DriverLog: %.*s\n", log_message->MessageLength,
log_message->Message);
} else {
DbgPrint("Invalid driver log message received.\n");
}
}
}
PDOKAN_INSTANCE
NewDokanInstance() {
PDOKAN_INSTANCE dokanInstance =
(PDOKAN_INSTANCE)malloc(sizeof(DOKAN_INSTANCE));
if (dokanInstance == NULL)
return NULL;
ZeroMemory(dokanInstance, sizeof(DOKAN_INSTANCE));
dokanInstance->GlobalDevice = INVALID_HANDLE_VALUE;
dokanInstance->Device = INVALID_HANDLE_VALUE;
dokanInstance->NotifyHandle = INVALID_HANDLE_VALUE;
dokanInstance->KeepaliveHandle = INVALID_HANDLE_VALUE;
(void)InitializeCriticalSectionAndSpinCount(&dokanInstance->CriticalSection,
0x80000400);
InitializeListHead(&dokanInstance->ListEntry);
dokanInstance->DeviceClosedWaitHandle = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!dokanInstance->DeviceClosedWaitHandle) {
DokanDbgPrint("Dokan Error: Cannot create Dokan instance because the "
"device closed wait handle could not be created.\n");
DeleteCriticalSection(&dokanInstance->CriticalSection);
free(dokanInstance);
return NULL;
}
EnterCriticalSection(&g_InstanceCriticalSection);
{
PTP_POOL threadPool = GetThreadPool();
if (!threadPool) {
DokanDbgPrint("Dokan Error: Cannot create Dokan instance because the "
"thread pool hasn't been created.\n");
LeaveCriticalSection(&g_InstanceCriticalSection);
DeleteCriticalSection(&dokanInstance->CriticalSection);
CloseHandle(dokanInstance->DeviceClosedWaitHandle);
free(dokanInstance);
return NULL;
}
dokanInstance->ThreadInfo.ThreadPool = threadPool;
dokanInstance->ThreadInfo.CleanupGroup = CreateThreadpoolCleanupGroup();
if (!dokanInstance->ThreadInfo.CleanupGroup) {
DokanDbgPrint(
"Dokan Error: Failed to create thread pool cleanup group.\n");
LeaveCriticalSection(&g_InstanceCriticalSection);
DeleteCriticalSection(&dokanInstance->CriticalSection);
CloseHandle(dokanInstance->DeviceClosedWaitHandle);
free(dokanInstance);
return NULL;
}
InitializeThreadpoolEnvironment(
&dokanInstance->ThreadInfo.CallbackEnvironment);
SetThreadpoolCallbackPool(&dokanInstance->ThreadInfo.CallbackEnvironment,
threadPool);
SetThreadpoolCallbackCleanupGroup(
&dokanInstance->ThreadInfo.CallbackEnvironment,
dokanInstance->ThreadInfo.CleanupGroup, NULL);
InsertTailList(&g_InstanceList, &dokanInstance->ListEntry);
}
LeaveCriticalSection(&g_InstanceCriticalSection);
return dokanInstance;
}
VOID DeleteDokanInstance(PDOKAN_INSTANCE DokanInstance) {
SetEvent(DokanInstance->DeviceClosedWaitHandle);
if (DokanInstance->ThreadInfo.CleanupGroup) {
CloseThreadpoolCleanupGroupMembers(DokanInstance->ThreadInfo.CleanupGroup,
FALSE, DokanInstance);
CloseThreadpoolCleanupGroup(DokanInstance->ThreadInfo.CleanupGroup);
DokanInstance->ThreadInfo.CleanupGroup = NULL;
DestroyThreadpoolEnvironment(
&DokanInstance->ThreadInfo.CallbackEnvironment);
}
if (DokanInstance->NotifyHandle &&
DokanInstance->NotifyHandle != INVALID_HANDLE_VALUE) {
CloseHandle(DokanInstance->NotifyHandle);
}
if (DokanInstance->KeepaliveHandle &&
DokanInstance->KeepaliveHandle != INVALID_HANDLE_VALUE) {
CloseHandle(DokanInstance->KeepaliveHandle);
}
if (DokanInstance->Device && DokanInstance->Device != INVALID_HANDLE_VALUE) {
CloseHandle(DokanInstance->Device);
}
if (DokanInstance->GlobalDevice &&
DokanInstance->GlobalDevice != INVALID_HANDLE_VALUE) {
CloseHandle(DokanInstance->GlobalDevice);
}
DeleteCriticalSection(&DokanInstance->CriticalSection);
EnterCriticalSection(&g_InstanceCriticalSection);
{ RemoveEntryList(&DokanInstance->ListEntry); }
LeaveCriticalSection(&g_InstanceCriticalSection);
CloseHandle(DokanInstance->DeviceClosedWaitHandle);
free(DokanInstance);
}
BOOL IsMountPointDriveLetter(LPCWSTR mountPoint) {
size_t mountPointLength;
if (!mountPoint || *mountPoint == 0) {
return FALSE;
}
mountPointLength = wcslen(mountPoint);
if (mountPointLength == 1 ||
(mountPointLength == 2 && mountPoint[1] == L':') ||
(mountPointLength == 3 && mountPoint[1] == L':' &&
mountPoint[2] == L'\\')) {
return TRUE;
}
return FALSE;
}
BOOL IsValidDriveLetter(WCHAR DriveLetter) {
return (L'a' <= DriveLetter && DriveLetter <= L'z') ||
(L'A' <= DriveLetter && DriveLetter <= L'Z');
}
BOOL CheckDriveLetterAvailability(WCHAR DriveLetter) {
DWORD result = 0;
WCHAR buffer[MAX_PATH];
WCHAR dosDevice[] = L"\\\\.\\C:";
WCHAR driveName[] = L"C:";
WCHAR driveLetter = towupper(DriveLetter);
HANDLE device = NULL;
dosDevice[4] = driveLetter;
driveName[0] = driveLetter;
DokanMountPointsCleanUp();
if (!IsValidDriveLetter(driveLetter)) {
DbgPrintW(L"CheckDriveLetterAvailability failed, bad drive letter %c\n",
DriveLetter);
return FALSE;
}
device = CreateFile(dosDevice, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING, NULL);
if (device != INVALID_HANDLE_VALUE) {
DbgPrintW(L"CheckDriveLetterAvailability failed, %c: is already used\n",
DriveLetter);
CloseHandle(device);
return FALSE;
}
ZeroMemory(buffer, MAX_PATH * sizeof(WCHAR));
result = QueryDosDevice(driveName, buffer, MAX_PATH);
if (result > 0) {
DbgPrintW(L"CheckDriveLetterAvailability failed, QueryDosDevice - Drive "
L"letter \"%c\" is already used.\n",
DriveLetter);
return FALSE;
}
DWORD drives = GetLogicalDrives();
result = (drives >> (driveLetter - L'A') & 0x00000001);
if (result > 0) {
DbgPrintW(L"CheckDriveLetterAvailability failed, GetLogicalDrives - Drive "
L"letter \"%c\" is already used.\n",
DriveLetter);
return FALSE;
}
return TRUE;
}
VOID CheckAllocationUnitSectorSize(PDOKAN_OPTIONS DokanOptions) {
ULONG allocationUnitSize = DokanOptions->AllocationUnitSize;
ULONG sectorSize = DokanOptions->SectorSize;
if ((allocationUnitSize < 512 || allocationUnitSize > 65536 ||
(allocationUnitSize & (allocationUnitSize - 1)) != 0) // Is power of two
|| (sectorSize < 512 || sectorSize > 65536 ||
(sectorSize & (sectorSize - 1)))) { // Is power of two
// Reset to default if values does not fit windows FAT/NTFS value
// https://support.microsoft.com/en-us/kb/140365
DokanOptions->SectorSize = DOKAN_DEFAULT_SECTOR_SIZE;
DokanOptions->AllocationUnitSize = DOKAN_DEFAULT_ALLOCATION_UNIT_SIZE;
}
DbgPrintW(L"AllocationUnitSize: %d SectorSize: %d\n",
DokanOptions->AllocationUnitSize, DokanOptions->SectorSize);
}
VOID SetupIOEventForProcessing(PDOKAN_IO_EVENT IoEvent) {
// The event should not have a pending result from a previous request.
assert(IoEvent->EventResult == NULL);
IoEvent->DokanOpenInfo =
(PDOKAN_OPEN_INFO)(UINT_PTR)IoEvent->EventContext->Context;
IoEvent->DokanFileInfo.DokanContext = (ULONG64)IoEvent;
IoEvent->DokanFileInfo.ProcessId = IoEvent->EventContext->ProcessId;
IoEvent->DokanFileInfo.DokanOptions = IoEvent->DokanInstance->DokanOptions;
if (!IoEvent->DokanOpenInfo) {
return;
}
EnterCriticalSection(&IoEvent->DokanOpenInfo->CriticalSection);
IoEvent->DokanOpenInfo->OpenCount++;
IoEvent->DokanFileInfo.Context = IoEvent->DokanOpenInfo->UserContext;
LeaveCriticalSection(&IoEvent->DokanOpenInfo->CriticalSection);
IoEvent->DokanFileInfo.IsDirectory =
(UCHAR)IoEvent->DokanOpenInfo->IsDirectory;
if (IoEvent->EventContext->FileFlags & DOKAN_DELETE_ON_CLOSE) {
IoEvent->DokanFileInfo.DeleteOnClose = 1;
}
if (IoEvent->EventContext->FileFlags & DOKAN_PAGING_IO) {
IoEvent->DokanFileInfo.PagingIo = 1;
}
if (IoEvent->EventContext->FileFlags & DOKAN_WRITE_TO_END_OF_FILE) {
IoEvent->DokanFileInfo.WriteToEndOfFile = 1;
}
if (IoEvent->EventContext->FileFlags & DOKAN_SYNCHRONOUS_IO) {
IoEvent->DokanFileInfo.SynchronousIo = 1;
}
if (IoEvent->EventContext->FileFlags & DOKAN_NOCACHE) {
IoEvent->DokanFileInfo.Nocache = 1;
}
}
VOID DispatchEvent(PDOKAN_IO_EVENT ioEvent) {
SetupIOEventForProcessing(ioEvent);
switch (ioEvent->EventContext->MajorFunction) {
case IRP_MJ_CREATE:
DispatchCreate(ioEvent);
break;
case IRP_MJ_CLEANUP:
DispatchCleanup(ioEvent);
break;
case IRP_MJ_CLOSE:
DispatchClose(ioEvent);
break;
case IRP_MJ_DIRECTORY_CONTROL:
DispatchDirectoryInformation(ioEvent);
break;
case IRP_MJ_READ:
DispatchRead(ioEvent);
break;
case IRP_MJ_WRITE:
DispatchWrite(ioEvent);
break;
case IRP_MJ_QUERY_INFORMATION:
DispatchQueryInformation(ioEvent);
break;
case IRP_MJ_QUERY_VOLUME_INFORMATION:
DispatchQueryVolumeInformation(ioEvent);
break;
case IRP_MJ_LOCK_CONTROL:
DispatchLock(ioEvent);
break;
case IRP_MJ_SET_INFORMATION:
DispatchSetInformation(ioEvent);
break;
case IRP_MJ_FLUSH_BUFFERS:
DispatchFlush(ioEvent);
break;
case IRP_MJ_QUERY_SECURITY:
DispatchQuerySecurity(ioEvent);
break;
case IRP_MJ_SET_SECURITY:
DispatchSetSecurity(ioEvent);
break;
case DOKAN_IRP_LOG_MESSAGE:
DispatchDriverLogs(ioEvent);
break;
default:
DokanDbgPrintW(L"Dokan Warning: Unsupported IRP 0x%x, event Info = 0x%p.\n",
ioEvent->EventContext->MajorFunction, ioEvent->EventContext);
PushIoEventBuffer(ioEvent);
break;
}
}
VOID OnDeviceIoCtlFailed(PDOKAN_INSTANCE DokanInstance, DWORD Result) {
if (!DokanInstance->FileSystemStopped) {
DokanDbgPrintW(L"Dokan Fatal: Closing IO processing for dokan instance %s "
L"with error code 0x%x and unmounting volume.\n",
DokanInstance->DeviceName, Result);
}
if (InterlockedAdd(&DokanInstance->UnmountedCalled, 1) == 1) {
DokanNotifyUnmounted(DokanInstance);
}
// set the device to a closed state
SetEvent(DokanInstance->DeviceClosedWaitHandle);
}
// Don't know what went wrong
// Life will never be the same again
// End it all
VOID HandleProcessIoFatalError(PDOKAN_INSTANCE DokanInstance,
PDOKAN_IO_BATCH IoBatch, DWORD Result) {
PushIoBatchBuffer(IoBatch);
OnDeviceIoCtlFailed(DokanInstance, Result);
}
VOID FreeIoEventResult(PEVENT_INFORMATION EventResult, ULONG EventResultSize,
BOOL PoolAllocated) {
if (!EventResult) {
return;
}
if (!PoolAllocated) {
FreeEventResult(EventResult);
} else if (EventResultSize <= DOKAN_EVENT_INFO_DEFAULT_SIZE) {
PushEventResult(EventResult);
} else if (EventResultSize <= DOKAN_EVENT_INFO_16K_SIZE) {
Push16KEventResult(EventResult);
} else if (EventResultSize <= DOKAN_EVENT_INFO_32K_SIZE) {
Push32KEventResult(EventResult);
} else if (EventResultSize <= DOKAN_EVENT_INFO_64K_SIZE) {
Push64KEventResult(EventResult);
} else if (EventResultSize <= DOKAN_EVENT_INFO_128K_SIZE) {
Push128KEventResult(EventResult);
} else {
assert(FALSE);
}
}
VOID QueueIoEvent(PDOKAN_IO_EVENT IoEvent, PTP_WORK_CALLBACK Callback) {
PTP_WORK work = CreateThreadpoolWork(
Callback, IoEvent,
&IoEvent->DokanInstance->ThreadInfo.CallbackEnvironment);
if (!work) {
DWORD lastError = GetLastError();
DbgPrintW(L"Dokan Error: CreateThreadpoolWork() has returned error "
L"code %u.\n",
lastError);
OnDeviceIoCtlFailed(IoEvent->DokanInstance, lastError);
return;
}
SubmitThreadpoolWork(work);
}
DWORD
GetEventInfoSize(__in ULONG MajorFunction, __in PEVENT_INFORMATION EventInfo) {
if (MajorFunction == IRP_MJ_WRITE) {
// For writes only, the reply is a fixed size and the BufferLength inside it
// is the "bytes written" value as opposed to the reply size.
return sizeof(EVENT_INFORMATION);
}
return (DWORD)max((ULONG)sizeof(EVENT_INFORMATION),
FIELD_OFFSET(EVENT_INFORMATION, Buffer[0]) +
EventInfo->BufferLength);
}
DWORD SendAndPullEventInformation(PDOKAN_IO_EVENT IoEvent,
PDOKAN_IO_BATCH IoBatch,
BOOL ReleaseBatchBuffers) {
DWORD lastError = 0;
PCHAR inputBuffer = NULL;
DWORD eventInfoSize = 0;
ULONG eventResultSize = 0;
PEVENT_INFORMATION eventInfo = NULL;
BOOL eventInfoPollAllocated = FALSE;
if (IoEvent && IoEvent->EventResult) {
eventInfo = IoEvent->EventResult;
eventResultSize = IoEvent->EventResultSize;
eventInfoPollAllocated = IoEvent->PoolAllocated;
inputBuffer = (PCHAR)eventInfo;
eventInfoSize =
GetEventInfoSize(IoEvent->EventContext->MajorFunction, eventInfo);
eventInfo->PullEventTimeoutMs =
IoBatch->MainPullThread ? /*infinite*/ 0 : DOKAN_PULL_EVENT_TIMEOUT_MS;
if (ReleaseBatchBuffers) {
PushIoBatchBuffer(IoEvent->IoBatch);
PushIoEventBuffer(IoEvent);
}
DbgPrint(
"Dokan Information: SendAndPullEventInformation() with NTSTATUS 0x%x, "
"context 0x%lx, and result object 0x%p with size %d\n",
eventInfo->Status, eventInfo->Context, eventInfo, eventInfoSize);
} else {
// Main pull thread is allowed to pull events without having event results to send
assert(IoBatch->MainPullThread);
}
if (!DeviceIoControl(
IoBatch->DokanInstance->Device, // Handle to device
FSCTL_EVENT_PROCESS_N_PULL, // IO Control code
inputBuffer, // Input Buffer to driver.
eventInfoSize, // Length of input buffer in bytes.
&IoBatch->EventContext[0], // Output Buffer from driver.
BATCH_EVENT_CONTEXT_SIZE, // Length of output buffer in bytes.
&IoBatch->NumberOfBytesTransferred, // Bytes placed in buffer.
NULL // asynchronous call
)) {
lastError = GetLastError();
if (eventInfo) {
FreeIoEventResult(eventInfo, eventResultSize, eventInfoPollAllocated);
}
if (!IoBatch->DokanInstance->FileSystemStopped) {
DokanDbgPrintW(
L"Dokan Error: Dokan device result ioctl failed for wait with "
L"code %d.\n",
lastError);
}
return lastError;
}
if (eventInfo) {
FreeIoEventResult(eventInfo, eventResultSize, eventInfoPollAllocated);
}
return 0;
}
VOID CALLBACK DispatchBatchIoCallback(PTP_CALLBACK_INSTANCE Instance, PVOID Parameter,
PTP_WORK Work) {
UNREFERENCED_PARAMETER(Instance);
UNREFERENCED_PARAMETER(Work);
PDOKAN_IO_EVENT ioEvent = (PDOKAN_IO_EVENT)Parameter;
assert(ioEvent);
PDOKAN_INSTANCE dokanInstance = ioEvent->DokanInstance;
PDOKAN_IO_BATCH ioBatch = NULL;
BOOL mainPullThread = ioEvent->EventContext == NULL;
while (TRUE) {
// 6 - Process events coming from:
// - Last event not dispatched to the pool (see bottom of this fct).
// - New pool thread that just started with a dispatched event.
// Note: Main pull thread does not have an EventContext when started.
if (ioEvent && ioEvent->EventContext) {
DispatchEvent(ioEvent);
if (!ioEvent->EventResult) {
// Some events like Close() do not have event results.
// Release the resource and terminate here unless we are the main pulling thread.
PushIoBatchBuffer(ioEvent->IoBatch);
PushIoEventBuffer(ioEvent);
if (mainPullThread) {
ioEvent = NULL;
continue;
}
return;
}
}
ioBatch = PopIoBatchBuffer();
ioBatch->MainPullThread = mainPullThread;
ioBatch->DokanInstance = dokanInstance;
// 1 - Send event result and pull new events.
DWORD error = SendAndPullEventInformation(ioEvent, ioBatch, /*ReleaseBatchBuffers=*/TRUE);
if (error) {
HandleProcessIoFatalError(dokanInstance, ioBatch, error);
return;
}
// 2 - Terminate thread as nothing needs to be proceed unless we are the mainPullThread.
if (!ioBatch->NumberOfBytesTransferred) {
PushIoBatchBuffer(ioBatch);
if (mainPullThread) {
ioEvent = NULL;
continue;
}
return;
}
PEVENT_CONTEXT context = ioBatch->EventContext;
ULONG_PTR currentNumberOfBytesTransferred =
ioBatch->NumberOfBytesTransferred;
while (currentNumberOfBytesTransferred) {
++ioBatch->EventContextBatchCount;
currentNumberOfBytesTransferred -= context->Length;
context = (PEVENT_CONTEXT)((PCHAR)(context) + context->Length);
}
// 3 - Dispatch Events
context = ioBatch->EventContext;
LONG eventContextBatchCount = ioBatch->EventContextBatchCount;
while (eventContextBatchCount) {
ioEvent = PopIoEventBuffer();
if (!ioEvent) {
DbgPrintW(L"Dokan Error: IoEvent allocation failed.\n");
OnDeviceIoCtlFailed(ioBatch->DokanInstance, ERROR_OUTOFMEMORY);
return;
}
ioEvent->DokanInstance = ioBatch->DokanInstance;
ioEvent->EventContext = context;
ioEvent->IoBatch = ioBatch;
--eventContextBatchCount;
// It is unsafe to access the context from here after Queuing the event.
context = (PEVENT_CONTEXT)((PCHAR)(context) + context->Length);
// 4 - All batched events are dispatched to the thread pool except the last event that is executed on the current thread.
// Note: Single thread mode has batching disabled and therefore only has one event which is executed on the main thread.
if (eventContextBatchCount) {
QueueIoEvent(ioEvent, DispatchBatchIoCallback);
}
}
}
}
VOID CALLBACK DispatchDedicatedIoCallback(PTP_CALLBACK_INSTANCE Instance,
PVOID Parameter, PTP_WORK Work) {
UNREFERENCED_PARAMETER(Instance);
UNREFERENCED_PARAMETER(Work);
PDOKAN_IO_EVENT ioEvent = (PDOKAN_IO_EVENT)Parameter;
assert(ioEvent);
PDOKAN_IO_BATCH ioBatch = PopIoBatchBuffer();
ioBatch->MainPullThread = TRUE;
ioBatch->DokanInstance = ioEvent->DokanInstance;
ioEvent->EventContext = ioBatch->EventContext;
ioEvent->IoBatch = ioBatch;
while (TRUE) {
// 1 - Send possible event result and pull new events.
DWORD error =
SendAndPullEventInformation(ioEvent, ioBatch, /*ReleaseBatchBuffers=*/FALSE);
if (error) {
PushIoEventBuffer(ioEvent);
HandleProcessIoFatalError(ioBatch->DokanInstance, ioBatch, error);
return;
}
RtlZeroMemory(ioEvent, sizeof(DOKAN_IO_EVENT));
ioEvent->DokanInstance = ioBatch->DokanInstance;
ioEvent->EventContext = ioBatch->EventContext;
ioEvent->IoBatch = ioBatch;
// 2 - Restart pulling as there is nothing to process.
if (!ioBatch->NumberOfBytesTransferred) {
continue;
}
// 3 - Process event
DispatchEvent(ioEvent);
}
}
BOOL DOKANAPI DokanIsFileSystemRunning(_In_ DOKAN_HANDLE DokanInstance) {
DOKAN_INSTANCE *instance = (DOKAN_INSTANCE *)DokanInstance;
if (!instance) {
return FALSE;
}
return WaitForSingleObject(instance->DeviceClosedWaitHandle, 0) ==
WAIT_TIMEOUT;
}
DWORD DOKANAPI DokanWaitForFileSystemClosed(_In_ DOKAN_HANDLE DokanInstance,
_In_ DWORD dwMilliseconds) {
DOKAN_INSTANCE *instance = (DOKAN_INSTANCE *)DokanInstance;
if (!instance) {
return FALSE;
}
return WaitForSingleObject(instance->DeviceClosedWaitHandle, dwMilliseconds);
}
BOOL DOKANAPI DokanRegisterWaitForFileSystemClosed(
_In_ DOKAN_HANDLE DokanInstance, _Out_ PHANDLE WaitHandle,
_In_ WAITORTIMERCALLBACKFUNC Callback, _In_ PVOID Context,
ULONG dwMilliseconds) {
DOKAN_INSTANCE *instance = (DOKAN_INSTANCE *)DokanInstance;
if (!instance) {
return FALSE;
}
return RegisterWaitForSingleObject(
WaitHandle, instance->DeviceClosedWaitHandle, Callback, Context,
dwMilliseconds, WT_EXECUTEONLYONCE);
}
BOOL DOKANAPI DokanUnregisterWaitForFileSystemClosed(
_In_ HANDLE WaitHandle, BOOL WaitForCallbacks) {
return UnregisterWaitEx(
WaitHandle, WaitForCallbacks ? INVALID_HANDLE_VALUE : NULL);
}
VOID DOKANAPI DokanCloseHandle(_In_ DOKAN_HANDLE DokanInstance) {
DOKAN_INSTANCE *instance = (DOKAN_INSTANCE *)DokanInstance;
if (!instance) {
return;
}
// make sure the driver is unmounted
instance->FileSystemStopped = TRUE;
DokanRemoveMountPoint(instance->MountPoint);
DokanWaitForFileSystemClosed((DOKAN_HANDLE)instance, INFINITE);
EnterCriticalSection(&g_InstanceCriticalSection);
DeleteDokanInstance(instance);
LeaveCriticalSection(&g_InstanceCriticalSection);
}
int DOKANAPI DokanMain(PDOKAN_OPTIONS DokanOptions,
PDOKAN_OPERATIONS DokanOperations) {
DOKAN_INSTANCE *instance = NULL;
int returnCode;
returnCode = DokanCreateFileSystem(DokanOptions, DokanOperations,
(DOKAN_HANDLE *)&instance);
if (returnCode != DOKAN_SUCCESS) {
return returnCode;
}
DokanWaitForFileSystemClosed((DOKAN_HANDLE)instance, INFINITE);
DeleteDokanInstance(instance);
return returnCode;
}
int DOKANAPI DokanCreateFileSystem(_In_ PDOKAN_OPTIONS DokanOptions,
_In_ PDOKAN_OPERATIONS DokanOperations,
_Out_ DOKAN_HANDLE *DokanInstance) {
PDOKAN_INSTANCE dokanInstance;
WCHAR rawDeviceName[MAX_PATH];
if (DokanInstance) {
*DokanInstance = NULL;
}
if (InterlockedAdd(&g_DokanInitialized, 0) <= 0) {
RaiseException(DOKAN_EXCEPTION_NOT_INITIALIZED, 0, 0, NULL);
}
g_DebugMode = DokanOptions->Options & DOKAN_OPTION_DEBUG;
g_UseStdErr = DokanOptions->Options & DOKAN_OPTION_STDERR;
if (g_DebugMode) {
DbgPrintW(L"Dokan: debug mode on\n");
}
if (g_UseStdErr) {
DbgPrintW(L"Dokan: use stderr\n");
g_DebugMode = TRUE;
}
if ((DokanOptions->Options & DOKAN_OPTION_NETWORK) &&
!IsMountPointDriveLetter(DokanOptions->MountPoint)) {
DokanOptions->Options &= ~DOKAN_OPTION_NETWORK;
DbgPrintW(L"Dokan: Mount point folder is specified with network device "
L"option. Disable network device.\n");
}
if ((DokanOptions->Options & DOKAN_OPTION_NETWORK) &&
DokanOptions->UNCName == NULL) {
DbgPrintW(L"Dokan: Network filesystem is enabled without UNC name.\n");
return DOKAN_MOUNT_POINT_ERROR;
}
if (DokanOptions->Version < DOKAN_MINIMUM_COMPATIBLE_VERSION) {
DokanDbgPrintW(
L"Dokan Error: Incompatible version (%d), minimum is (%d) \n",
DokanOptions->Version, DOKAN_MINIMUM_COMPATIBLE_VERSION);
return DOKAN_VERSION_ERROR;
}
if (DokanOptions->SingleThread) {
DbgPrintW(L"Dokan Info: Single thread mode enabled.\n");
}
CheckAllocationUnitSectorSize(DokanOptions);
dokanInstance = NewDokanInstance();
if (!dokanInstance) {
return DOKAN_DRIVER_INSTALL_ERROR;
}
dokanInstance->DokanOptions = DokanOptions;
dokanInstance->DokanOperations = DokanOperations;
dokanInstance->GlobalDevice =
CreateFile(DOKAN_GLOBAL_DEVICE_NAME, // lpFileName
0, // dwDesiredAccess
FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_EXISTING, // dwCreationDistribution
0, // dwFlagsAndAttributes
NULL // hTemplateFile
);
if (dokanInstance->GlobalDevice == INVALID_HANDLE_VALUE) {
DWORD lastError = GetLastError();
DokanDbgPrintW(L"Dokan Error: CreatFile failed to open %s: %d\n",
DOKAN_GLOBAL_DEVICE_NAME, lastError);
DeleteDokanInstance(dokanInstance);
return DOKAN_DRIVER_INSTALL_ERROR;
}
DbgPrint("Global device opened\n");
if (DokanOptions->MountPoint != NULL) {
wcscpy_s(dokanInstance->MountPoint,
sizeof(dokanInstance->MountPoint) / sizeof(WCHAR),
DokanOptions->MountPoint);
// When mount manager is enabled we will try to release the busy letter if we own it or get one assigned but otherwise we just fail here.
if (!(DokanOptions->Options & DOKAN_OPTION_MOUNT_MANAGER) &&
IsMountPointDriveLetter(dokanInstance->MountPoint) &&
!CheckDriveLetterAvailability(dokanInstance->MountPoint[0])) {
DokanDbgPrint("Dokan Error: CheckDriveLetterAvailability Failed\n");
DeleteDokanInstance(dokanInstance);
return DOKAN_MOUNT_ERROR;
}
}
if (DokanOptions->UNCName != NULL) {
wcscpy_s(dokanInstance->UNCName, sizeof(dokanInstance->UNCName) / sizeof(WCHAR),
DokanOptions->UNCName);
}
int result = DokanStart(dokanInstance);
if (result != DOKAN_SUCCESS) {
DeleteDokanInstance(dokanInstance);
return result;
}
GetRawDeviceName(dokanInstance->DeviceName, rawDeviceName, MAX_PATH);
dokanInstance->Device =
CreateFile(rawDeviceName, // lpFileName
0, // dwDesiredAccess
FILE_SHARE_READ | FILE_SHARE_WRITE, // dwShareMode
NULL, // lpSecurityAttributes
OPEN_EXISTING, // dwCreationDistribution
FILE_FLAG_OVERLAPPED, // dwFlagsAndAttributes
NULL // hTemplateFile
);
if (dokanInstance->Device == INVALID_HANDLE_VALUE) {
DWORD lastError = GetLastError();
DokanDbgPrintW(L"Dokan Error: CreatFile failed to open %s: %d\n",
rawDeviceName, lastError);
DeleteDokanInstance(dokanInstance);
return DOKAN_DRIVER_INSTALL_ERROR;
}
DWORD_PTR processAffinityMask;
DWORD_PTR systemAffinityMask;
DWORD mainPullThreadCount = 0;
if (GetProcessAffinityMask(GetCurrentProcess(), &processAffinityMask,
&systemAffinityMask)) {
while (processAffinityMask) {
mainPullThreadCount += 1;
processAffinityMask >>= 1;
}
} else {
DbgPrintW(L"Dokan Error: GetProcessAffinityMask failed with Error %d\n",
GetLastError());
}
if (DokanOptions->SingleThread) {
mainPullThreadCount = 1; // Really not recommanded
DokanOptions->Options &= ~DOKAN_OPTION_ALLOW_IPC_BATCHING;
} else if (mainPullThreadCount < DOKAN_MAIN_PULL_THREAD_COUNT_MIN) {
mainPullThreadCount = DOKAN_MAIN_PULL_THREAD_COUNT_MIN;
} else if (mainPullThreadCount > DOKAN_MAIN_PULL_THREAD_COUNT_MAX) {
// Thread pool will allocate more threads when pulling batched events
DokanOptions->Options |= DOKAN_OPTION_ALLOW_IPC_BATCHING;
mainPullThreadCount = DOKAN_MAIN_PULL_THREAD_COUNT_MAX;
}
BOOLEAN allowIpcBatching =
(BOOLEAN)(DokanOptions->Options & DOKAN_OPTION_ALLOW_IPC_BATCHING);
DbgPrintW(L"Dokan: Using %d main pull threads with ipc batching: %d\n",
mainPullThreadCount, allowIpcBatching);
for (DWORD x = 0; x < mainPullThreadCount; ++x) {
PDOKAN_IO_EVENT ioEvent = PopIoEventBuffer();
if (!ioEvent) {
DokanDbgPrintW(L"Dokan Error: IoEvent allocation failed.");
DeleteDokanInstance(dokanInstance);
return DOKAN_MOUNT_ERROR;
}
ioEvent->DokanInstance = dokanInstance;
QueueIoEvent(ioEvent, allowIpcBatching
? DispatchBatchIoCallback
: DispatchDedicatedIoCallback);
}
if (!DokanMount(dokanInstance, DokanOptions)) {
SendReleaseIRP(dokanInstance->DeviceName);
DokanDbgPrint("Dokan Error: DokanMount Failed\n");
DeleteDokanInstance(dokanInstance);
return DOKAN_MOUNT_ERROR;
}
wchar_t keepalive_path[128];
StringCbPrintfW(keepalive_path, sizeof(keepalive_path), L"\\\\?%s%s",
dokanInstance->DeviceName, DOKAN_KEEPALIVE_FILE_NAME);
dokanInstance->KeepaliveHandle =
CreateFile(keepalive_path, 0, 0, NULL, OPEN_EXISTING, 0, NULL);
if (dokanInstance->KeepaliveHandle == INVALID_HANDLE_VALUE) {
// We don't consider this a fatal error because the keepalive handle is only
// needed for abnormal termination cases anyway.
DbgPrintW(L"Failed to open keepalive file: %s error %d\n", keepalive_path,
GetLastError());
} else {
DWORD keepalive_bytes_returned = 0;
if (!DeviceIoControl(dokanInstance->KeepaliveHandle, FSCTL_ACTIVATE_KEEPALIVE,
NULL, 0, NULL, 0, &keepalive_bytes_returned, NULL))
DbgPrintW(L"Failed to activate keepalive handle.\n");
}
wchar_t notify_path[128];
StringCbPrintfW(notify_path, sizeof(notify_path), L"\\\\?%s%s",
dokanInstance->DeviceName, DOKAN_NOTIFICATION_FILE_NAME);
dokanInstance->NotifyHandle = CreateFile(
notify_path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (dokanInstance->NotifyHandle == INVALID_HANDLE_VALUE) {
DbgPrintW(L"Failed to open notify handle: %s\n", notify_path);
}
// Here we should have been mounter by mountmanager thanks to
// IOCTL_MOUNTDEV_QUERY_SUGGESTED_LINK_NAME
DbgPrintW(L"Dokan Information: mounted: %s -> %s\n", dokanInstance->MountPoint,
dokanInstance->DeviceName);
if (DokanOperations->Mounted) {
DOKAN_FILE_INFO fileInfo;
RtlZeroMemory(&fileInfo, sizeof(DOKAN_FILE_INFO));
fileInfo.DokanOptions = DokanOptions;
// Ignore return value
DokanOperations->Mounted(dokanInstance->MountPoint, &fileInfo);
}
if (DokanInstance) {
*DokanInstance = dokanInstance;
}
return DOKAN_SUCCESS;
}
VOID GetRawDeviceName(LPCWSTR DeviceName, LPWSTR DestinationBuffer,
rsize_t DestinationBufferSizeInElements) {
if (DeviceName && DestinationBuffer && DestinationBufferSizeInElements > 0) {
wcscpy_s(DestinationBuffer, DestinationBufferSizeInElements, L"\\\\.");
wcscat_s(DestinationBuffer, DestinationBufferSizeInElements, DeviceName);
}
}
VOID ALIGN_ALLOCATION_SIZE(PLARGE_INTEGER size, PDOKAN_OPTIONS DokanOptions) {
long long r = size->QuadPart % DokanOptions->AllocationUnitSize;
size->QuadPart =
(size->QuadPart + (r > 0 ? DokanOptions->AllocationUnitSize - r : 0));
}
VOID EventCompletion(PDOKAN_IO_EVENT IoEvent) {
assert(IoEvent->EventResult);
ReleaseDokanOpenInfo(IoEvent);
}
VOID CheckFileName(LPWSTR FileName) {
size_t len = wcslen(FileName);
// if the beginning of file name is "\\",
// replace it with "\"
if (len >= 2 && FileName[0] == L'\\' && FileName[1] == L'\\') {
int i;
for (i = 0; FileName[i + 1] != L'\0'; ++i) {
FileName[i] = FileName[i + 1];
}
FileName[i] = L'\0';
}
// Remove "\" in front of Directory
len = wcslen(FileName);
if (len > 2 && FileName[len - 1] == L'\\')
FileName[len - 1] = '\0';
}
ULONG DispatchGetEventInformationLength(ULONG bufferSize) {
// EVENT_INFORMATION has a buffer of size 8 already
// we remote it to the struct size and add the requested buffer size
// but we need at least to have enough space to set EVENT_INFORMATION
return max((ULONG)sizeof(EVENT_INFORMATION),
FIELD_OFFSET(EVENT_INFORMATION, Buffer[0]) + bufferSize);
}
VOID CreateDispatchCommon(PDOKAN_IO_EVENT IoEvent, ULONG SizeOfEventInfo, BOOL UseExtraMemoryPool, BOOL ClearNonPoolBuffer) {
assert(IoEvent != NULL);
assert(IoEvent->EventResult == NULL && IoEvent->EventResultSize == 0);
if (SizeOfEventInfo <= DOKAN_EVENT_INFO_DEFAULT_BUFFER_SIZE) {
IoEvent->EventResult = PopEventResult();
IoEvent->EventResultSize = DOKAN_EVENT_INFO_DEFAULT_SIZE;
IoEvent->PoolAllocated = TRUE;
} else {
if (UseExtraMemoryPool) {
if (SizeOfEventInfo <= (16 * 1024)) {
IoEvent->EventResult = Pop16KEventResult();
IoEvent->EventResultSize = DOKAN_EVENT_INFO_16K_SIZE;
IoEvent->PoolAllocated = TRUE;
} else if (SizeOfEventInfo <= (32 * 1024)) {
IoEvent->EventResult = Pop32KEventResult();
IoEvent->EventResultSize = DOKAN_EVENT_INFO_32K_SIZE;
IoEvent->PoolAllocated = TRUE;
} else if (SizeOfEventInfo <= (64 * 1024)) {
IoEvent->EventResult = Pop64KEventResult();
IoEvent->EventResultSize = DOKAN_EVENT_INFO_64K_SIZE;
IoEvent->PoolAllocated = TRUE;
} else if (SizeOfEventInfo <= (128 * 1024)) {
IoEvent->EventResult = Pop128KEventResult();
IoEvent->EventResultSize = DOKAN_EVENT_INFO_128K_SIZE;
IoEvent->PoolAllocated = TRUE;
}
}
if (IoEvent->EventResult == NULL) {
IoEvent->EventResultSize =
DispatchGetEventInformationLength(SizeOfEventInfo);
IoEvent->EventResult =
(PEVENT_INFORMATION)malloc(IoEvent->EventResultSize);
if (!IoEvent->EventResult) {
return;
}
ZeroMemory(IoEvent->EventResult,
ClearNonPoolBuffer
? IoEvent->EventResultSize
: FIELD_OFFSET(EVENT_INFORMATION, Buffer[0]));
}
}
assert(IoEvent->EventResult &&
IoEvent->EventResultSize >=
DispatchGetEventInformationLength(SizeOfEventInfo));
IoEvent->EventResult->SerialNumber = IoEvent->EventContext->SerialNumber;
IoEvent->EventResult->Context = IoEvent->EventContext->Context;
}
VOID ReleaseDokanOpenInfo(PDOKAN_IO_EVENT IoEvent) {
if (!IoEvent->DokanOpenInfo) {
return;
}
EnterCriticalSection(&IoEvent->DokanOpenInfo->CriticalSection);
IoEvent->DokanOpenInfo->UserContext = IoEvent->DokanFileInfo.Context;
IoEvent->DokanOpenInfo->OpenCount--;
if (IoEvent->EventContext->MajorFunction == IRP_MJ_CLOSE) {
IoEvent->DokanOpenInfo->CloseFileName =
_wcsdup(IoEvent->EventContext->Operation.Close.FileName);
IoEvent->DokanOpenInfo->CloseUserContext = IoEvent->DokanFileInfo.Context;
IoEvent->DokanOpenInfo->OpenCount--;
}
if (IoEvent->DokanOpenInfo->OpenCount > 0) {
// We are still waiting for the Close event or there is another event running. We delay the Close event.
LeaveCriticalSection(&IoEvent->DokanOpenInfo->CriticalSection);
return;
}
// Process close event as OpenCount is now 0
LPWSTR fileNameForClose = NULL;
if (IoEvent->DokanOpenInfo->CloseFileName) {
fileNameForClose = IoEvent->DokanOpenInfo->CloseFileName;
IoEvent->DokanOpenInfo->CloseFileName = NULL;