-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathlib.rs
327 lines (299 loc) · 9.68 KB
/
lib.rs
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
#![cfg(windows)]
#![doc(html_root_url = "https://dokan-dev.github.io/dokan-rust-doc/html")]
//! [Dokan] is a user mode file system for Windows. It allows anyone to safely and easily develop
//! new file systems on Windows.
//!
//! This crate is a Rust-friendly wrapper for Dokan, allowing you to create file systems using Rust.
//! It builds upon the low-level [`dokan-sys`] crate.
//!
//! In general, to create a file system with this library, you need to implement the
//! [`FileSystemHandler`] trait, create a [`FileSystemMounter`], and [mount](FileSystemMounter::mount) it
//! to create a [`FileSystem`]. When dropped, the latter will block the current thread until it gets unmounted.
//! You have to call [`init`] once before, and [`shutdown`] when you're done.
//!
//! The same explanations with a few lines of code: see [the MemFS example](https://github.com/dokan-dev/dokan-rust/blob/master/dokan/examples/memfs/main.rs#L1330)!
//!
//! Please note that some of the constants from Win32 API that might be used when interacting with
//! this crate are not provided directly here. However, you can easily find them in the
//! [`winapi`] crate.
//!
//! [Dokan]: https://dokan-dev.github.io/
//! [`dokan-sys`]: https://crates.io/crates/dokan-sys
//! [`winapi`]: https://crates.io/crates/winapi
mod data;
mod file_system;
mod file_system_handler;
mod notify;
mod operations;
mod operations_helpers;
mod to_file_time;
#[cfg(test)]
mod usage_tests;
use dokan_sys::*;
use widestring::U16CStr;
use winapi::{
shared::{
minwindef::{DWORD, FALSE, TRUE},
ntdef::NTSTATUS,
},
um::{errhandlingapi::GetLastError, winnt::ACCESS_MASK},
};
pub use crate::{data::*, file_system::*, file_system_handler::*, notify::*};
/// Re-exported from `dokan-sys` for convenience.
pub use dokan_sys::{
DOKAN_DRIVER_NAME as DRIVER_NAME, DOKAN_IO_SECURITY_CONTEXT as IO_SECURITY_CONTEXT,
DOKAN_MAJOR_API_VERSION as MAJOR_API_VERSION, DOKAN_NP_NAME as NP_NAME,
DOKAN_VERSION as WRAPPER_VERSION,
};
/// Initializes all required Dokan internal resources.
///
/// This needs to be called only once before trying to use other functions for the first time.
/// Otherwise they will fail and raise an exception.
pub fn init() {
unsafe { DokanInit() }
}
/// Releases all allocated resources by [`init`] when they are no longer needed.
///
/// This should be called when the application no longer expects to create a new FileSystem and after all devices are unmount.
pub fn shutdown() {
unsafe { DokanShutdown() }
}
/// Gets version of the loaded Dokan library.
///
/// The returned value is the version number without dots. For example, it returns `131` if Dokan
/// v1.3.1 is loaded.
pub fn get_lib_version() -> u32 {
unsafe { DokanVersion() }
}
/// Gets version of the Dokan driver installed on the current system.
///
/// The returned value is the version number without dots.
pub fn get_driver_version() -> u32 {
unsafe { DokanDriverVersion() }
}
#[test]
fn test_versions() {
assert_eq!(MAJOR_API_VERSION, (get_lib_version() / 100).to_string());
assert!(get_driver_version() < 1000);
assert_eq!(DRIVER_NAME, format!("dokan{}.sys", MAJOR_API_VERSION));
assert_eq!(NP_NAME, format!("Dokan{}", MAJOR_API_VERSION));
}
/// Checks whether the `name` matches the specified `expression`.
///
/// This is a helper function that can be used to implement
/// [`FileSystemHandler::find_files_with_pattern`]. It behaves like the [`FsRtlIsNameInExpression`]
/// routine provided for file system drivers by Windows.
///
/// [`FsRtlIsNameInExpression`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/nf-ntifs-_fsrtl_advanced_fcb_header-fsrtlisnameinexpression
pub fn is_name_in_expression(
expression: impl AsRef<U16CStr>,
name: impl AsRef<U16CStr>,
ignore_case: bool,
) -> bool {
unsafe {
DokanIsNameInExpression(
expression.as_ref().as_ptr(),
name.as_ref().as_ptr(),
ignore_case.into(),
) == TRUE
}
}
#[test]
fn test_is_name_in_expression() {
use usage_tests::convert_str;
assert_eq!(
is_name_in_expression(convert_str("foo"), convert_str("foo"), true),
true
);
assert_eq!(
is_name_in_expression(convert_str("*"), convert_str("foo"), true),
true
);
assert_eq!(
is_name_in_expression(convert_str("?"), convert_str("x"), true),
true
);
assert_eq!(
is_name_in_expression(convert_str("?"), convert_str("foo"), true),
false
);
assert_eq!(
is_name_in_expression(convert_str("F*"), convert_str("foo"), true),
true
);
assert_eq!(
is_name_in_expression(convert_str("F*"), convert_str("foo"), false),
false
);
}
/// Converts Win32 error (e.g. returned by [`GetLastError`]) to [`NTSTATUS`].
pub fn map_win32_error_to_ntstatus(error: DWORD) -> NTSTATUS {
unsafe { DokanNtStatusFromWin32(error) }
}
#[test]
fn can_map_win32_error_to_ntstatus() {
use winapi::shared::{ntstatus::STATUS_INTERNAL_ERROR, winerror::ERROR_INTERNAL_ERROR};
assert_eq!(
map_win32_error_to_ntstatus(ERROR_INTERNAL_ERROR),
STATUS_INTERNAL_ERROR
);
}
/// For convenience, returns an `Err(`[`NTSTATUS`]`)` from [`GetLastError`] if the condition is `false`.
///
/// It builds upon [`map_win32_error_to_ntstatus`].
///
/// **Warning**: success of some functions can only be known by checking `GetLastError`.
/// In such cases, **do not use this function!**
/// For instance, `ReadFile` and `WriteFile` in asynchronous mode are successful if they
/// return `FALSE` and `GetLastError` returns `ERROR_IO_PENDING`.
///
/// # Example
///
/// ```
/// # use std::ptr;
/// #
/// # use dokan::win32_ensure;
/// # use widestring::U16CString;
/// # use winapi::{shared::ntdef::NTSTATUS, um::processenv::GetCurrentDirectoryW};
/// #
/// fn get_current_directory() -> Result<U16CString, NTSTATUS> {
/// unsafe {
/// let len = GetCurrentDirectoryW(0, ptr::null_mut());
/// win32_ensure(len != 0)?;
///
/// let mut buffer = Vec::with_capacity(len as usize);
/// let actual_len = GetCurrentDirectoryW(len, buffer.as_mut_ptr());
/// win32_ensure(actual_len != 0)?;
/// assert_eq!(actual_len, len);
///
/// Ok(U16CString::from_vec_with_nul_unchecked(buffer))
/// }
/// }
/// ```
pub fn win32_ensure(condition: bool) -> Result<(), NTSTATUS> {
match condition {
true => Ok(()),
false => Err(map_win32_error_to_ntstatus(unsafe { GetLastError() })),
}
}
/// Flags returned by [`map_kernel_to_user_create_file_flags`].
///
/// These flags are the same as those accepted by [`CreateFile`].
///
/// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct UserCreateFileFlags {
/// The requested access to the file.
pub desired_access: ACCESS_MASK,
/// The file attributes and flags.
pub flags_and_attributes: u32,
/// The action to take on the file that exists or does not exist.
pub creation_disposition: u32,
}
/// Converts the arguments passed to [`FileSystemHandler::create_file`] to flags accepted by the
/// Win32 [`CreateFile`] function.
///
/// Dokan forwards the parameters directly from [`IRP_MJ_CREATE`]. This functions converts them to
/// corresponding flags in Win32, making it easier to process them.
///
/// [`CreateFile`]: https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew
/// [`IRP_MJ_CREATE`]: https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/irp-mj-create
pub fn map_kernel_to_user_create_file_flags(
desired_access: ACCESS_MASK,
file_attributes: u32,
create_options: u32,
create_disposition: u32,
) -> UserCreateFileFlags {
let mut result = UserCreateFileFlags {
desired_access: 0,
flags_and_attributes: 0,
creation_disposition: 0,
};
unsafe {
DokanMapKernelToUserCreateFileFlags(
desired_access,
file_attributes,
create_options,
create_disposition,
&mut result.desired_access,
&mut result.flags_and_attributes,
&mut result.creation_disposition,
);
}
result
}
#[test]
fn test_map_kernel_to_user_create_file_flags() {
use dokan_sys::win32::{FILE_OPEN, FILE_WRITE_THROUGH};
use winapi::um::{
fileapi::OPEN_EXISTING,
winbase::FILE_FLAG_WRITE_THROUGH,
winnt::{
FILE_ALL_ACCESS, FILE_ATTRIBUTE_NORMAL, GENERIC_ALL, GENERIC_EXECUTE, GENERIC_READ,
GENERIC_WRITE,
},
};
let result = map_kernel_to_user_create_file_flags(
FILE_ALL_ACCESS,
FILE_ATTRIBUTE_NORMAL,
FILE_WRITE_THROUGH,
FILE_OPEN,
);
assert_eq!(
result.desired_access,
GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL
);
assert_eq!(
result.flags_and_attributes,
FILE_FLAG_WRITE_THROUGH | FILE_ATTRIBUTE_NORMAL
);
assert_eq!(result.creation_disposition, OPEN_EXISTING);
}
/// Unmounts a Dokan volume from the specified mount point.
///
/// Returns whether it succeeded.
#[must_use]
pub fn unmount(mount_point: impl AsRef<U16CStr>) -> bool {
unsafe { DokanRemoveMountPoint(mount_point.as_ref().as_ptr()) == TRUE }
}
/// Output stream to write debug messages to.
///
/// Used by [`set_debug_stream`].
pub enum DebugStream {
/// The standard output stream.
Stdout,
/// The standard input stream.
Stderr,
}
/// Sets the output stream to write debug messages to.
pub fn set_debug_stream(stream: DebugStream) {
unsafe {
DokanUseStdErr(if let DebugStream::Stdout = stream {
TRUE
} else {
FALSE
});
}
}
/// Enables or disables debug mode of the user mode library.
pub fn set_lib_debug_mode(enabled: bool) {
unsafe {
DokanDebugMode(if enabled { TRUE } else { FALSE });
}
}
/// Enables or disables debug mode of the kernel driver;
///
/// Returns `true` on success.
#[must_use]
pub fn set_driver_debug_mode(enabled: bool) -> bool {
unsafe { DokanSetDebugMode(if enabled { TRUE } else { FALSE }) == TRUE }
}
#[test]
fn test_debug_mode() {
set_debug_stream(DebugStream::Stdout);
set_debug_stream(DebugStream::Stderr);
set_lib_debug_mode(true);
set_lib_debug_mode(false);
assert!(set_driver_debug_mode(true));
assert!(set_driver_debug_mode(false));
}