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