shell32: Constify some variables.
[wine] / server / change.c
1 /*
2  * Server-side change notification management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  * Copyright (C) 2006 Mike McCormack
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <fcntl.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <signal.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <limits.h>
33 #include <dirent.h>
34 #include <errno.h>
35 #ifdef HAVE_SYS_ERRNO_H
36 #include <sys/errno.h>
37 #endif
38
39 #include "ntstatus.h"
40 #define WIN32_NO_STATUS
41 #include "windef.h"
42
43 #include "file.h"
44 #include "handle.h"
45 #include "thread.h"
46 #include "request.h"
47 #include "winternl.h"
48
49 /* dnotify support */
50
51 #ifdef linux
52 #ifndef F_NOTIFY
53 #define F_NOTIFY 1026
54 #define DN_ACCESS       0x00000001      /* File accessed */
55 #define DN_MODIFY       0x00000002      /* File modified */
56 #define DN_CREATE       0x00000004      /* File created */
57 #define DN_DELETE       0x00000008      /* File removed */
58 #define DN_RENAME       0x00000010      /* File renamed */
59 #define DN_ATTRIB       0x00000020      /* File changed attibutes */
60 #define DN_MULTISHOT    0x80000000      /* Don't remove notifier */
61 #endif
62 #endif
63
64 /* inotify support */
65
66 #if defined(__linux__) && defined(__i386__)
67
68 #define SYS_inotify_init        291
69 #define SYS_inotify_add_watch   292
70 #define SYS_inotify_rm_watch    293
71
72 struct inotify_event {
73     int           wd;
74     unsigned int  mask;
75     unsigned int  cookie;
76     unsigned int  len;
77     char          name[1];
78 };
79
80 #define IN_ACCESS        0x00000001
81 #define IN_MODIFY        0x00000002
82 #define IN_ATTRIB        0x00000004
83 #define IN_CLOSE_WRITE   0x00000008
84 #define IN_CLOSE_NOWRITE 0x00000010
85 #define IN_OPEN          0x00000020
86 #define IN_MOVED_FROM    0x00000040
87 #define IN_MOVED_TO      0x00000080
88 #define IN_CREATE        0x00000100
89 #define IN_DELETE        0x00000200
90 #define IN_DELETE_SELF   0x00000400
91
92 static inline int inotify_init( void )
93 {
94     int ret;
95     __asm__ __volatile__( "int $0x80"
96                           : "=a" (ret)
97                           : "0" (SYS_inotify_init));
98     if (ret<0) { errno = -ret; ret = -1; }
99     return ret;
100 }
101
102 static inline int inotify_add_watch( int fd, const char *name, unsigned int mask )
103 {
104     int ret;
105     __asm__ __volatile__( "pushl %%ebx;\n\t"
106                           "movl %2,%%ebx;\n\t"
107                           "int $0x80;\n\t"
108                           "popl %%ebx"
109                           : "=a" (ret) : "0" (SYS_inotify_add_watch),
110                             "r" (fd), "c" (name), "d" (mask) );
111     if (ret<0) { errno = -ret; ret = -1; }
112     return ret;
113 }
114
115 static inline int inotify_remove_watch( int fd, int wd )
116 {
117     int ret;
118     __asm__ __volatile__( "pushl %%ebx;\n\t"
119                           "movl %2,%%ebx;\n\t"
120                           "int $0x80;\n\t"
121                           "popl %%ebx"
122                           : "=a" (ret) : "0" (SYS_inotify_rm_watch),
123                             "r" (fd), "c" (wd) );
124     if (ret<0) { errno = -ret; ret = -1; }
125     return ret;
126 }
127
128 #define USE_INOTIFY
129
130 #endif
131
132 struct inode;
133
134 static void free_inode( struct inode *inode );
135
136 static struct fd *inotify_fd;
137
138 struct change_record {
139     struct list entry;
140     int action;
141     int len;
142     char name[1];
143 };
144
145 struct dir
146 {
147     struct object  obj;      /* object header */
148     struct fd     *fd;       /* file descriptor to the directory */
149     struct list    entry;    /* entry in global change notifications list */
150     unsigned int   filter;   /* notification filter */
151     int            notified; /* SIGIO counter */
152     int            want_data; /* return change data */
153     int            subtree;  /* do we want to watch subdirectories? */
154     struct list    change_records;   /* data for the change */
155     struct list    in_entry; /* entry in the inode dirs list */
156     struct inode  *inode;    /* inode of the associated directory */
157 };
158
159 static struct fd *dir_get_fd( struct object *obj );
160 static void dir_dump( struct object *obj, int verbose );
161 static void dir_destroy( struct object *obj );
162
163 static const struct object_ops dir_ops =
164 {
165     sizeof(struct dir),       /* size */
166     dir_dump,                 /* dump */
167     add_queue,                /* add_queue */
168     remove_queue,             /* remove_queue */
169     default_fd_signaled,      /* signaled */
170     no_satisfied,             /* satisfied */
171     no_signal,                /* signal */
172     dir_get_fd,               /* get_fd */
173     default_fd_map_access,    /* map_access */
174     default_get_sd,           /* get_sd */
175     default_set_sd,           /* set_sd */
176     no_lookup_name,           /* lookup_name */
177     no_open_file,             /* open_file */
178     fd_close_handle,          /* close_handle */
179     dir_destroy               /* destroy */
180 };
181
182 static int dir_get_poll_events( struct fd *fd );
183 static enum server_fd_type dir_get_fd_type( struct fd *fd );
184
185 static const struct fd_ops dir_fd_ops =
186 {
187     dir_get_poll_events,         /* get_poll_events */
188     default_poll_event,          /* poll_event */
189     no_flush,                    /* flush */
190     dir_get_fd_type,             /* get_fd_type */
191     default_fd_ioctl,            /* ioctl */
192     default_fd_queue_async,      /* queue_async */
193     default_fd_reselect_async,   /* reselect_async */
194     default_fd_cancel_async      /* cancel_async */
195 };
196
197 static struct list change_list = LIST_INIT(change_list);
198
199 static void dnotify_adjust_changes( struct dir *dir )
200 {
201 #if defined(F_SETSIG) && defined(F_NOTIFY)
202     int fd = get_unix_fd( dir->fd );
203     unsigned int filter = dir->filter;
204     unsigned int val;
205     if ( 0 > fcntl( fd, F_SETSIG, SIGIO) )
206         return;
207
208     val = DN_MULTISHOT;
209     if (filter & FILE_NOTIFY_CHANGE_FILE_NAME)
210         val |= DN_RENAME | DN_DELETE | DN_CREATE;
211     if (filter & FILE_NOTIFY_CHANGE_DIR_NAME)
212         val |= DN_RENAME | DN_DELETE | DN_CREATE;
213     if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
214         val |= DN_ATTRIB;
215     if (filter & FILE_NOTIFY_CHANGE_SIZE)
216         val |= DN_MODIFY;
217     if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
218         val |= DN_MODIFY;
219     if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
220         val |= DN_ACCESS;
221     if (filter & FILE_NOTIFY_CHANGE_CREATION)
222         val |= DN_CREATE;
223     if (filter & FILE_NOTIFY_CHANGE_SECURITY)
224         val |= DN_ATTRIB;
225     fcntl( fd, F_NOTIFY, val );
226 #endif
227 }
228
229 /* insert change in the global list */
230 static inline void insert_change( struct dir *dir )
231 {
232     sigset_t sigset;
233
234     sigemptyset( &sigset );
235     sigaddset( &sigset, SIGIO );
236     sigprocmask( SIG_BLOCK, &sigset, NULL );
237     list_add_head( &change_list, &dir->entry );
238     sigprocmask( SIG_UNBLOCK, &sigset, NULL );
239 }
240
241 /* remove change from the global list */
242 static inline void remove_change( struct dir *dir )
243 {
244     sigset_t sigset;
245
246     sigemptyset( &sigset );
247     sigaddset( &sigset, SIGIO );
248     sigprocmask( SIG_BLOCK, &sigset, NULL );
249     list_remove( &dir->entry );
250     sigprocmask( SIG_UNBLOCK, &sigset, NULL );
251 }
252
253 static void dir_dump( struct object *obj, int verbose )
254 {
255     struct dir *dir = (struct dir *)obj;
256     assert( obj->ops == &dir_ops );
257     fprintf( stderr, "Dirfile fd=%p filter=%08x\n", dir->fd, dir->filter );
258 }
259
260 /* enter here directly from SIGIO signal handler */
261 void do_change_notify( int unix_fd )
262 {
263     struct dir *dir;
264
265     /* FIXME: this is O(n) ... probably can be improved */
266     LIST_FOR_EACH_ENTRY( dir, &change_list, struct dir, entry )
267     {
268         if (get_unix_fd( dir->fd ) != unix_fd) continue;
269         interlocked_xchg_add( &dir->notified, 1 );
270         break;
271     }
272 }
273
274 /* SIGIO callback, called synchronously with the poll loop */
275 void sigio_callback(void)
276 {
277     struct dir *dir;
278
279     LIST_FOR_EACH_ENTRY( dir, &change_list, struct dir, entry )
280     {
281         if (interlocked_xchg( &dir->notified, 0 ))
282             fd_async_wake_up( dir->fd, ASYNC_TYPE_WAIT, STATUS_NOTIFY_ENUM_DIR );
283     }
284 }
285
286 static struct fd *dir_get_fd( struct object *obj )
287 {
288     struct dir *dir = (struct dir *)obj;
289     assert( obj->ops == &dir_ops );
290     return (struct fd *)grab_object( dir->fd );
291 }
292
293 static struct change_record *get_first_change_record( struct dir *dir )
294 {
295     struct list *ptr = list_head( &dir->change_records );
296     if (!ptr) return NULL;
297     list_remove( ptr );
298     return LIST_ENTRY( ptr, struct change_record, entry );
299 }
300
301 static void dir_destroy( struct object *obj )
302 {
303     struct change_record *record;
304     struct dir *dir = (struct dir *)obj;
305     assert (obj->ops == &dir_ops);
306
307     if (dir->filter)
308         remove_change( dir );
309
310     if (dir->inode)
311     {
312         list_remove( &dir->in_entry );
313         free_inode( dir->inode );
314     }
315
316     while ((record = get_first_change_record( dir ))) free( record );
317
318     release_object( dir->fd );
319
320     if (inotify_fd && list_empty( &change_list ))
321     {
322         release_object( inotify_fd );
323         inotify_fd = NULL;
324     }
325 }
326
327 static struct dir *
328 get_dir_obj( struct process *process, obj_handle_t handle, unsigned int access )
329 {
330     return (struct dir *)get_handle_obj( process, handle, access, &dir_ops );
331 }
332
333 static int dir_get_poll_events( struct fd *fd )
334 {
335     return 0;
336 }
337
338 static enum server_fd_type dir_get_fd_type( struct fd *fd )
339 {
340     return FD_TYPE_DIR;
341 }
342
343 #ifdef USE_INOTIFY
344
345 #define HASH_SIZE 31
346
347 struct inode {
348     struct list ch_entry;    /* entry in the children list */
349     struct list children;    /* children of this inode */
350     struct inode *parent;    /* parent of this inode */
351     struct list dirs;        /* directory handles watching this inode */
352     struct list ino_entry;   /* entry in the inode hash */
353     struct list wd_entry;    /* entry in the watch descriptor hash */
354     dev_t dev;               /* device number */
355     ino_t ino;               /* device's inode number */
356     int wd;                  /* inotify's watch descriptor */
357     char *name;              /* basename name of the inode */
358 };
359
360 struct list inode_hash[ HASH_SIZE ];
361 struct list wd_hash[ HASH_SIZE ];
362
363 static int inotify_add_dir( char *path, unsigned int filter );
364
365 static struct inode *inode_from_wd( int wd )
366 {
367     struct list *bucket = &wd_hash[ wd % HASH_SIZE ];
368     struct inode *inode;
369
370     LIST_FOR_EACH_ENTRY( inode, bucket, struct inode, wd_entry )
371         if (inode->wd == wd)
372             return inode;
373
374     return NULL;
375 }
376
377 static inline struct list *get_hash_list( dev_t dev, ino_t ino )
378 {
379     return &inode_hash[ (ino ^ dev) % HASH_SIZE ];
380 }
381
382 static struct inode *find_inode( dev_t dev, ino_t ino )
383 {
384     struct list *bucket = get_hash_list( dev, ino );
385     struct inode *inode;
386
387     LIST_FOR_EACH_ENTRY( inode, bucket, struct inode, ino_entry )
388         if (inode->ino == ino && inode->dev == dev)
389              return inode;
390
391     return NULL;
392 }
393
394 static struct inode *create_inode( dev_t dev, ino_t ino )
395 {
396     struct inode *inode;
397
398     inode = malloc( sizeof *inode );
399     if (inode)
400     {
401         list_init( &inode->children );
402         list_init( &inode->dirs );
403         inode->ino = ino;
404         inode->dev = dev;
405         inode->wd = -1;
406         inode->parent = NULL;
407         inode->name = NULL;
408         list_add_tail( get_hash_list( dev, ino ), &inode->ino_entry );
409     }
410     return inode;
411 }
412
413 static struct inode *get_inode( dev_t dev, ino_t ino )
414 {
415     struct inode *inode;
416
417     inode = find_inode( dev, ino );
418     if (inode)
419         return inode;
420     return create_inode( dev, ino );
421 }
422
423 static void inode_set_wd( struct inode *inode, int wd )
424 {
425     if (inode->wd != -1)
426         list_remove( &inode->wd_entry );
427     inode->wd = wd;
428     list_add_tail( &wd_hash[ wd % HASH_SIZE ], &inode->wd_entry );
429 }
430
431 static void inode_set_name( struct inode *inode, const char *name )
432 {
433     free (inode->name);
434     inode->name = name ? strdup( name ) : NULL;
435 }
436
437 static void free_inode( struct inode *inode )
438 {
439     int subtree = 0, watches = 0;
440     struct dir *dir;
441
442     LIST_FOR_EACH_ENTRY( dir, &inode->dirs, struct dir, in_entry )
443     {
444         subtree |= dir->subtree;
445         watches++;
446     }
447
448     if (!subtree && !inode->parent)
449     {
450         struct inode *tmp, *next;
451         LIST_FOR_EACH_ENTRY_SAFE( tmp, next, &inode->children,
452                                   struct inode, ch_entry )
453         {
454             assert( tmp != inode );
455             assert( tmp->parent == inode );
456             free_inode( tmp );
457         }
458     }
459
460     if (watches)
461         return;
462
463     if (inode->parent)
464         list_remove( &inode->ch_entry );
465
466     if (inode->wd != -1)
467     {
468         inotify_remove_watch( get_unix_fd( inotify_fd ), inode->wd );
469         list_remove( &inode->wd_entry );
470     }
471     list_remove( &inode->ino_entry );
472
473     free( inode->name );
474     free( inode );
475 }
476
477 static struct inode *inode_add( struct inode *parent,
478                                 dev_t dev, ino_t ino, const char *name )
479 {
480     struct inode *inode;
481  
482     inode = get_inode( dev, ino );
483     if (!inode)
484         return NULL;
485  
486     if (!inode->parent)
487     {
488         list_add_tail( &parent->children, &inode->ch_entry );
489         inode->parent = parent;
490         assert( inode != parent );
491     }
492     inode_set_name( inode, name );
493
494     return inode;
495 }
496
497 static struct inode *inode_from_name( struct inode *inode, const char *name )
498 {
499     struct inode *i;
500
501     LIST_FOR_EACH_ENTRY( i, &inode->children, struct inode, ch_entry )
502         if (i->name && !strcmp( i->name, name ))
503             return i;
504     return NULL;
505 }
506
507 static int inotify_get_poll_events( struct fd *fd );
508 static void inotify_poll_event( struct fd *fd, int event );
509
510 static const struct fd_ops inotify_fd_ops =
511 {
512     inotify_get_poll_events,     /* get_poll_events */
513     inotify_poll_event,          /* poll_event */
514     NULL,                        /* flush */
515     NULL,                        /* get_fd_type */
516     NULL,                        /* ioctl */
517     NULL,                        /* queue_async */
518     NULL,                        /* reselect_async */
519     NULL,                        /* cancel_async */
520 };
521
522 static int inotify_get_poll_events( struct fd *fd )
523 {
524     return POLLIN;
525 }
526
527 static void inotify_do_change_notify( struct dir *dir, unsigned int action,
528                                       const char *relpath )
529 {
530     struct change_record *record;
531
532     assert( dir->obj.ops == &dir_ops );
533
534     if (dir->want_data)
535     {
536         size_t len = strlen(relpath);
537         record = malloc( offsetof(struct change_record, name[len]) );
538         if (!record)
539             return;
540
541         record->action = action;
542         memcpy( record->name, relpath, len );
543         record->len = len;
544
545         list_add_tail( &dir->change_records, &record->entry );
546     }
547
548     fd_async_wake_up( dir->fd, ASYNC_TYPE_WAIT, STATUS_ALERTED );
549 }
550
551 static unsigned int filter_from_event( struct inotify_event *ie )
552 {
553     unsigned int filter = 0;
554
555     if (ie->mask & (IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE | IN_CREATE))
556         filter |= FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
557     if (ie->mask & IN_MODIFY)
558         filter |= FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE;
559     if (ie->mask & IN_ATTRIB)
560         filter |= FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY;
561     if (ie->mask & IN_ACCESS)
562         filter |= FILE_NOTIFY_CHANGE_LAST_ACCESS;
563     if (ie->mask & IN_CREATE)
564         filter |= FILE_NOTIFY_CHANGE_CREATION;
565
566     return filter;
567 }
568
569 /* scan up the parent directories for watches */
570 static unsigned int filter_from_inode( struct inode *inode, int is_parent )
571 {
572     unsigned int filter = 0;
573     struct dir *dir;
574
575     /* combine filters from parents watching subtrees */
576     while (inode)
577     {
578         LIST_FOR_EACH_ENTRY( dir, &inode->dirs, struct dir, in_entry )
579             if (dir->subtree || !is_parent)
580                 filter |= dir->filter;
581         is_parent = 1;
582         inode = inode->parent;
583     }
584
585     return filter;
586 }
587
588 static char *inode_get_path( struct inode *inode, int sz )
589 {
590     struct list *head;
591     char *path;
592     int len;
593
594     if (!inode)
595         return NULL;
596
597     head = list_head( &inode->dirs );
598     if (head)
599     {
600         int unix_fd = get_unix_fd( LIST_ENTRY( head, struct dir, in_entry )->fd );
601         path = malloc ( 32 + sz );
602         if (path)
603             sprintf( path, "/proc/self/fd/%u/", unix_fd );
604         return path;
605     }
606
607     if (!inode->name)
608         return NULL;
609
610     len = strlen( inode->name );
611     path = inode_get_path( inode->parent, sz + len + 1 );
612     if (!path)
613         return NULL;
614     
615     strcat( path, inode->name );
616     strcat( path, "/" );
617
618     return path;
619 }
620
621 static int inode_check_dir( struct inode *parent, const char *name )
622 {
623     char *path;
624     unsigned int filter;
625     struct inode *inode;
626     struct stat st;
627     int wd = -1, r = -1;
628
629     path = inode_get_path( parent, strlen(name) );
630     if (!path)
631         return r;
632
633     strcat( path, name );
634
635     r = stat( path, &st );
636     if (r < 0) goto end;
637
638     if (!S_ISDIR(st.st_mode))
639     {
640         r = 0;
641         goto end;
642     }
643
644     r = 1;
645
646     filter = filter_from_inode( parent, 1 );
647     if (!filter)
648         goto end;
649
650     inode = inode_add( parent, st.st_dev, st.st_ino, name );
651     if (!inode || inode->wd != -1)
652         goto end;
653
654     wd = inotify_add_dir( path, filter );
655     if (wd != -1)
656         inode_set_wd( inode, wd );
657     else
658         free_inode( inode );
659
660 end:
661     free( path );
662     return r;
663 }
664
665 static int prepend( char **path, const char *segment )
666 {
667     int extra;
668     char *p;
669
670     extra = strlen( segment ) + 1;
671     if (*path)
672     {
673         int len = strlen( *path ) + 1;
674         p = realloc( *path, len + extra );
675         if (!p) return 0;
676         memmove( &p[ extra ], p, len );
677         p[ extra - 1 ] = '/';
678         memcpy( p, segment, extra - 1 );
679     }
680     else
681     {
682         p = malloc( extra );
683         if (!p) return 0;
684         memcpy( p, segment, extra );
685     }
686
687     *path = p;
688
689     return 1;
690 }
691
692 static void inotify_notify_all( struct inotify_event *ie )
693 {
694     unsigned int filter, action;
695     struct inode *inode, *i;
696     char *path = NULL;
697     struct dir *dir;
698
699     inode = inode_from_wd( ie->wd );
700     if (!inode)
701     {
702         fprintf( stderr, "no inode matches %d\n", ie->wd);
703         return;
704     }
705
706     filter = filter_from_event( ie );
707     
708     if (ie->mask & IN_CREATE)
709     {
710         switch (inode_check_dir( inode, ie->name ))
711         {
712         case 1:
713             filter &= ~FILE_NOTIFY_CHANGE_FILE_NAME;
714             break;
715         case 0:
716             filter &= ~FILE_NOTIFY_CHANGE_DIR_NAME;
717             break;
718         default:
719             break;
720             /* Maybe the file disappeared before we could check it? */
721         }
722         action = FILE_ACTION_ADDED;
723     }
724     else if (ie->mask & IN_DELETE)
725         action = FILE_ACTION_REMOVED;
726     else
727         action = FILE_ACTION_MODIFIED;
728
729     /*
730      * Work our way up the inode hierarchy
731      *  extending the relative path as we go
732      *  and notifying all recursive watches.
733      */
734     if (!prepend( &path, ie->name ))
735         return;
736
737     for (i = inode; i; i = i->parent)
738     {
739         LIST_FOR_EACH_ENTRY( dir, &i->dirs, struct dir, in_entry )
740             if ((filter & dir->filter) && (i==inode || dir->subtree))
741                 inotify_do_change_notify( dir, action, path );
742
743         if (!i->name || !prepend( &path, i->name ))
744             break;
745     }
746
747     free( path );
748
749     if (ie->mask & IN_DELETE)
750     {
751         i = inode_from_name( inode, ie->name );
752         if (i)
753             free_inode( i );
754     }
755 }
756
757 static void inotify_poll_event( struct fd *fd, int event )
758 {
759     int r, ofs, unix_fd;
760     char buffer[0x1000];
761     struct inotify_event *ie;
762
763     unix_fd = get_unix_fd( fd );
764     r = read( unix_fd, buffer, sizeof buffer );
765     if (r < 0)
766     {
767         fprintf(stderr,"inotify_poll_event(): inotify read failed!\n");
768         return;
769     }
770
771     for( ofs = 0; ofs < r - offsetof(struct inotify_event, name); )
772     {
773         ie = (struct inotify_event*) &buffer[ofs];
774         if (!ie->len)
775             break;
776         ofs += offsetof( struct inotify_event, name[ie->len] );
777         if (ofs > r) break;
778         inotify_notify_all( ie );
779     }
780 }
781
782 static inline struct fd *create_inotify_fd( void )
783 {
784     int unix_fd;
785
786     unix_fd = inotify_init();
787     if (unix_fd<0)
788         return NULL;
789     return create_anonymous_fd( &inotify_fd_ops, unix_fd, NULL, 0 );
790 }
791
792 static int map_flags( unsigned int filter )
793 {
794     unsigned int mask;
795
796     /* always watch these so we can track subdirectories in recursive watches */
797     mask = (IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF);
798
799     if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
800         mask |= IN_ATTRIB;
801     if (filter & FILE_NOTIFY_CHANGE_SIZE)
802         mask |= IN_MODIFY;
803     if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
804         mask |= IN_MODIFY;
805     if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
806         mask |= IN_ACCESS;
807     if (filter & FILE_NOTIFY_CHANGE_SECURITY)
808         mask |= IN_ATTRIB;
809
810     return mask;
811 }
812
813 static int inotify_add_dir( char *path, unsigned int filter )
814 {
815     int wd = inotify_add_watch( get_unix_fd( inotify_fd ),
816                                 path, map_flags( filter ) );
817     if (wd != -1)
818         set_fd_events( inotify_fd, POLLIN );
819     return wd;
820 }
821
822 static int init_inotify( void )
823 {
824     int i;
825
826     if (inotify_fd)
827         return 1;
828
829     inotify_fd = create_inotify_fd();
830     if (!inotify_fd)
831         return 0;
832
833     for (i=0; i<HASH_SIZE; i++)
834     {
835         list_init( &inode_hash[i] );
836         list_init( &wd_hash[i] );
837     }
838
839     return 1;
840 }
841
842 static int inotify_adjust_changes( struct dir *dir )
843 {
844     unsigned int filter;
845     struct inode *inode;
846     struct stat st;
847     char path[32];
848     int wd, unix_fd;
849
850     if (!inotify_fd)
851         return 0;
852
853     unix_fd = get_unix_fd( dir->fd );
854
855     inode = dir->inode;
856     if (!inode)
857     {
858         /* check if this fd is already being watched */
859         if (-1 == fstat( unix_fd, &st ))
860             return 0;
861
862         inode = get_inode( st.st_dev, st.st_ino );
863         if (!inode)
864             inode = create_inode( st.st_dev, st.st_ino );
865         if (!inode)
866             return 0;
867         list_add_tail( &inode->dirs, &dir->in_entry );
868         dir->inode = inode;
869     }
870
871     filter = filter_from_inode( inode, 0 );
872
873     sprintf( path, "/proc/self/fd/%u", unix_fd );
874     wd = inotify_add_dir( path, filter );
875     if (wd == -1) return 0;
876
877     inode_set_wd( inode, wd );
878
879     return 1;
880 }
881
882 static char *get_basename( const char *link )
883 {
884     char *buffer, *name = NULL;
885     int r, n = 0x100;
886
887     while (1)
888     {
889         buffer = malloc( n );
890         if (!buffer) return NULL;
891
892         r = readlink( link, buffer, n );
893         if (r < 0)
894             break;
895
896         if (r < n)
897         {
898             name = buffer;
899             break;
900         }
901         free( buffer );
902         n *= 2;
903     }
904
905     if (name)
906     {
907         while (r > 0 && name[ r - 1 ] == '/' )
908             r--;
909         name[ r ] = 0;
910
911         name = strrchr( name, '/' );
912         if (name)
913             name = strdup( &name[1] );
914     }
915
916     free( buffer );
917     return name;
918 }
919
920 static int dir_add_to_existing_notify( struct dir *dir )
921 {
922     struct inode *inode, *parent;
923     unsigned int filter = 0;
924     struct stat st, st_new;
925     char link[35], *name;
926     int wd, unix_fd;
927
928     if (!inotify_fd)
929         return 0;
930
931     unix_fd = get_unix_fd( dir->fd );
932
933     /* check if it's in the list of inodes we want to watch */
934     if (-1 == fstat( unix_fd, &st_new ))
935         return 0;
936     inode = find_inode( st_new.st_dev, st_new.st_ino );
937     if (inode)
938         return 0;
939
940     /* lookup the parent */
941     sprintf( link, "/proc/self/fd/%u/..", unix_fd );
942     if (-1 == stat( link, &st ))
943         return 0;
944
945     /*
946      * If there's no parent, stop.  We could keep going adding
947      *  ../ to the path until we hit the root of the tree or
948      *  find a recursively watched ancestor.
949      * Assume it's too expensive to search up the tree for now.
950      */
951     parent = find_inode( st.st_dev, st.st_ino );
952     if (!parent)
953         return 0;
954
955     if (parent->wd == -1)
956         return 0;
957
958     filter = filter_from_inode( parent, 1 );
959     if (!filter)
960         return 0;
961
962     sprintf( link, "/proc/self/fd/%u", unix_fd );
963     name = get_basename( link );
964     if (!name)
965         return 0;
966     inode = inode_add( parent, st_new.st_dev, st_new.st_ino, name );
967     free( name );
968     if (!inode)
969         return 0;
970
971     /* Couldn't find this inode at the start of the function, must be new */
972     assert( inode->wd == -1 );
973
974     wd = inotify_add_dir( link, filter );
975     if (wd != -1)
976         inode_set_wd( inode, wd );
977
978     return 1;
979 }
980
981 #else
982
983 static int init_inotify( void )
984 {
985     return 0;
986 }
987
988 static int inotify_adjust_changes( struct dir *dir )
989 {
990     return 0;
991 }
992
993 static void free_inode( struct inode *inode )
994 {
995     assert( 0 );
996 }
997
998 static int dir_add_to_existing_notify( struct dir *dir )
999 {
1000     return 0;
1001 }
1002
1003 #endif  /* USE_INOTIFY */
1004
1005 struct object *create_dir_obj( struct fd *fd )
1006 {
1007     struct dir *dir;
1008
1009     dir = alloc_object( &dir_ops );
1010     if (!dir)
1011         return NULL;
1012
1013     list_init( &dir->change_records );
1014     dir->filter = 0;
1015     dir->notified = 0;
1016     dir->want_data = 0;
1017     dir->inode = NULL;
1018     grab_object( fd );
1019     dir->fd = fd;
1020     set_fd_user( fd, &dir_fd_ops, &dir->obj );
1021
1022     dir_add_to_existing_notify( dir );
1023
1024     return &dir->obj;
1025 }
1026
1027 /* enable change notifications for a directory */
1028 DECL_HANDLER(read_directory_changes)
1029 {
1030     struct dir *dir;
1031     struct async *async;
1032
1033     if (!req->filter)
1034     {
1035         set_error(STATUS_INVALID_PARAMETER);
1036         return;
1037     }
1038
1039     dir = get_dir_obj( current->process, req->handle, 0 );
1040     if (!dir)
1041         return;
1042
1043     /* requests don't timeout */
1044     if (!(async = fd_queue_async( dir->fd, &req->async, ASYNC_TYPE_WAIT, 0 ))) goto end;
1045
1046     /* assign it once */
1047     if (!dir->filter)
1048     {
1049         init_inotify();
1050         insert_change( dir );
1051         dir->filter = req->filter;
1052         dir->subtree = req->subtree;
1053         dir->want_data = req->want_data;
1054     }
1055
1056     /* if there's already a change in the queue, send it */
1057     if (!list_empty( &dir->change_records ))
1058         fd_async_wake_up( dir->fd, ASYNC_TYPE_WAIT, STATUS_ALERTED );
1059
1060     /* setup the real notification */
1061     if (!inotify_adjust_changes( dir ))
1062         dnotify_adjust_changes( dir );
1063
1064     release_object( async );
1065     set_error(STATUS_PENDING);
1066
1067 end:
1068     release_object( dir );
1069 }
1070
1071 DECL_HANDLER(read_change)
1072 {
1073     struct change_record *record;
1074     struct dir *dir;
1075
1076     dir = get_dir_obj( current->process, req->handle, 0 );
1077     if (!dir)
1078         return;
1079
1080     if ((record = get_first_change_record( dir )) != NULL)
1081     {
1082         reply->action = record->action;
1083         set_reply_data( record->name, record->len );
1084         free( record );
1085     }
1086     else
1087         set_error( STATUS_NO_DATA_DETECTED );
1088
1089     release_object( dir );
1090 }