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