| 1 | package Filesys::Notify::Win32::ReadDirectoryChanges; | ||
| 2 | use 5.020; | ||
| 3 | |||
| 4 | use Moo 2; | ||
| 5 | use feature 'signatures'; | ||
| 6 | no warnings 'experimental::signatures'; | ||
| 7 | |||
| 8 | use File::Spec; | ||
| 9 | use Win32::API; | ||
| 10 | use Win32API::File 'CreateFile', 'CloseHandle', ':FILE_FLAG_', 'FILE_LIST_DIRECTORY', 'OPEN_EXISTING', 'FILE_SHARE_WRITE', 'FILE_SHARE_READ', 'GENERIC_READ'; | ||
| 11 | use threads; # we launch a thread for each watched tree to keep the logic simple | ||
| 12 | use Thread::Queue; | ||
| 13 | use Encode 'decode'; | ||
| 14 | |||
| 15 | our $VERSION = '0.07'; | ||
| 16 | our $is_cygwin = $^O eq 'cygwin'; | ||
| 17 | our $bufsize = 65520; | ||
| 18 | |||
| 19 | =head1 NAME | ||
| 20 | |||
| 21 | Filesys::Notify::Win32::ReadDirectoryChanges - read/watch directory changes | ||
| 22 | |||
| 23 | =head1 SYNOPSIS | ||
| 24 | |||
| 25 | my $watcher = Filesys::Notify::Win32::ReadDirectoryChanges->new(); | ||
| 26 | for my $dir (@ARGV) { | ||
| 27 | $watcher->watch_directory( path => $dir, subtree => 1 ); | ||
| 28 | }; | ||
| 29 | $watcher->wait(sub { | ||
| 30 | my( $event ) = @_; | ||
| 31 | say $event->{action}, ":", $event->{path}; | ||
| 32 | }); | ||
| 33 | |||
| 34 | This module allows to watch multiple directories for changes and invokes a | ||
| 35 | callback for every change. | ||
| 36 | |||
| 37 | This module spawns a thread for each watched directory. Each such thread | ||
| 38 | synchronously reads file system changes and communicates them to the main | ||
| 39 | thread through a L<Thread::Queue>. | ||
| 40 | |||
| 41 | =head1 METHODS | ||
| 42 | |||
| 43 | =head2 C<< ->new %options >> | ||
| 44 | |||
| 45 | my $w = Filesys::Notify::Win32::ReadDirectoryChanges->new( | ||
| 46 | directories => \@ARGV, | ||
| 47 | subtree => 1, | ||
| 48 | ); | ||
| 49 | |||
| 50 | Creates a new watcher object. | ||
| 51 | |||
| 52 | =cut | ||
| 53 | |||
| 54 | sub BUILD($self, $args) { | ||
| 55 | if( my $dirs = delete $args->{directory}) { | ||
| 56 | $dirs = [$dirs] if ! ref $dirs; | ||
| 57 | for my $d (@$dirs) { | ||
| 58 | $self->watch_directory( path => $d ); | ||
| 59 | } | ||
| 60 | } | ||
| 61 | } | ||
| 62 | |||
| 63 | has 'subtree' => ( | ||
| 64 | is => 'ro', | ||
| 65 | ); | ||
| 66 | |||
| 67 | has 'watchers' => ( | ||
| 68 | is => 'lazy', | ||
| 69 | default => sub{ +{} }, | ||
| 70 | ); | ||
| 71 | |||
| 72 | =head2 C<< ->queue >> | ||
| 73 | |||
| 74 | my $q = $w->queue; | ||
| 75 | |||
| 76 | Returns the L<Thread::Queue> object where the filesystem events get | ||
| 77 | passed in. Use this for integration with your own event loop. | ||
| 78 | |||
| 79 | =cut | ||
| 80 | |||
| 81 | has 'queue' => ( | ||
| 82 | is => 'lazy', | ||
| 83 | default => sub { Thread::Queue->new() }, | ||
| 84 | ); | ||
| 85 | |||
| 86 | Win32::API::More->Import( 'kernel32', 'BOOL ReadDirectoryChangesW( | ||
| 87 | HANDLE hDirectory, | ||
| 88 | LPVOID lpBuffer, | ||
| 89 | DWORD nBufferLength, | ||
| 90 | BOOL bWatchSubtree, | ||
| 91 | DWORD dwNotifyFilter, | ||
| 92 | LPDWORD lpBytesReturned, | ||
| 93 | LPVOID lpOverlapped, | ||
| 94 | LPVOID lpCompletionRoutine | ||
| 95 | )' ) | ||
| 96 | or die Win32::FormatMessage(Win32::GetLastError()); | ||
| 97 | Win32::API->Import( 'kernel32.dll', 'CancelIoEx', 'NN','N' ) | ||
| 98 | or die $^E; | ||
| 99 | |||
| 100 | our @action = ( | ||
| 101 | 'unknown', | ||
| 102 | 'added', | ||
| 103 | 'removed', | ||
| 104 | 'modified', | ||
| 105 | 'old_name', | ||
| 106 | 'new_name', | ||
| 107 | ); | ||
| 108 | |||
| 109 | sub _unpack_file_notify_information( $buf ) { | ||
| 110 | # typedef struct _FILE_NOTIFY_INFORMATION { | ||
| 111 | # DWORD NextEntryOffset; | ||
| 112 | # DWORD Action; | ||
| 113 | # DWORD FileNameLength; | ||
| 114 | # WCHAR FileName[1]; | ||
| 115 | # } FILE_NOTIFY_INFORMATION, *PFILE_NOTIFY_INFORMATION; | ||
| 116 | |||
| 117 | my @res; | ||
| 118 | my $ofs = 0; | ||
| 119 | my $last_name; | ||
| 120 | my $last_action; | ||
| 121 | do { | ||
| 122 | my ($next, $action, $fn ) = unpack 'VVV/a', $buf; | ||
| 123 | $ofs = $next; | ||
| 124 | $fn = decode( 'UTF-16le', $fn ); | ||
| 125 | push @res, { action => $action[ $action ], path => $fn }; | ||
| 126 | |||
| 127 | if( $action == 5 and $last_action == 4 ) { | ||
| 128 | # Create a synthetic event in addition | ||
| 129 | push @res, { | ||
| 130 | action => 'renamed', | ||
| 131 | old_name => $last_name, | ||
| 132 | new_name => $fn, | ||
| 133 | path => $last_name, | ||
| 134 | hint => 'synthetic', | ||
| 135 | }; | ||
| 136 | } | ||
| 137 | $last_name = $fn; | ||
| 138 | $last_action = $action; | ||
| 139 | |||
| 140 | $buf = substr($buf, $next); | ||
| 141 | } while $ofs > 0; | ||
| 142 | @res | ||
| 143 | } | ||
| 144 | |||
| 145 | sub _ReadDirectoryChangesW( $hDirectory, $watchSubTree, $filter ) { | ||
| 146 | my $buffer = "\0" x $bufsize; | ||
| 147 | my $returnBufferSize = 0; | ||
| 148 | my $r = ReadDirectoryChangesW( | ||
| 149 | $hDirectory, | ||
| 150 | $buffer, | ||
| 151 | length($buffer), | ||
| 152 | !!$watchSubTree, | ||
| 153 | $filter, | ||
| 154 | $returnBufferSize, | ||
| 155 | undef, | ||
| 156 | undef); | ||
| 157 | if( $r ) { | ||
| 158 | return substr $buffer, 0, $returnBufferSize; | ||
| 159 | } else { | ||
| 160 | return undef | ||
| 161 | } | ||
| 162 | } | ||
| 163 | |||
| 164 | # Add ReadDirectoryChangesExW support | ||
| 165 | # Consider sub backfillExtendedInformation($fn,$info) { | ||
| 166 | # } | ||
| 167 | |||
| 168 | # This is what each thread runs, in a named subroutine so | ||
| 169 | # we don't accidentially close over some variable | ||
| 170 | sub _watcher($winpath,$orgpath,$hPath,$subtree,$queue) { | ||
| 171 | my $running = 1; | ||
| 172 | while($running) { | ||
| 173 | # 0x1b means 'DIR_NAME|FILE_NAME|LAST_WRITE|SIZE|CHANGE_ATTRIBUTES' = 2|1|0x10|8|4 | ||
| 174 | my $res = _ReadDirectoryChangesW($hPath, $subtree, 0x1f); | ||
| 175 | |||
| 176 | if( ! defined $res ) { | ||
| 177 | my $err = Win32::GetLastError(); | ||
| 178 | if( $err != 995 ) { # 995 means ReadDirectoryChangesW got cancelled and we should quit | ||
| 179 | warn $orgpath; | ||
| 180 | warn $winpath; | ||
| 181 | warn $^E; | ||
| 182 | } | ||
| 183 | last | ||
| 184 | }; | ||
| 185 | |||
| 186 | for my $i (_unpack_file_notify_information($res)) { | ||
| 187 | $i->{path} = $winpath . $i->{path}; | ||
| 188 | if( $is_cygwin ) { | ||
| 189 | my $p = $i->{path}; | ||
| 190 | $i->{path} = Cygwin::win_to_posix_path( $p ); | ||
| 191 | }; | ||
| 192 | if( $i->{action} eq 'renamed') { | ||
| 193 | for( qw(old_name new_name)) { | ||
| 194 | $i->{$_} = $winpath . $i->{$_}; | ||
| 195 | if( $is_cygwin ) { | ||
| 196 | $i->{$_} = Cygwin::win_to_posix_path( $i->{$_} ); | ||
| 197 | }; | ||
| 198 | }; | ||
| 199 | }; | ||
| 200 | $queue->enqueue($i); | ||
| 201 | }; | ||
| 202 | } | ||
| 203 | }; | ||
| 204 | |||
| 205 | sub build_watcher( $self, %options ) { | ||
| 206 | my $orgpath = delete $options{ path }; | ||
| 207 | my $winpath = $is_cygwin ? Cygwin::posix_to_win_path($orgpath) : $orgpath; | ||
| 208 | my $subtree = !!( $options{ subtree } // $self->subtree ); | ||
| 209 | $winpath .= "\\" if $winpath !~ /\\\z/; | ||
| 210 | my $queue = $self->queue; | ||
| 211 | my $hPath = CreateFile( $winpath, FILE_LIST_DIRECTORY()|GENERIC_READ(), FILE_SHARE_READ() | FILE_SHARE_WRITE(), [], OPEN_EXISTING(), FILE_FLAG_BACKUP_SEMANTICS(), [] ) | ||
| 212 | or die $^E; | ||
| 213 | $orgpath =~ s![\\/]$!!; | ||
| 214 | my $thr = threads->new( \&_watcher, $winpath, $orgpath, $hPath, $subtree, $queue); | ||
| 215 | return { thread => $thr, handle => $hPath }; | ||
| 216 | } | ||
| 217 | |||
| 218 | =head2 C<< ->watch_directory >> | ||
| 219 | |||
| 220 | $w->watch_directory( path => $dir, subtree => 1 ); | ||
| 221 | |||
| 222 | Add a directory to the list of watched directories. | ||
| 223 | |||
| 224 | =cut | ||
| 225 | |||
| 226 | sub watch_directory( $self, %options ) { | ||
| 227 | my $dir = delete $options{ path }; | ||
| 228 | if( $self->watchers->{$dir}) { | ||
| 229 | $self->unwatch_directory( path => $dir ); | ||
| 230 | } | ||
| 231 | $self->watchers->{ $dir } = $self->build_watcher( | ||
| 232 | queue => $self->queue, | ||
| 233 | path => $dir, | ||
| 234 | %options | ||
| 235 | ); | ||
| 236 | } | ||
| 237 | |||
| 238 | =head2 C<< ->unwatch_directory >> | ||
| 239 | |||
| 240 | $w->unwatch_directory( path => $dir ); | ||
| 241 | |||
| 242 | Remove a directory from the list of watched directories. There still may | ||
| 243 | come in some events stored for that directory previously in the queue. | ||
| 244 | |||
| 245 | =cut | ||
| 246 | |||
| 247 | sub unwatch_directory( $self, %options ) { | ||
| 248 | my $dir = delete $options{ path }; | ||
| 249 | if( my $t = delete $self->watchers->{ $dir }) { | ||
| 250 | CancelIoEx($t->{handle},0); | ||
| 251 | CloseHandle($t->{handle}); | ||
| 252 | my $thr = delete $t->{thread}; | ||
| 253 | eval { $thr->join; }; # sometimes the thread is not yet joinable?! | ||
| 254 | } | ||
| 255 | } | ||
| 256 | |||
| 257 | sub DESTROY($self) { | ||
| 258 | if( my $w = $self->{watchers}) { | ||
| 259 | for my $t (keys %$w) { | ||
| 260 | $self->unwatch_directory( path => $t ) | ||
| 261 | } | ||
| 262 | }; | ||
| 263 | } | ||
| 264 | |||
| 265 | =head2 C<< ->wait $CB >> | ||
| 266 | |||
| 267 | $w->wait(sub { | ||
| 268 | my ($event) = @_; | ||
| 269 | say $event->{action}; | ||
| 270 | say $event->{path}; | ||
| 271 | }); | ||
| 272 | |||
| 273 | Synchronously wait for file system events. | ||
| 274 | |||
| 275 | =cut | ||
| 276 | |||
| 277 | sub wait( $self, $cb) { | ||
| 278 | while( 1 ) { | ||
| 279 | my @events = $self->queue->dequeue; | ||
| 280 | for (@events) { | ||
| 281 | if( defined $_ ) { | ||
| 282 | $cb->($_); | ||
| 283 | } else { | ||
| 284 | # somebody did ->queue->enqueue(undef) to stop us | ||
| 285 | last; | ||
| 286 | } | ||
| 287 | }; | ||
| 288 | }; | ||
| 289 | } | ||
| 290 | |||
| 291 | 1; | ||
| 292 | |||
| 293 | =head1 EVENTS | ||
| 294 | |||
| 295 | The following events are created by ReadDirectoryChangesW resp. this module | ||
| 296 | |||
| 297 | =over 4 | ||
| 298 | |||
| 299 | =item B<added> | ||
| 300 | |||
| 301 | { | ||
| 302 | action => 'added', | ||
| 303 | path => 'old-name.example', | ||
| 304 | } | ||
| 305 | |||
| 306 | A new file was created | ||
| 307 | |||
| 308 | =item B<removed> | ||
| 309 | |||
| 310 | { | ||
| 311 | action => 'removed', | ||
| 312 | path => 'old-name.example', | ||
| 313 | } | ||
| 314 | |||
| 315 | A file was removed | ||
| 316 | |||
| 317 | =item B<modified> | ||
| 318 | |||
| 319 | { | ||
| 320 | action => 'modified', | ||
| 321 | path => 'old-name.example', | ||
| 322 | } | ||
| 323 | |||
| 324 | A file was modified | ||
| 325 | |||
| 326 | =item B<old_name> | ||
| 327 | |||
| 328 | { | ||
| 329 | action => 'old_name', | ||
| 330 | path => 'old-name.example', | ||
| 331 | } | ||
| 332 | |||
| 333 | First half of a rename | ||
| 334 | |||
| 335 | =item B<new_name> | ||
| 336 | |||
| 337 | { | ||
| 338 | action => 'new_name', | ||
| 339 | path => 'new-name.example', | ||
| 340 | } | ||
| 341 | |||
| 342 | Second half of a rename | ||
| 343 | |||
| 344 | =item B<renamed> | ||
| 345 | |||
| 346 | Whenever the event B<old_name> is followed immediately by B<new_name>, | ||
| 347 | a third, synthetic event is generated, C<renamed>. | ||
| 348 | |||
| 349 | { | ||
| 350 | action => 'renamed', | ||
| 351 | path => 'old-name.example', | ||
| 352 | old_name => 'old-name.example', | ||
| 353 | new_name => 'new-name.example', | ||
| 354 | } | ||
| 355 | |||
| 356 | =back | ||
| 357 | |||
| 358 | =head1 GLOBAL VARIABLES | ||
| 359 | |||
| 360 | =over 4 | ||
| 361 | |||
| 362 | =item C<$bufsize> | ||
| 363 | |||
| 364 | local $Filesys::Notify::Win32::ReadDirectoryChanges::bufsize = 1024*1024; | ||
| 365 | |||
| 366 | This variable is the buffer for the directory changes that get read from | ||
| 367 | Windows. The default size is 65520 bytes. | ||
| 368 | |||
| 369 | =back | ||
| 370 | |||
| 371 | =head1 HELP WANTED | ||
| 372 | |||
| 373 | In theory, this module should also work on Cygwin, but for some reason, it | ||
| 374 | seems that there is memory corruption on Cygwin. If you happen to be handy | ||
| 375 | with a debugger and familiar with Cygwin, your help is appreciated. | ||
| 376 | |||
| 377 | =head1 SEE ALSO | ||
| 378 | |||
| 379 | L<Filesys::Notify::Simple> - simple cross-platform directory watcher | ||
| 380 | |||
| 381 | L<File::ChangeNotify> - complex cross-platform directory watcher | ||
| 382 | |||
| 383 | L<Win32::ChangeNotify> - Win32 directory watcher using the ChangeNotify API | ||
| 384 | |||
| 385 | Currently, no additional information like that available through | ||
| 386 | L<https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesexw|ReadDirectoryChangesExW> | ||
| 387 | is collected. But a wrapper/emulation could provide that information whenever | ||
| 388 | RDCE is unavailable (on Windows versions before Windows 10). | ||
| 389 | |||
| 390 | =head1 REPOSITORY | ||
| 391 | |||
| 392 | The public repository of this module is | ||
| 393 | L<https://github.com/Corion/Filesys-Notify-Win32-ReadDirectoryChanges>. | ||
| 394 | |||
| 395 | =head1 SUPPORT | ||
| 396 | |||
| 397 | The public support forum of this module is | ||
| 398 | L<https://perlmonks.org/>. | ||
| 399 | |||
| 400 | =head1 AUTHOR | ||
| 401 | |||
| 402 | Max Maischein C<corion@cpan.org> | ||
| 403 | |||
| 404 | =head1 COPYRIGHT (c) | ||
| 405 | |||
| 406 | Copyright 2022 by Max Maischein C<corion@cpan.org>. | ||
| 407 | |||
| 408 | =head1 LICENSE | ||
| 409 | |||
| 410 | This module is released under the same terms as Perl itself. | ||
| 411 | |||
| 412 | =cut |