server: Add an open_file() function to the object operations.
[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     struct event  *event;
151     unsigned int   filter;   /* notification filter */
152     int            notified; /* SIGIO counter */
153     int            want_data; /* return change data */
154     long           signaled; /* the file changed */
155     int            subtree;  /* do we want to watch subdirectories? */
156     struct list    change_q; /* change readers */
157     struct list    change_records;   /* data for the change */
158     struct list    in_entry; /* entry in the inode dirs list */
159     struct inode  *inode;    /* inode of the associated directory */
160 };
161
162 static struct fd *dir_get_fd( struct object *obj );
163 static unsigned int dir_map_access( struct object *obj, unsigned int access );
164 static void dir_dump( struct object *obj, int verbose );
165 static void dir_destroy( struct object *obj );
166 static int dir_signaled( struct object *obj, struct thread *thread );
167
168 static const struct object_ops dir_ops =
169 {
170     sizeof(struct dir),       /* size */
171     dir_dump,                 /* dump */
172     add_queue,                /* add_queue */
173     remove_queue,             /* remove_queue */
174     dir_signaled,             /* signaled */
175     no_satisfied,             /* satisfied */
176     no_signal,                /* signal */
177     dir_get_fd,               /* get_fd */
178     dir_map_access,           /* map_access */
179     no_lookup_name,           /* lookup_name */
180     no_open_file,             /* open_file */
181     fd_close_handle,          /* close_handle */
182     dir_destroy               /* destroy */
183 };
184
185 static int dir_get_poll_events( struct fd *fd );
186 static enum server_fd_type dir_get_info( struct fd *fd, int *flags );
187 static void dir_cancel_async( struct fd *fd );
188
189 static const struct fd_ops dir_fd_ops =
190 {
191     dir_get_poll_events,      /* get_poll_events */
192     default_poll_event,       /* poll_event */
193     no_flush,                 /* flush */
194     dir_get_info,             /* get_file_info */
195     default_fd_queue_async,   /* queue_async */
196     dir_cancel_async          /* cancel_async */
197 };
198
199 static struct list change_list = LIST_INIT(change_list);
200
201 static void dnotify_adjust_changes( struct dir *dir )
202 {
203 #if defined(F_SETSIG) && defined(F_NOTIFY)
204     int fd = get_unix_fd( dir->fd );
205     unsigned int filter = dir->filter;
206     unsigned int val;
207     if ( 0 > fcntl( fd, F_SETSIG, SIGIO) )
208         return;
209
210     val = DN_MULTISHOT;
211     if (filter & FILE_NOTIFY_CHANGE_FILE_NAME)
212         val |= DN_RENAME | DN_DELETE | DN_CREATE;
213     if (filter & FILE_NOTIFY_CHANGE_DIR_NAME)
214         val |= DN_RENAME | DN_DELETE | DN_CREATE;
215     if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
216         val |= DN_ATTRIB;
217     if (filter & FILE_NOTIFY_CHANGE_SIZE)
218         val |= DN_MODIFY;
219     if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
220         val |= DN_MODIFY;
221     if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
222         val |= DN_ACCESS;
223     if (filter & FILE_NOTIFY_CHANGE_CREATION)
224         val |= DN_CREATE;
225     if (filter & FILE_NOTIFY_CHANGE_SECURITY)
226         val |= DN_ATTRIB;
227     fcntl( fd, F_NOTIFY, val );
228 #endif
229 }
230
231 /* insert change in the global list */
232 static inline void insert_change( struct dir *dir )
233 {
234     sigset_t sigset;
235
236     sigemptyset( &sigset );
237     sigaddset( &sigset, SIGIO );
238     sigprocmask( SIG_BLOCK, &sigset, NULL );
239     list_add_head( &change_list, &dir->entry );
240     sigprocmask( SIG_UNBLOCK, &sigset, NULL );
241 }
242
243 /* remove change from the global list */
244 static inline void remove_change( struct dir *dir )
245 {
246     sigset_t sigset;
247
248     sigemptyset( &sigset );
249     sigaddset( &sigset, SIGIO );
250     sigprocmask( SIG_BLOCK, &sigset, NULL );
251     list_remove( &dir->entry );
252     sigprocmask( SIG_UNBLOCK, &sigset, NULL );
253 }
254
255 static void dir_dump( struct object *obj, int verbose )
256 {
257     struct dir *dir = (struct dir *)obj;
258     assert( obj->ops == &dir_ops );
259     fprintf( stderr, "Dirfile fd=%p event=%p filter=%08x\n",
260              dir->fd, dir->event, dir->filter );
261 }
262
263 static int dir_signaled( struct object *obj, struct thread *thread )
264 {
265     struct dir *dir = (struct dir *)obj;
266     assert (obj->ops == &dir_ops);
267     return (dir->event == NULL) && dir->signaled;
268 }
269
270 /* enter here directly from SIGIO signal handler */
271 void do_change_notify( int unix_fd )
272 {
273     struct dir *dir;
274
275     /* FIXME: this is O(n) ... probably can be improved */
276     LIST_FOR_EACH_ENTRY( dir, &change_list, struct dir, entry )
277     {
278         if (get_unix_fd( dir->fd ) != unix_fd) continue;
279         interlocked_xchg_add( &dir->notified, 1 );
280         break;
281     }
282 }
283
284 static void dir_signal_changed( struct dir *dir )
285 {
286     if (!dir->event) wake_up( &dir->obj, 0 );
287 }
288
289 /* SIGIO callback, called synchronously with the poll loop */
290 void sigio_callback(void)
291 {
292     struct dir *dir;
293
294     LIST_FOR_EACH_ENTRY( dir, &change_list, struct dir, entry )
295     {
296         long count = interlocked_xchg( &dir->notified, 0 );
297         if (count)
298         {
299             dir->signaled += count;
300             if (dir->signaled == count)  /* was it 0? */
301                 dir_signal_changed( dir );
302         }
303     }
304 }
305
306 static struct fd *dir_get_fd( struct object *obj )
307 {
308     struct dir *dir = (struct dir *)obj;
309     assert( obj->ops == &dir_ops );
310     return (struct fd *)grab_object( dir->fd );
311 }
312
313 static unsigned int dir_map_access( struct object *obj, unsigned int access )
314 {
315     if (access & GENERIC_READ)    access |= FILE_GENERIC_READ;
316     if (access & GENERIC_WRITE)   access |= FILE_GENERIC_WRITE;
317     if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
318     if (access & GENERIC_ALL)     access |= FILE_ALL_ACCESS;
319     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
320 }
321
322 static struct change_record *get_first_change_record( struct dir *dir )
323 {
324     struct list *ptr = list_head( &dir->change_records );
325     if (!ptr) return NULL;
326     list_remove( ptr );
327     return LIST_ENTRY( ptr, struct change_record, entry );
328 }
329
330 static void dir_destroy( struct object *obj )
331 {
332     struct change_record *record;
333     struct dir *dir = (struct dir *)obj;
334     assert (obj->ops == &dir_ops);
335
336     if (dir->filter)
337         remove_change( dir );
338
339     if (dir->inode)
340     {
341         list_remove( &dir->in_entry );
342         free_inode( dir->inode );
343     }
344
345     async_terminate_queue( &dir->change_q, STATUS_CANCELLED );
346     while ((record = get_first_change_record( dir ))) free( record );
347
348     if (dir->event) release_object( dir->event );
349     release_object( dir->fd );
350
351     if (inotify_fd && list_empty( &change_list ))
352     {
353         release_object( inotify_fd );
354         inotify_fd = NULL;
355     }
356 }
357
358 static struct dir *
359 get_dir_obj( struct process *process, obj_handle_t handle, unsigned int access )
360 {
361     return (struct dir *)get_handle_obj( process, handle, access, &dir_ops );
362 }
363
364 static int dir_get_poll_events( struct fd *fd )
365 {
366     return 0;
367 }
368
369 static enum server_fd_type dir_get_info( struct fd *fd, int *flags )
370 {
371     *flags = 0;
372     return FD_TYPE_DIR;
373 }
374
375 static void dir_cancel_async( struct fd *fd )
376 {
377     struct dir *dir = (struct dir *) get_fd_user( fd );
378     async_terminate_queue( &dir->change_q, STATUS_CANCELLED );
379 }
380
381
382 #ifdef USE_INOTIFY
383
384 #define HASH_SIZE 31
385
386 struct inode {
387     struct list ch_entry;    /* entry in the children list */
388     struct list children;    /* children of this inode */
389     struct inode *parent;    /* parent of this inode */
390     struct list dirs;        /* directory handles watching this inode */
391     struct list ino_entry;   /* entry in the inode hash */
392     struct list wd_entry;    /* entry in the watch descriptor hash */
393     dev_t dev;               /* device number */
394     ino_t ino;               /* device's inode number */
395     int wd;                  /* inotify's watch descriptor */
396     char *name;              /* basename name of the inode */
397 };
398
399 struct list inode_hash[ HASH_SIZE ];
400 struct list wd_hash[ HASH_SIZE ];
401
402 static int inotify_add_dir( char *path, unsigned int filter );
403
404 static struct inode *inode_from_wd( int wd )
405 {
406     struct list *bucket = &wd_hash[ wd % HASH_SIZE ];
407     struct inode *inode;
408
409     LIST_FOR_EACH_ENTRY( inode, bucket, struct inode, wd_entry )
410         if (inode->wd == wd)
411             return inode;
412
413     return NULL;
414 }
415
416 static inline struct list *get_hash_list( dev_t dev, ino_t ino )
417 {
418     return &inode_hash[ (ino ^ dev) % HASH_SIZE ];
419 }
420
421 static struct inode *find_inode( dev_t dev, ino_t ino )
422 {
423     struct list *bucket = get_hash_list( dev, ino );
424     struct inode *inode;
425
426     LIST_FOR_EACH_ENTRY( inode, bucket, struct inode, ino_entry )
427         if (inode->ino == ino && inode->dev == dev)
428              return inode;
429
430     return NULL;
431 }
432
433 static struct inode *create_inode( dev_t dev, ino_t ino )
434 {
435     struct inode *inode;
436
437     inode = malloc( sizeof *inode );
438     if (inode)
439     {
440         list_init( &inode->children );
441         list_init( &inode->dirs );
442         inode->ino = ino;
443         inode->dev = dev;
444         inode->wd = -1;
445         inode->parent = NULL;
446         inode->name = NULL;
447         list_add_tail( get_hash_list( dev, ino ), &inode->ino_entry );
448     }
449     return inode;
450 }
451
452 static struct inode *get_inode( dev_t dev, ino_t ino )
453 {
454     struct inode *inode;
455
456     inode = find_inode( dev, ino );
457     if (inode)
458         return inode;
459     return create_inode( dev, ino );
460 }
461
462 static void inode_set_wd( struct inode *inode, int wd )
463 {
464     if (inode->wd != -1)
465         list_remove( &inode->wd_entry );
466     inode->wd = wd;
467     list_add_tail( &wd_hash[ wd % HASH_SIZE ], &inode->wd_entry );
468 }
469
470 static void inode_set_name( struct inode *inode, const char *name )
471 {
472     free (inode->name);
473     inode->name = name ? strdup( name ) : NULL;
474 }
475
476 static void free_inode( struct inode *inode )
477 {
478     int subtree = 0, watches = 0;
479     struct dir *dir;
480
481     LIST_FOR_EACH_ENTRY( dir, &inode->dirs, struct dir, in_entry )
482     {
483         subtree |= dir->subtree;
484         watches++;
485     }
486
487     if (!subtree && !inode->parent)
488     {
489         struct inode *tmp, *next;
490         LIST_FOR_EACH_ENTRY_SAFE( tmp, next, &inode->children,
491                                   struct inode, ch_entry )
492         {
493             assert( tmp != inode );
494             assert( tmp->parent == inode );
495             free_inode( tmp );
496         }
497     }
498
499     if (watches)
500         return;
501
502     if (inode->parent)
503         list_remove( &inode->ch_entry );
504
505     if (inode->wd != -1)
506     {
507         inotify_remove_watch( get_unix_fd( inotify_fd ), inode->wd );
508         list_remove( &inode->wd_entry );
509     }
510     list_remove( &inode->ino_entry );
511
512     free( inode->name );
513     free( inode );
514 }
515
516 static struct inode *inode_add( struct inode *parent,
517                                 dev_t dev, ino_t ino, const char *name )
518 {
519     struct inode *inode;
520  
521     inode = get_inode( dev, ino );
522     if (!inode)
523         return NULL;
524  
525     if (!inode->parent)
526     {
527         list_add_tail( &parent->children, &inode->ch_entry );
528         inode->parent = parent;
529         assert( inode != parent );
530     }
531     inode_set_name( inode, name );
532
533     return inode;
534 }
535
536 static struct inode *inode_from_name( struct inode *inode, const char *name )
537 {
538     struct inode *i;
539
540     LIST_FOR_EACH_ENTRY( i, &inode->children, struct inode, ch_entry )
541         if (i->name && !strcmp( i->name, name ))
542             return i;
543     return NULL;
544 }
545
546 static int inotify_get_poll_events( struct fd *fd );
547 static void inotify_poll_event( struct fd *fd, int event );
548
549 static const struct fd_ops inotify_fd_ops =
550 {
551     inotify_get_poll_events,  /* get_poll_events */
552     inotify_poll_event,       /* poll_event */
553     no_flush,                 /* flush */
554     no_get_file_info,         /* get_file_info */
555     default_fd_queue_async,   /* queue_async */
556     default_fd_cancel_async,  /* cancel_async */
557 };
558
559 static int inotify_get_poll_events( struct fd *fd )
560 {
561     return POLLIN;
562 }
563
564 static void inotify_do_change_notify( struct dir *dir, unsigned int action,
565                                       const char *relpath )
566 {
567     struct change_record *record;
568
569     assert( dir->obj.ops == &dir_ops );
570
571     if (dir->want_data)
572     {
573         size_t len = strlen(relpath);
574         record = malloc( offsetof(struct change_record, name[len]) );
575         if (!record)
576             return;
577
578         record->action = action;
579         memcpy( record->name, relpath, len );
580         record->len = len;
581
582         list_add_tail( &dir->change_records, &record->entry );
583     }
584
585     if (!list_empty( &dir->change_q ))
586         async_terminate_head( &dir->change_q, STATUS_ALERTED );
587 }
588
589 static unsigned int filter_from_event( struct inotify_event *ie )
590 {
591     unsigned int filter = 0;
592
593     if (ie->mask & (IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE | IN_CREATE))
594         filter |= FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
595     if (ie->mask & IN_MODIFY)
596         filter |= FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE;
597     if (ie->mask & IN_ATTRIB)
598         filter |= FILE_NOTIFY_CHANGE_ATTRIBUTES | FILE_NOTIFY_CHANGE_SECURITY;
599     if (ie->mask & IN_ACCESS)
600         filter |= FILE_NOTIFY_CHANGE_LAST_ACCESS;
601     if (ie->mask & IN_CREATE)
602         filter |= FILE_NOTIFY_CHANGE_CREATION;
603
604     return filter;
605 }
606
607 /* scan up the parent directories for watches */
608 static unsigned int filter_from_inode( struct inode *inode, int is_parent )
609 {
610     unsigned int filter = 0;
611     struct dir *dir;
612
613     /* combine filters from parents watching subtrees */
614     while (inode)
615     {
616         LIST_FOR_EACH_ENTRY( dir, &inode->dirs, struct dir, in_entry )
617             if (dir->subtree || !is_parent)
618                 filter |= dir->filter;
619         is_parent = 1;
620         inode = inode->parent;
621     }
622
623     return filter;
624 }
625
626 static char *inode_get_path( struct inode *inode, int sz )
627 {
628     struct list *head;
629     char *path;
630     int len;
631
632     if (!inode)
633         return NULL;
634
635     head = list_head( &inode->dirs );
636     if (head)
637     {
638         int unix_fd = get_unix_fd( LIST_ENTRY( head, struct dir, in_entry )->fd );
639         path = malloc ( 32 + sz );
640         if (path)
641             sprintf( path, "/proc/self/fd/%u/", unix_fd );
642         return path;
643     }
644
645     if (!inode->name)
646         return NULL;
647
648     len = strlen( inode->name );
649     path = inode_get_path( inode->parent, sz + len + 1 );
650     if (!path)
651         return NULL;
652     
653     strcat( path, inode->name );
654     strcat( path, "/" );
655
656     return path;
657 }
658
659 static int inode_check_dir( struct inode *parent, const char *name )
660 {
661     char *path;
662     unsigned int filter;
663     struct inode *inode;
664     struct stat st;
665     int wd = -1, r = -1;
666
667     path = inode_get_path( parent, strlen(name) );
668     if (!path)
669         return r;
670
671     strcat( path, name );
672
673     r = stat( path, &st );
674     if (r < 0) goto end;
675
676     if (!S_ISDIR(st.st_mode))
677     {
678         r = 0;
679         goto end;
680     }
681
682     r = 1;
683
684     filter = filter_from_inode( parent, 1 );
685     if (!filter)
686         goto end;
687
688     inode = inode_add( parent, st.st_dev, st.st_ino, name );
689     if (!inode || inode->wd != -1)
690         goto end;
691
692     wd = inotify_add_dir( path, filter );
693     if (wd != -1)
694         inode_set_wd( inode, wd );
695     else
696         free_inode( inode );
697
698 end:
699     free( path );
700     return r;
701 }
702
703 static int prepend( char **path, const char *segment )
704 {
705     int extra;
706     char *p;
707
708     extra = strlen( segment ) + 1;
709     if (*path)
710     {
711         int len = strlen( *path ) + 1;
712         p = realloc( *path, len + extra );
713         if (!p) return 0;
714         memmove( &p[ extra ], p, len );
715         p[ extra - 1 ] = '/';
716         memcpy( p, segment, extra - 1 );
717     }
718     else
719     {
720         p = malloc( extra );
721         if (!p) return 0;
722         memcpy( p, segment, extra );
723     }
724
725     *path = p;
726
727     return 1;
728 }
729
730 static void inotify_notify_all( struct inotify_event *ie )
731 {
732     unsigned int filter, action;
733     struct inode *inode, *i;
734     char *path = NULL;
735     struct dir *dir;
736
737     inode = inode_from_wd( ie->wd );
738     if (!inode)
739     {
740         fprintf( stderr, "no inode matches %d\n", ie->wd);
741         return;
742     }
743
744     filter = filter_from_event( ie );
745     
746     if (ie->mask & IN_CREATE)
747     {
748         switch (inode_check_dir( inode, ie->name ))
749         {
750         case 1:
751             filter &= ~FILE_NOTIFY_CHANGE_FILE_NAME;
752             break;
753         case 0:
754             filter &= ~FILE_NOTIFY_CHANGE_DIR_NAME;
755             break;
756         default:
757             break;
758             /* Maybe the file disappeared before we could check it? */
759         }
760         action = FILE_ACTION_ADDED;
761     }
762     else if (ie->mask & IN_DELETE)
763         action = FILE_ACTION_REMOVED;
764     else
765         action = FILE_ACTION_MODIFIED;
766
767     /*
768      * Work our way up the inode hierarchy
769      *  extending the relative path as we go
770      *  and notifying all recursive watches.
771      */
772     if (!prepend( &path, ie->name ))
773         return;
774
775     for (i = inode; i; i = i->parent)
776     {
777         LIST_FOR_EACH_ENTRY( dir, &i->dirs, struct dir, in_entry )
778             if ((filter & dir->filter) && (i==inode || dir->subtree))
779                 inotify_do_change_notify( dir, action, path );
780
781         if (!i->name || !prepend( &path, i->name ))
782             break;
783     }
784
785     free( path );
786
787     if (ie->mask & IN_DELETE)
788     {
789         i = inode_from_name( inode, ie->name );
790         if (i)
791             free_inode( i );
792     }
793 }
794
795 static void inotify_poll_event( struct fd *fd, int event )
796 {
797     int r, ofs, unix_fd;
798     char buffer[0x1000];
799     struct inotify_event *ie;
800
801     unix_fd = get_unix_fd( fd );
802     r = read( unix_fd, buffer, sizeof buffer );
803     if (r < 0)
804     {
805         fprintf(stderr,"inotify_poll_event(): inotify read failed!\n");
806         return;
807     }
808
809     for( ofs = 0; ofs < r - offsetof(struct inotify_event, name); )
810     {
811         ie = (struct inotify_event*) &buffer[ofs];
812         if (!ie->len)
813             break;
814         ofs += offsetof( struct inotify_event, name[ie->len] );
815         if (ofs > r) break;
816         inotify_notify_all( ie );
817     }
818 }
819
820 static inline struct fd *create_inotify_fd( void )
821 {
822     int unix_fd;
823
824     unix_fd = inotify_init();
825     if (unix_fd<0)
826         return NULL;
827     return create_anonymous_fd( &inotify_fd_ops, unix_fd, NULL );
828 }
829
830 static int map_flags( unsigned int filter )
831 {
832     unsigned int mask;
833
834     /* always watch these so we can track subdirectories in recursive watches */
835     mask = (IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF);
836
837     if (filter & FILE_NOTIFY_CHANGE_ATTRIBUTES)
838         mask |= IN_ATTRIB;
839     if (filter & FILE_NOTIFY_CHANGE_SIZE)
840         mask |= IN_MODIFY;
841     if (filter & FILE_NOTIFY_CHANGE_LAST_WRITE)
842         mask |= IN_MODIFY;
843     if (filter & FILE_NOTIFY_CHANGE_LAST_ACCESS)
844         mask |= IN_ACCESS;
845     if (filter & FILE_NOTIFY_CHANGE_SECURITY)
846         mask |= IN_ATTRIB;
847
848     return mask;
849 }
850
851 static int inotify_add_dir( char *path, unsigned int filter )
852 {
853     int wd = inotify_add_watch( get_unix_fd( inotify_fd ),
854                                 path, map_flags( filter ) );
855     if (wd != -1)
856         set_fd_events( inotify_fd, POLLIN );
857     return wd;
858 }
859
860 static int init_inotify( void )
861 {
862     int i;
863
864     if (inotify_fd)
865         return 1;
866
867     inotify_fd = create_inotify_fd();
868     if (!inotify_fd)
869         return 0;
870
871     for (i=0; i<HASH_SIZE; i++)
872     {
873         list_init( &inode_hash[i] );
874         list_init( &wd_hash[i] );
875     }
876
877     return 1;
878 }
879
880 static int inotify_adjust_changes( struct dir *dir )
881 {
882     unsigned int filter;
883     struct inode *inode;
884     struct stat st;
885     char path[32];
886     int wd, unix_fd;
887
888     if (!inotify_fd)
889         return 0;
890
891     unix_fd = get_unix_fd( dir->fd );
892
893     inode = dir->inode;
894     if (!inode)
895     {
896         /* check if this fd is already being watched */
897         if (-1 == fstat( unix_fd, &st ))
898             return 0;
899
900         inode = get_inode( st.st_dev, st.st_ino );
901         if (!inode)
902             inode = create_inode( st.st_dev, st.st_ino );
903         if (!inode)
904             return 0;
905         list_add_tail( &inode->dirs, &dir->in_entry );
906         dir->inode = inode;
907     }
908
909     filter = filter_from_inode( inode, 0 );
910
911     sprintf( path, "/proc/self/fd/%u", unix_fd );
912     wd = inotify_add_dir( path, filter );
913     if (wd == -1) return 0;
914
915     inode_set_wd( inode, wd );
916
917     return 1;
918 }
919
920 static char *get_basename( const char *link )
921 {
922     char *buffer, *name = NULL;
923     int r, n = 0x100;
924
925     while (1)
926     {
927         buffer = malloc( n );
928         if (!buffer) return NULL;
929
930         r = readlink( link, buffer, n );
931         if (r < 0)
932             break;
933
934         if (r < n)
935         {
936             name = buffer;
937             break;
938         }
939         free( buffer );
940         n *= 2;
941     }
942
943     if (name)
944     {
945         while (r > 0 && name[ r - 1 ] == '/' )
946             r--;
947         name[ r ] = 0;
948
949         name = strrchr( name, '/' );
950         if (name)
951             name = strdup( &name[1] );
952     }
953
954     free( buffer );
955     return name;
956 }
957
958 static int dir_add_to_existing_notify( struct dir *dir )
959 {
960     struct inode *inode, *parent;
961     unsigned int filter = 0;
962     struct stat st, st_new;
963     char link[35], *name;
964     int wd, unix_fd;
965
966     if (!inotify_fd)
967         return 0;
968
969     unix_fd = get_unix_fd( dir->fd );
970
971     /* check if it's in the list of inodes we want to watch */
972     if (-1 == fstat( unix_fd, &st_new ))
973         return 0;
974     inode = find_inode( st_new.st_dev, st_new.st_ino );
975     if (inode)
976         return 0;
977
978     /* lookup the parent */
979     sprintf( link, "/proc/self/fd/%u/..", unix_fd );
980     if (-1 == stat( link, &st ))
981         return 0;
982
983     /*
984      * If there's no parent, stop.  We could keep going adding
985      *  ../ to the path until we hit the root of the tree or
986      *  find a recursively watched ancestor.
987      * Assume it's too expensive to search up the tree for now.
988      */
989     parent = find_inode( st.st_dev, st.st_ino );
990     if (!parent)
991         return 0;
992
993     if (parent->wd == -1)
994         return 0;
995
996     filter = filter_from_inode( parent, 1 );
997     if (!filter)
998         return 0;
999
1000     sprintf( link, "/proc/self/fd/%u", unix_fd );
1001     name = get_basename( link );
1002     if (!name)
1003         return 0;
1004     inode = inode_add( parent, st_new.st_dev, st_new.st_ino, name );
1005     free( name );
1006     if (!inode)
1007         return 0;
1008
1009     /* Couldn't find this inode at the start of the function, must be new */
1010     assert( inode->wd == -1 );
1011
1012     wd = inotify_add_dir( link, filter );
1013     if (wd != -1)
1014         inode_set_wd( inode, wd );
1015
1016     return 1;
1017 }
1018
1019 #else
1020
1021 static int init_inotify( void )
1022 {
1023     return 0;
1024 }
1025
1026 static int inotify_adjust_changes( struct dir *dir )
1027 {
1028     return 0;
1029 }
1030
1031 static void free_inode( struct inode *inode )
1032 {
1033     assert( 0 );
1034 }
1035
1036 static int dir_add_to_existing_notify( struct dir *dir )
1037 {
1038     return 0;
1039 }
1040
1041 #endif  /* USE_INOTIFY */
1042
1043 struct object *create_dir_obj( struct fd *fd )
1044 {
1045     struct dir *dir;
1046
1047     dir = alloc_object( &dir_ops );
1048     if (!dir)
1049         return NULL;
1050
1051     list_init( &dir->change_q );
1052     list_init( &dir->change_records );
1053     dir->event = NULL;
1054     dir->filter = 0;
1055     dir->notified = 0;
1056     dir->signaled = 0;
1057     dir->want_data = 0;
1058     dir->inode = NULL;
1059     grab_object( fd );
1060     dir->fd = fd;
1061     set_fd_user( fd, &dir_fd_ops, &dir->obj );
1062
1063     dir_add_to_existing_notify( dir );
1064
1065     return &dir->obj;
1066 }
1067
1068 /* enable change notifications for a directory */
1069 DECL_HANDLER(read_directory_changes)
1070 {
1071     struct event *event = NULL;
1072     struct dir *dir;
1073
1074     if (!req->filter)
1075     {
1076         set_error(STATUS_INVALID_PARAMETER);
1077         return;
1078     }
1079
1080     dir = get_dir_obj( current->process, req->handle, 0 );
1081     if (!dir)
1082         return;
1083
1084     /* possibly send changes through an event flag */
1085     if (req->async.event &&
1086         !(event = get_event_obj( current->process, req->async.event, EVENT_MODIFY_STATE )))
1087         goto end;
1088
1089     /* discard the current data, and move onto the next event */
1090     if (dir->event) release_object( dir->event );
1091     dir->event = event;
1092
1093     /* requests don't timeout */
1094     if (!create_async( current, NULL, &dir->change_q, &req->async )) goto end;
1095
1096     /* assign it once */
1097     if (!dir->filter)
1098     {
1099         init_inotify();
1100         insert_change( dir );
1101         dir->filter = req->filter;
1102         dir->subtree = req->subtree;
1103         dir->want_data = req->want_data;
1104     }
1105
1106     /* remove any notifications */
1107     if (dir->signaled>0)
1108         dir->signaled--;
1109
1110     /* if there's already a change in the queue, send it */
1111     if (!list_empty( &dir->change_q ) &&
1112         !list_empty( &dir->change_records ))
1113         async_terminate_head( &dir->change_q, STATUS_ALERTED );
1114
1115     /* setup the real notification */
1116     if (!inotify_adjust_changes( dir ))
1117         dnotify_adjust_changes( dir );
1118
1119     set_error(STATUS_PENDING);
1120
1121 end:
1122     release_object( dir );
1123 }
1124
1125 DECL_HANDLER(read_change)
1126 {
1127     struct change_record *record;
1128     struct dir *dir;
1129
1130     dir = get_dir_obj( current->process, req->handle, 0 );
1131     if (!dir)
1132         return;
1133
1134     if ((record = get_first_change_record( dir )) != NULL)
1135     {
1136         reply->action = record->action;
1137         set_reply_data( record->name, record->len );
1138         free( record );
1139     }
1140     else
1141         set_error( STATUS_NO_DATA_DETECTED );
1142
1143     /* now signal it */
1144     dir->signaled++;
1145     dir_signal_changed( dir );
1146
1147     release_object( dir );
1148 }