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