Debian Codegraph @

debian/rust-vendor/notify/src/windows.rs

raw
1 #![allow(missing_docs)]
2 //! Watcher implementation for Windows' directory management APIs
3 //!
4 //! For more information see the [ReadDirectoryChangesW reference][ref].
5 //!
6 //! [ref]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa363950(v=vs.85).aspx
7
8 use crate::{bounded, unbounded, BoundSender, Config, Receiver, Sender};
9 use crate::{event::*, WatcherKind};
10 use crate::{Error, EventHandler, RecursiveMode, Result, Watcher};
11 use std::alloc;
12 use std::collections::HashMap;
13 use std::env;
14 use std::ffi::OsString;
15 use std::os::raw::c_void;
16 use std::os::windows::ffi::{OsStrExt, OsStringExt};
17 use std::path::{Path, PathBuf};
18 use std::ptr;
19 use std::slice;
20 use std::sync::{Arc, Mutex};
21 use std::thread;
22 use windows_sys::Win32::Foundation::{
23 CloseHandle, ERROR_ACCESS_DENIED, ERROR_OPERATION_ABORTED, ERROR_SUCCESS, HANDLE,
24 INVALID_HANDLE_VALUE, WAIT_OBJECT_0,
25 };
26 use windows_sys::Win32::Storage::FileSystem::{
27 CreateFileW, ReadDirectoryChangesW, FILE_ACTION_ADDED, FILE_ACTION_MODIFIED,
28 FILE_ACTION_REMOVED, FILE_ACTION_RENAMED_NEW_NAME, FILE_ACTION_RENAMED_OLD_NAME,
29 FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY,
30 FILE_NOTIFY_CHANGE_ATTRIBUTES, FILE_NOTIFY_CHANGE_CREATION, FILE_NOTIFY_CHANGE_DIR_NAME,
31 FILE_NOTIFY_CHANGE_FILE_NAME, FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SECURITY,
32 FILE_NOTIFY_CHANGE_SIZE, FILE_NOTIFY_INFORMATION, FILE_SHARE_DELETE, FILE_SHARE_READ,
33 FILE_SHARE_WRITE, OPEN_EXISTING,
34 };
35 use windows_sys::Win32::System::Threading::{
36 CreateSemaphoreW, ReleaseSemaphore, WaitForSingleObjectEx, INFINITE,
37 };
38 use windows_sys::Win32::System::IO::{CancelIo, OVERLAPPED};
39
40 const BUF_SIZE: u32 = 16384;
41
42 #[derive(Clone)]
43 struct ReadData {
44 dir: PathBuf, // directory that is being watched
45 file: Option<PathBuf>, // if a file is being watched, this is its full path
46 complete_sem: HANDLE,
47 is_recursive: bool,
48 }
49
50 struct ReadDirectoryRequest {
51 event_handler: Arc<Mutex<dyn EventHandler>>,
52 buffer: [u8; BUF_SIZE as usize],
53 handle: HANDLE,
54 data: ReadData,
55 action_tx: Sender<Action>,
56 }
57
58 impl ReadDirectoryRequest {
59 fn unwatch(&self) {
60 let _ = self.action_tx.send(Action::Unwatch(self.data.dir.clone()));
61 }
62 }
63
64 enum Action {
65 Watch(PathBuf, RecursiveMode),
66 Unwatch(PathBuf),
67 Stop,
68 Configure(Config, BoundSender<Result<bool>>),
69 }
70
71 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
72 pub enum MetaEvent {
73 SingleWatchComplete,
74 WatcherAwakened,
75 }
76
77 struct WatchState {
78 dir_handle: HANDLE,
79 complete_sem: HANDLE,
80 }
81
82 struct ReadDirectoryChangesServer {
83 tx: Sender<Action>,
84 rx: Receiver<Action>,
85 event_handler: Arc<Mutex<dyn EventHandler>>,
86 meta_tx: Sender<MetaEvent>,
87 cmd_tx: Sender<Result<PathBuf>>,
88 watches: HashMap<PathBuf, WatchState>,
89 wakeup_sem: HANDLE,
90 }
91
92 impl ReadDirectoryChangesServer {
93 fn start(
94 event_handler: Arc<Mutex<dyn EventHandler>>,
95 meta_tx: Sender<MetaEvent>,
96 cmd_tx: Sender<Result<PathBuf>>,
97 wakeup_sem: HANDLE,
98 ) -> Sender<Action> {
99 let (action_tx, action_rx) = unbounded();
100 // it is, in fact, ok to send the semaphore across threads
101 let sem_temp = wakeup_sem as u64;
102 let _ = thread::Builder::new()
103 .name("notify-rs windows loop".to_string())
104 .spawn({
105 let tx = action_tx.clone();
106 move || {
107 let wakeup_sem = sem_temp as HANDLE;
108 let server = ReadDirectoryChangesServer {
109 tx,
110 rx: action_rx,
111 event_handler,
112 meta_tx,
113 cmd_tx,
114 watches: HashMap::new(),
115 wakeup_sem,
116 };
117 server.run();
118 }
119 });
120 action_tx
121 }
122
123 fn run(mut self) {
124 loop {
125 // process all available actions first
126 let mut stopped = false;
127
128 while let Ok(action) = self.rx.try_recv() {
129 match action {
130 Action::Watch(path, recursive_mode) => {
131 let res = self.add_watch(path, recursive_mode.is_recursive());
132 let _ = self.cmd_tx.send(res);
133 }
134 Action::Unwatch(path) => self.remove_watch(path),
135 Action::Stop => {
136 stopped = true;
137 for ws in self.watches.values() {
138 stop_watch(ws, &self.meta_tx);
139 }
140 break;
141 }
142 Action::Configure(config, tx) => {
143 self.configure_raw_mode(config, tx);
144 }
145 }
146 }
147
148 if stopped {
149 break;
150 }
151
152 unsafe {
153 // wait with alertable flag so that the completion routine fires
154 let waitres = WaitForSingleObjectEx(self.wakeup_sem, 100, 1);
155 if waitres == WAIT_OBJECT_0 {
156 let _ = self.meta_tx.send(MetaEvent::WatcherAwakened);
157 }
158 }
159 }
160
161 // we have to clean this up, since the watcher may be long gone
162 unsafe {
163 CloseHandle(self.wakeup_sem);
164 }
165 }
166
167 fn add_watch(&mut self, path: PathBuf, is_recursive: bool) -> Result<PathBuf> {
168 // path must exist and be either a file or directory
169 if !path.is_dir() && !path.is_file() {
170 return Err(
171 Error::generic("Input watch path is neither a file nor a directory.")
172 .add_path(path),
173 );
174 }
175
176 let (watching_file, dir_target) = {
177 if path.is_dir() {
178 (false, path.clone())
179 } else {
180 // emulate file watching by watching the parent directory
181 (true, path.parent().unwrap().to_path_buf())
182 }
183 };
184
185 let encoded_path: Vec<u16> = dir_target
186 .as_os_str()
187 .encode_wide()
188 .chain(Some(0))
189 .collect();
190 let handle;
191 unsafe {
192 handle = CreateFileW(
193 encoded_path.as_ptr(),
194 FILE_LIST_DIRECTORY,
195 FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE,
196 ptr::null_mut(),
197 OPEN_EXISTING,
198 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
199 ptr::null_mut(),
200 );
201
202 if handle == INVALID_HANDLE_VALUE {
203 return Err(if watching_file {
204 Error::generic(
205 "You attempted to watch a single file, but parent \
206 directory could not be opened.",
207 )
208 .add_path(path)
209 } else {
210 // TODO: Call GetLastError for better error info?
211 Error::path_not_found().add_path(path)
212 });
213 }
214 }
215 let wf = if watching_file {
216 Some(path.clone())
217 } else {
218 None
219 };
220 // every watcher gets its own semaphore to signal completion
221 let semaphore = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
222 if semaphore.is_null() || semaphore == INVALID_HANDLE_VALUE {
223 unsafe {
224 CloseHandle(handle);
225 }
226 return Err(Error::generic("Failed to create semaphore for watch.").add_path(path));
227 }
228 let rd = ReadData {
229 dir: dir_target,
230 file: wf,
231 complete_sem: semaphore,
232 is_recursive,
233 };
234 let ws = WatchState {
235 dir_handle: handle,
236 complete_sem: semaphore,
237 };
238 self.watches.insert(path.clone(), ws);
239 start_read(&rd, self.event_handler.clone(), handle, self.tx.clone());
240 Ok(path)
241 }
242
243 fn remove_watch(&mut self, path: PathBuf) {
244 if let Some(ws) = self.watches.remove(&path) {
245 stop_watch(&ws, &self.meta_tx);
246 }
247 }
248
249 fn configure_raw_mode(&mut self, _config: Config, tx: BoundSender<Result<bool>>) {
250 tx.send(Ok(false))
251 .expect("configuration channel disconnect");
252 }
253 }
254
255 fn stop_watch(ws: &WatchState, meta_tx: &Sender<MetaEvent>) {
256 unsafe {
257 let cio = CancelIo(ws.dir_handle);
258 let ch = CloseHandle(ws.dir_handle);
259 // have to wait for it, otherwise we leak the memory allocated for there read request
260 if cio != 0 && ch != 0 {
261 while WaitForSingleObjectEx(ws.complete_sem, INFINITE, 1) != WAIT_OBJECT_0 {
262 // drain the apc queue, fix for https://github.com/notify-rs/notify/issues/287#issuecomment-801465550
263 }
264 }
265 CloseHandle(ws.complete_sem);
266 }
267 let _ = meta_tx.send(MetaEvent::SingleWatchComplete);
268 }
269
270 fn start_read(
271 rd: &ReadData,
272 event_handler: Arc<Mutex<dyn EventHandler>>,
273 handle: HANDLE,
274 action_tx: Sender<Action>,
275 ) {
276 let request = Box::new(ReadDirectoryRequest {
277 event_handler,
278 handle,
279 buffer: [0u8; BUF_SIZE as usize],
280 data: rd.clone(),
281 action_tx,
282 });
283
284 let flags = FILE_NOTIFY_CHANGE_FILE_NAME
285 | FILE_NOTIFY_CHANGE_DIR_NAME
286 | FILE_NOTIFY_CHANGE_ATTRIBUTES
287 | FILE_NOTIFY_CHANGE_SIZE
288 | FILE_NOTIFY_CHANGE_LAST_WRITE
289 | FILE_NOTIFY_CHANGE_CREATION
290 | FILE_NOTIFY_CHANGE_SECURITY;
291
292 let monitor_subdir = if request.data.file.is_none() && request.data.is_recursive {
293 1
294 } else {
295 0
296 };
297
298 unsafe {
299 let overlapped = alloc::alloc_zeroed(alloc::Layout::new::<OVERLAPPED>()) as *mut OVERLAPPED;
300 // When using callback based async requests, we are allowed to use the hEvent member
301 // for our own purposes
302
303 let request = Box::leak(request);
304 (*overlapped).hEvent = request as *mut _ as _;
305
306 // This is using an asynchronous call with a completion routine for receiving notifications
307 // An I/O completion port would probably be more performant
308 let ret = ReadDirectoryChangesW(
309 handle,
310 request.buffer.as_mut_ptr() as *mut c_void,
311 BUF_SIZE,
312 monitor_subdir,
313 flags,
314 &mut 0u32 as *mut u32, // not used for async reqs
315 overlapped,
316 Some(handle_event),
317 );
318
319 if ret == 0 {
320 // error reading. retransmute request memory to allow drop.
321 // Because of the error, ownership of the `overlapped` alloc was not passed
322 // over to `ReadDirectoryChangesW`.
323 // So we can claim ownership back.
324 let _overlapped = Box::from_raw(overlapped);
325 let request = Box::from_raw(request);
326 ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
327 }
328 }
329 }
330
331 unsafe extern "system" fn handle_event(
332 error_code: u32,
333 _bytes_written: u32,
334 overlapped: *mut OVERLAPPED,
335 ) {
336 let overlapped: Box<OVERLAPPED> = Box::from_raw(overlapped);
337 let request: Box<ReadDirectoryRequest> = Box::from_raw(overlapped.hEvent as *mut _);
338
339 match error_code {
340 ERROR_OPERATION_ABORTED => {
341 // received when dir is unwatched or watcher is shutdown; return and let overlapped/request get drop-cleaned
342 ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
343 return;
344 }
345 ERROR_ACCESS_DENIED => {
346 // This could happen when the watched directory is deleted or trashed, first check if it's the case.
347 // If so, unwatch the directory and return, otherwise, continue to handle the event.
348 if !request.data.dir.exists() {
349 request.unwatch();
350 ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
351 return;
352 }
353 }
354 ERROR_SUCCESS => {
355 // Success, continue to handle the event
356 }
357 _ => {
358 // Some unidentified error occurred, log and unwatch the directory, then return.
359 log::error!(
360 "unknown error in ReadDirectoryChangesW for directory {}: {}",
361 request.data.dir.display(),
362 error_code
363 );
364 request.unwatch();
365 ReleaseSemaphore(request.data.complete_sem, 1, ptr::null_mut());
366 return;
367 }
368 }
369
370 // Get the next request queued up as soon as possible
371 start_read(
372 &request.data,
373 request.event_handler.clone(),
374 request.handle,
375 request.action_tx,
376 );
377
378 // The FILE_NOTIFY_INFORMATION struct has a variable length due to the variable length
379 // string as its last member. Each struct contains an offset for getting the next entry in
380 // the buffer.
381 let mut cur_offset: *const u8 = request.buffer.as_ptr();
382 // In Wine, FILE_NOTIFY_INFORMATION structs are packed placed in the buffer;
383 // they are aligned to 16bit (WCHAR) boundary instead of 32bit required by FILE_NOTIFY_INFORMATION.
384 // Hence, we need to use `read_unaligned` here to avoid UB.
385 let mut cur_entry = ptr::read_unaligned(cur_offset as *const FILE_NOTIFY_INFORMATION);
386 loop {
387 // filename length is size in bytes, so / 2
388 let len = cur_entry.FileNameLength as usize / 2;
389 let encoded_path: &[u16] = slice::from_raw_parts(
390 cur_offset.offset(std::mem::offset_of!(FILE_NOTIFY_INFORMATION, FileName) as isize)
391 as _,
392 len,
393 );
394 // prepend root to get a full path
395 let path = request
396 .data
397 .dir
398 .join(PathBuf::from(OsString::from_wide(encoded_path)));
399
400 // if we are watching a single file, ignore the event unless the path is exactly
401 // the watched file
402 let skip = match request.data.file {
403 None => false,
404 Some(ref watch_path) => *watch_path != path,
405 };
406
407 if !skip {
408 log::trace!(
409 "Event: path = `{}`, action = {:?}",
410 path.display(),
411 cur_entry.Action
412 );
413
414 let newe = Event::new(EventKind::Any).add_path(path);
415
416 fn emit_event(event_handler: &Mutex<dyn EventHandler>, res: Result<Event>) {
417 if let Ok(mut guard) = event_handler.lock() {
418 let f: &mut dyn EventHandler = &mut *guard;
419 f.handle_event(res);
420 }
421 }
422
423 let event_handler = |res| emit_event(&request.event_handler, res);
424
425 if cur_entry.Action == FILE_ACTION_RENAMED_OLD_NAME {
426 let mode = RenameMode::From;
427 let kind = ModifyKind::Name(mode);
428 let kind = EventKind::Modify(kind);
429 let ev = newe.set_kind(kind);
430 event_handler(Ok(ev))
431 } else {
432 match cur_entry.Action {
433 FILE_ACTION_RENAMED_NEW_NAME => {
434 let kind = EventKind::Modify(ModifyKind::Name(RenameMode::To));
435 let ev = newe.set_kind(kind);
436 event_handler(Ok(ev));
437 }
438 FILE_ACTION_ADDED => {
439 let kind = EventKind::Create(CreateKind::Any);
440 let ev = newe.set_kind(kind);
441 event_handler(Ok(ev));
442 }
443 FILE_ACTION_REMOVED => {
444 let kind = EventKind::Remove(RemoveKind::Any);
445 let ev = newe.set_kind(kind);
446 event_handler(Ok(ev));
447 }
448 FILE_ACTION_MODIFIED => {
449 let kind = EventKind::Modify(ModifyKind::Any);
450 let ev = newe.set_kind(kind);
451 event_handler(Ok(ev));
452 }
453 _ => (),
454 };
455 }
456 }
457
458 if cur_entry.NextEntryOffset == 0 {
459 break;
460 }
461 cur_offset = cur_offset.offset(cur_entry.NextEntryOffset as isize);
462 cur_entry = ptr::read_unaligned(cur_offset as *const FILE_NOTIFY_INFORMATION);
463 }
464 }
465
466 /// Watcher implementation based on ReadDirectoryChanges
467 #[derive(Debug)]
468 pub struct ReadDirectoryChangesWatcher {
469 tx: Sender<Action>,
470 cmd_rx: Receiver<Result<PathBuf>>,
471 wakeup_sem: HANDLE,
472 }
473
474 impl ReadDirectoryChangesWatcher {
475 pub fn create(
476 event_handler: Arc<Mutex<dyn EventHandler>>,
477 meta_tx: Sender<MetaEvent>,
478 ) -> Result<ReadDirectoryChangesWatcher> {
479 let (cmd_tx, cmd_rx) = unbounded();
480
481 let wakeup_sem = unsafe { CreateSemaphoreW(ptr::null_mut(), 0, 1, ptr::null_mut()) };
482 if wakeup_sem.is_null() || wakeup_sem == INVALID_HANDLE_VALUE {
483 return Err(Error::generic("Failed to create wakeup semaphore."));
484 }
485
486 let action_tx =
487 ReadDirectoryChangesServer::start(event_handler, meta_tx, cmd_tx, wakeup_sem);
488
489 Ok(ReadDirectoryChangesWatcher {
490 tx: action_tx,
491 cmd_rx,
492 wakeup_sem,
493 })
494 }
495
496 fn wakeup_server(&mut self) {
497 // breaks the server out of its wait state. right now this is really just an optimization,
498 // so that if you add a watch you don't block for 100ms in watch() while the
499 // server sleeps.
500 unsafe {
501 ReleaseSemaphore(self.wakeup_sem, 1, ptr::null_mut());
502 }
503 }
504
505 fn send_action_require_ack(&mut self, action: Action, pb: &PathBuf) -> Result<()> {
506 self.tx
507 .send(action)
508 .map_err(|_| Error::generic("Error sending to internal channel"))?;
509
510 // wake 'em up, we don't want to wait around for the ack
511 self.wakeup_server();
512
513 let ack_pb = self
514 .cmd_rx
515 .recv()
516 .map_err(|_| Error::generic("Error receiving from command channel"))?
517 .map_err(|e| Error::generic(&format!("Error in watcher: {:?}", e)))?;
518
519 if pb.as_path() != ack_pb.as_path() {
520 Err(Error::generic(&format!(
521 "Expected ack for {:?} but got \
522 ack for {:?}",
523 pb, ack_pb
524 )))
525 } else {
526 Ok(())
527 }
528 }
529
530 fn watch_inner(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
531 let pb = if path.is_absolute() {
532 path.to_owned()
533 } else {
534 let p = env::current_dir().map_err(Error::io)?;
535 p.join(path)
536 };
537 // path must exist and be either a file or directory
538 if !pb.is_dir() && !pb.is_file() {
539 return Err(Error::generic(
540 "Input watch path is neither a file nor a directory.",
541 ));
542 }
543 self.send_action_require_ack(Action::Watch(pb.clone(), recursive_mode), &pb)
544 }
545
546 fn unwatch_inner(&mut self, path: &Path) -> Result<()> {
547 let pb = if path.is_absolute() {
548 path.to_owned()
549 } else {
550 let p = env::current_dir().map_err(Error::io)?;
551 p.join(path)
552 };
553 let res = self
554 .tx
555 .send(Action::Unwatch(pb))
556 .map_err(|_| Error::generic("Error sending to internal channel"));
557 self.wakeup_server();
558 res
559 }
560 }
561
562 impl Watcher for ReadDirectoryChangesWatcher {
563 fn new<F: EventHandler>(event_handler: F, _config: Config) -> Result<Self> {
564 // create dummy channel for meta event
565 // TODO: determine the original purpose of this - can we remove it?
566 let (meta_tx, _) = unbounded();
567 let event_handler = Arc::new(Mutex::new(event_handler));
568 Self::create(event_handler, meta_tx)
569 }
570
571 fn watch(&mut self, path: &Path, recursive_mode: RecursiveMode) -> Result<()> {
572 self.watch_inner(path, recursive_mode)
573 }
574
575 fn unwatch(&mut self, path: &Path) -> Result<()> {
576 self.unwatch_inner(path)
577 }
578
579 fn configure(&mut self, config: Config) -> Result<bool> {
580 let (tx, rx) = bounded(1);
581 self.tx.send(Action::Configure(config, tx))?;
582 rx.recv()?
583 }
584
585 fn kind() -> crate::WatcherKind {
586 WatcherKind::ReadDirectoryChangesWatcher
587 }
588 }
589
590 impl Drop for ReadDirectoryChangesWatcher {
591 fn drop(&mut self) {
592 let _ = self.tx.send(Action::Stop);
593 // better wake it up
594 self.wakeup_server();
595 }
596 }
597
598 // `ReadDirectoryChangesWatcher` is not Send/Sync because of the semaphore Handle.
599 // As said elsewhere it's perfectly safe to send it across threads.
600 unsafe impl Send for ReadDirectoryChangesWatcher {}
601 // Because all public methods are `&mut self` it's also perfectly safe to share references.
602 unsafe impl Sync for ReadDirectoryChangesWatcher {}