crypt32: Trace a few more items when decoding.
[wine] / server / fd.c
1 /*
2  * Server-side file descriptor management
3  *
4  * Copyright (C) 2000, 2003 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <limits.h>
29 #include <signal.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <string.h>
33 #include <stdlib.h>
34 #ifdef HAVE_POLL_H
35 #include <poll.h>
36 #endif
37 #ifdef HAVE_SYS_POLL_H
38 #include <sys/poll.h>
39 #endif
40 #ifdef HAVE_LINUX_MAJOR_H
41 #include <linux/major.h>
42 #endif
43 #ifdef HAVE_SYS_STATVFS_H
44 #include <sys/statvfs.h>
45 #endif
46 #ifdef HAVE_SYS_VFS_H
47 #include <sys/vfs.h>
48 #endif
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_SYS_MOUNT_H
53 #include <sys/mount.h>
54 #endif
55 #ifdef HAVE_SYS_STATFS_H
56 #include <sys/statfs.h>
57 #endif
58 #ifdef HAVE_SYS_SYSCTL_H
59 #include <sys/sysctl.h>
60 #endif
61 #ifdef HAVE_SYS_EVENT_H
62 #include <sys/event.h>
63 #undef LIST_INIT
64 #undef LIST_ENTRY
65 #endif
66 #ifdef HAVE_STDINT_H
67 #include <stdint.h>
68 #endif
69 #include <sys/stat.h>
70 #include <sys/time.h>
71 #include <sys/types.h>
72 #include <unistd.h>
73
74 #include "ntstatus.h"
75 #define WIN32_NO_STATUS
76 #include "object.h"
77 #include "file.h"
78 #include "handle.h"
79 #include "process.h"
80 #include "request.h"
81
82 #include "winternl.h"
83 #include "winioctl.h"
84
85 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
86 # include <sys/epoll.h>
87 # define USE_EPOLL
88 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
89 # define USE_EPOLL
90 # define EPOLLIN POLLIN
91 # define EPOLLOUT POLLOUT
92 # define EPOLLERR POLLERR
93 # define EPOLLHUP POLLHUP
94 # define EPOLL_CTL_ADD 1
95 # define EPOLL_CTL_DEL 2
96 # define EPOLL_CTL_MOD 3
97
98 typedef union epoll_data
99 {
100   void *ptr;
101   int fd;
102   uint32_t u32;
103   uint64_t u64;
104 } epoll_data_t;
105
106 struct epoll_event
107 {
108   uint32_t events;
109   epoll_data_t data;
110 };
111
112 #define SYSCALL_RET(ret) do { \
113         if (ret < 0) { errno = -ret; ret = -1; } \
114         return ret; \
115     } while(0)
116
117 static inline int epoll_create( int size )
118 {
119     int ret;
120     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
121              : "=a" (ret) : "0" (254 /*NR_epoll_create*/), "r" (size) );
122     SYSCALL_RET(ret);
123 }
124
125 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
126 {
127     int ret;
128     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
129              : "=a" (ret)
130              : "0" (255 /*NR_epoll_ctl*/), "r" (epfd), "c" (op), "d" (fd), "S" (event), "m" (*event) );
131     SYSCALL_RET(ret);
132 }
133
134 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
135 {
136     int ret;
137     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
138              : "=a" (ret)
139              : "0" (256 /*NR_epoll_wait*/), "r" (epfd), "c" (events), "d" (maxevents), "S" (timeout)
140              : "memory" );
141     SYSCALL_RET(ret);
142 }
143 #undef SYSCALL_RET
144
145 #endif /* linux && __i386__ && HAVE_STDINT_H */
146
147
148 /* Because of the stupid Posix locking semantics, we need to keep
149  * track of all file descriptors referencing a given file, and not
150  * close a single one until all the locks are gone (sigh).
151  */
152
153 /* file descriptor object */
154
155 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
156 struct closed_fd
157 {
158     struct list entry;       /* entry in inode closed list */
159     int         unix_fd;     /* the unix file descriptor */
160     char        unlink[1];   /* name to unlink on close (if any) */
161 };
162
163 struct fd
164 {
165     struct object        obj;         /* object header */
166     const struct fd_ops *fd_ops;      /* file descriptor operations */
167     struct inode        *inode;       /* inode that this fd belongs to */
168     struct list          inode_entry; /* entry in inode fd list */
169     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
170     struct object       *user;        /* object using this file descriptor */
171     struct list          locks;       /* list of locks on this fd */
172     unsigned int         access;      /* file access (FILE_READ_DATA etc.) */
173     unsigned int         options;     /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
174     unsigned int         sharing;     /* file sharing mode */
175     int                  unix_fd;     /* unix file descriptor */
176     unsigned int         no_fd_status;/* status to return when unix_fd is -1 */
177     int                  signaled :1; /* is the fd signaled? */
178     int                  fs_locks :1; /* can we use filesystem locks for this fd? */
179     int                  poll_index;  /* index of fd in poll array */
180     struct async_queue  *read_q;      /* async readers of this fd */
181     struct async_queue  *write_q;     /* async writers of this fd */
182     struct async_queue  *wait_q;      /* other async waiters of this fd */
183 };
184
185 static void fd_dump( struct object *obj, int verbose );
186 static void fd_destroy( struct object *obj );
187
188 static const struct object_ops fd_ops =
189 {
190     sizeof(struct fd),        /* size */
191     fd_dump,                  /* dump */
192     no_add_queue,             /* add_queue */
193     NULL,                     /* remove_queue */
194     NULL,                     /* signaled */
195     NULL,                     /* satisfied */
196     no_signal,                /* signal */
197     no_get_fd,                /* get_fd */
198     no_map_access,            /* map_access */
199     no_lookup_name,           /* lookup_name */
200     no_open_file,             /* open_file */
201     no_close_handle,          /* close_handle */
202     fd_destroy                /* destroy */
203 };
204
205 /* device object */
206
207 #define DEVICE_HASH_SIZE 7
208 #define INODE_HASH_SIZE 17
209
210 struct device
211 {
212     struct object       obj;        /* object header */
213     struct list         entry;      /* entry in device hash list */
214     dev_t               dev;        /* device number */
215     int                 removable;  /* removable device? (or -1 if unknown) */
216     struct list         inode_hash[INODE_HASH_SIZE];  /* inodes hash table */
217 };
218
219 static void device_dump( struct object *obj, int verbose );
220 static void device_destroy( struct object *obj );
221
222 static const struct object_ops device_ops =
223 {
224     sizeof(struct device),    /* size */
225     device_dump,              /* dump */
226     no_add_queue,             /* add_queue */
227     NULL,                     /* remove_queue */
228     NULL,                     /* signaled */
229     NULL,                     /* satisfied */
230     no_signal,                /* signal */
231     no_get_fd,                /* get_fd */
232     no_map_access,            /* map_access */
233     no_lookup_name,           /* lookup_name */
234     no_open_file,             /* open_file */
235     no_close_handle,          /* close_handle */
236     device_destroy            /* destroy */
237 };
238
239 /* inode object */
240
241 struct inode
242 {
243     struct object       obj;        /* object header */
244     struct list         entry;      /* inode hash list entry */
245     struct device      *device;     /* device containing this inode */
246     ino_t               ino;        /* inode number */
247     struct list         open;       /* list of open file descriptors */
248     struct list         locks;      /* list of file locks */
249     struct list         closed;     /* list of file descriptors to close at destroy time */
250 };
251
252 static void inode_dump( struct object *obj, int verbose );
253 static void inode_destroy( struct object *obj );
254
255 static const struct object_ops inode_ops =
256 {
257     sizeof(struct inode),     /* size */
258     inode_dump,               /* dump */
259     no_add_queue,             /* add_queue */
260     NULL,                     /* remove_queue */
261     NULL,                     /* signaled */
262     NULL,                     /* satisfied */
263     no_signal,                /* signal */
264     no_get_fd,                /* get_fd */
265     no_map_access,            /* map_access */
266     no_lookup_name,           /* lookup_name */
267     no_open_file,             /* open_file */
268     no_close_handle,          /* close_handle */
269     inode_destroy             /* destroy */
270 };
271
272 /* file lock object */
273
274 struct file_lock
275 {
276     struct object       obj;         /* object header */
277     struct fd          *fd;          /* fd owning this lock */
278     struct list         fd_entry;    /* entry in list of locks on a given fd */
279     struct list         inode_entry; /* entry in inode list of locks */
280     int                 shared;      /* shared lock? */
281     file_pos_t          start;       /* locked region is interval [start;end) */
282     file_pos_t          end;
283     struct process     *process;     /* process owning this lock */
284     struct list         proc_entry;  /* entry in list of locks owned by the process */
285 };
286
287 static void file_lock_dump( struct object *obj, int verbose );
288 static int file_lock_signaled( struct object *obj, struct thread *thread );
289
290 static const struct object_ops file_lock_ops =
291 {
292     sizeof(struct file_lock),   /* size */
293     file_lock_dump,             /* dump */
294     add_queue,                  /* add_queue */
295     remove_queue,               /* remove_queue */
296     file_lock_signaled,         /* signaled */
297     no_satisfied,               /* satisfied */
298     no_signal,                  /* signal */
299     no_get_fd,                  /* get_fd */
300     no_map_access,              /* map_access */
301     no_lookup_name,             /* lookup_name */
302     no_open_file,               /* open_file */
303     no_close_handle,            /* close_handle */
304     no_destroy                  /* destroy */
305 };
306
307
308 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
309 #define FILE_POS_T_MAX  (~(file_pos_t)0)
310
311 static file_pos_t max_unix_offset = OFF_T_MAX;
312
313 #define DUMP_LONG_LONG(val) do { \
314     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
315         fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
316     else \
317         fprintf( stderr, "%lx", (unsigned long)(val) ); \
318   } while (0)
319
320
321
322 /****************************************************************/
323 /* timeouts support */
324
325 struct timeout_user
326 {
327     struct list           entry;      /* entry in sorted timeout list */
328     timeout_t             when;       /* timeout expiry (absolute time) */
329     timeout_callback      callback;   /* callback function */
330     void                 *private;    /* callback private data */
331 };
332
333 static struct list timeout_list = LIST_INIT(timeout_list);   /* sorted timeouts list */
334 timeout_t current_time;
335
336 static inline void set_current_time(void)
337 {
338     static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
339     struct timeval now;
340     gettimeofday( &now, NULL );
341     current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
342 }
343
344 /* add a timeout user */
345 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
346 {
347     struct timeout_user *user;
348     struct list *ptr;
349
350     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
351     user->when     = (when > 0) ? when : current_time - when;
352     user->callback = func;
353     user->private  = private;
354
355     /* Now insert it in the linked list */
356
357     LIST_FOR_EACH( ptr, &timeout_list )
358     {
359         struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
360         if (timeout->when >= user->when) break;
361     }
362     list_add_before( ptr, &user->entry );
363     return user;
364 }
365
366 /* remove a timeout user */
367 void remove_timeout_user( struct timeout_user *user )
368 {
369     list_remove( &user->entry );
370     free( user );
371 }
372
373 /* return a text description of a timeout for debugging purposes */
374 const char *get_timeout_str( timeout_t timeout )
375 {
376     static char buffer[64];
377     long secs, nsecs;
378
379     if (!timeout) return "0";
380     if (timeout == TIMEOUT_INFINITE) return "infinite";
381
382     if (timeout < 0)  /* relative */
383     {
384         secs = -timeout / TICKS_PER_SEC;
385         nsecs = -timeout % TICKS_PER_SEC;
386         sprintf( buffer, "+%ld.%07ld", secs, nsecs );
387     }
388     else  /* absolute */
389     {
390         secs = (timeout - current_time) / TICKS_PER_SEC;
391         nsecs = (timeout - current_time) % TICKS_PER_SEC;
392         if (nsecs < 0)
393         {
394             nsecs += TICKS_PER_SEC;
395             secs--;
396         }
397         if (secs >= 0)
398             sprintf( buffer, "%x%08x (+%ld.%07ld)",
399                      (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
400         else
401             sprintf( buffer, "%x%08x (-%ld.%07ld)",
402                      (unsigned int)(timeout >> 32), (unsigned int)timeout,
403                      -(secs + 1), TICKS_PER_SEC - nsecs );
404     }
405     return buffer;
406 }
407
408
409 /****************************************************************/
410 /* poll support */
411
412 static struct fd **poll_users;              /* users array */
413 static struct pollfd *pollfd;               /* poll fd array */
414 static int nb_users;                        /* count of array entries actually in use */
415 static int active_users;                    /* current number of active users */
416 static int allocated_users;                 /* count of allocated entries in the array */
417 static struct fd **freelist;                /* list of free entries in the array */
418
419 static int get_next_timeout(void);
420
421 #ifdef USE_EPOLL
422
423 static int epoll_fd = -1;
424
425 static inline void init_epoll(void)
426 {
427     epoll_fd = epoll_create( 128 );
428 }
429
430 /* set the events that epoll waits for on this fd; helper for set_fd_events */
431 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
432 {
433     struct epoll_event ev;
434     int ctl;
435
436     if (epoll_fd == -1) return;
437
438     if (events == -1)  /* stop waiting on this fd completely */
439     {
440         if (pollfd[user].fd == -1) return;  /* already removed */
441         ctl = EPOLL_CTL_DEL;
442     }
443     else if (pollfd[user].fd == -1)
444     {
445         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
446         ctl = EPOLL_CTL_ADD;
447     }
448     else
449     {
450         if (pollfd[user].events == events) return;  /* nothing to do */
451         ctl = EPOLL_CTL_MOD;
452     }
453
454     ev.events = events;
455     memset(&ev.data, 0, sizeof(ev.data));
456     ev.data.u32 = user;
457
458     if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
459     {
460         if (errno == ENOMEM)  /* not enough memory, give up on epoll */
461         {
462             close( epoll_fd );
463             epoll_fd = -1;
464         }
465         else perror( "epoll_ctl" );  /* should not happen */
466     }
467 }
468
469 static inline void remove_epoll_user( struct fd *fd, int user )
470 {
471     if (epoll_fd == -1) return;
472
473     if (pollfd[user].fd != -1)
474     {
475         struct epoll_event dummy;
476         epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
477     }
478 }
479
480 static inline void main_loop_epoll(void)
481 {
482     int i, ret, timeout;
483     struct epoll_event events[128];
484
485     assert( POLLIN == EPOLLIN );
486     assert( POLLOUT == EPOLLOUT );
487     assert( POLLERR == EPOLLERR );
488     assert( POLLHUP == EPOLLHUP );
489
490     if (epoll_fd == -1) return;
491
492     while (active_users)
493     {
494         timeout = get_next_timeout();
495
496         if (!active_users) break;  /* last user removed by a timeout */
497         if (epoll_fd == -1) break;  /* an error occurred with epoll */
498
499         ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
500         set_current_time();
501
502         /* put the events into the pollfd array first, like poll does */
503         for (i = 0; i < ret; i++)
504         {
505             int user = events[i].data.u32;
506             pollfd[user].revents = events[i].events;
507         }
508
509         /* read events from the pollfd array, as set_fd_events may modify them */
510         for (i = 0; i < ret; i++)
511         {
512             int user = events[i].data.u32;
513             if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
514         }
515     }
516 }
517
518 #elif defined(HAVE_KQUEUE)
519
520 static int kqueue_fd = -1;
521
522 static inline void init_epoll(void)
523 {
524 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
525     int mib[2];
526     char release[32];
527     size_t len = sizeof(release);
528
529     mib[0] = CTL_KERN;
530     mib[1] = KERN_OSRELEASE;
531     if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
532     if (atoi(release) < 9) return;
533 #endif
534     kqueue_fd = kqueue();
535 }
536
537 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
538 {
539     struct kevent ev[2];
540
541     if (kqueue_fd == -1) return;
542
543     EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
544     EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
545
546     if (events == -1)  /* stop waiting on this fd completely */
547     {
548         if (pollfd[user].fd == -1) return;  /* already removed */
549         ev[0].flags |= EV_DELETE;
550         ev[1].flags |= EV_DELETE;
551     }
552     else if (pollfd[user].fd == -1)
553     {
554         if (pollfd[user].events) return;  /* stopped waiting on it, don't restart */
555         ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
556         ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
557     }
558     else
559     {
560         if (pollfd[user].events == events) return;  /* nothing to do */
561         ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
562         ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
563     }
564
565     if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
566     {
567         if (errno == ENOMEM)  /* not enough memory, give up on kqueue */
568         {
569             close( kqueue_fd );
570             kqueue_fd = -1;
571         }
572         else perror( "kevent" );  /* should not happen */
573     }
574 }
575
576 static inline void remove_epoll_user( struct fd *fd, int user )
577 {
578     if (kqueue_fd == -1) return;
579
580     if (pollfd[user].fd != -1)
581     {
582         struct kevent ev[2];
583
584         EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
585         EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
586         kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
587     }
588 }
589
590 static inline void main_loop_epoll(void)
591 {
592     int i, ret, timeout;
593     struct kevent events[128];
594
595     if (kqueue_fd == -1) return;
596
597     while (active_users)
598     {
599         timeout = get_next_timeout();
600
601         if (!active_users) break;  /* last user removed by a timeout */
602         if (kqueue_fd == -1) break;  /* an error occurred with kqueue */
603
604         if (timeout != -1)
605         {
606             struct timespec ts;
607
608             ts.tv_sec = timeout / 1000;
609             ts.tv_nsec = (timeout % 1000) * 1000000;
610             ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
611         }
612         else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
613
614         set_current_time();
615
616         /* put the events into the pollfd array first, like poll does */
617         for (i = 0; i < ret; i++)
618         {
619             long user = (long)events[i].udata;
620             pollfd[user].revents = 0;
621         }
622         for (i = 0; i < ret; i++)
623         {
624             long user = (long)events[i].udata;
625             if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
626             else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
627             if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
628             if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
629         }
630
631         /* read events from the pollfd array, as set_fd_events may modify them */
632         for (i = 0; i < ret; i++)
633         {
634             long user = (long)events[i].udata;
635             if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
636             pollfd[user].revents = 0;
637         }
638     }
639 }
640
641 #else /* HAVE_KQUEUE */
642
643 static inline void init_epoll(void) { }
644 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
645 static inline void remove_epoll_user( struct fd *fd, int user ) { }
646 static inline void main_loop_epoll(void) { }
647
648 #endif /* USE_EPOLL */
649
650
651 /* add a user in the poll array and return its index, or -1 on failure */
652 static int add_poll_user( struct fd *fd )
653 {
654     int ret;
655     if (freelist)
656     {
657         ret = freelist - poll_users;
658         freelist = (struct fd **)poll_users[ret];
659     }
660     else
661     {
662         if (nb_users == allocated_users)
663         {
664             struct fd **newusers;
665             struct pollfd *newpoll;
666             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
667             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
668             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
669             {
670                 if (allocated_users)
671                     poll_users = newusers;
672                 else
673                     free( newusers );
674                 return -1;
675             }
676             poll_users = newusers;
677             pollfd = newpoll;
678             if (!allocated_users) init_epoll();
679             allocated_users = new_count;
680         }
681         ret = nb_users++;
682     }
683     pollfd[ret].fd = -1;
684     pollfd[ret].events = 0;
685     pollfd[ret].revents = 0;
686     poll_users[ret] = fd;
687     active_users++;
688     return ret;
689 }
690
691 /* remove a user from the poll list */
692 static void remove_poll_user( struct fd *fd, int user )
693 {
694     assert( user >= 0 );
695     assert( poll_users[user] == fd );
696
697     remove_epoll_user( fd, user );
698     pollfd[user].fd = -1;
699     pollfd[user].events = 0;
700     pollfd[user].revents = 0;
701     poll_users[user] = (struct fd *)freelist;
702     freelist = &poll_users[user];
703     active_users--;
704 }
705
706 /* process pending timeouts and return the time until the next timeout, in milliseconds */
707 static int get_next_timeout(void)
708 {
709     if (!list_empty( &timeout_list ))
710     {
711         struct list expired_list, *ptr;
712
713         /* first remove all expired timers from the list */
714
715         list_init( &expired_list );
716         while ((ptr = list_head( &timeout_list )) != NULL)
717         {
718             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
719
720             if (timeout->when <= current_time)
721             {
722                 list_remove( &timeout->entry );
723                 list_add_tail( &expired_list, &timeout->entry );
724             }
725             else break;
726         }
727
728         /* now call the callback for all the removed timers */
729
730         while ((ptr = list_head( &expired_list )) != NULL)
731         {
732             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
733             list_remove( &timeout->entry );
734             timeout->callback( timeout->private );
735             free( timeout );
736         }
737
738         if ((ptr = list_head( &timeout_list )) != NULL)
739         {
740             struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
741             int diff = (timeout->when - current_time + 9999) / 10000;
742             if (diff < 0) diff = 0;
743             return diff;
744         }
745     }
746     return -1;  /* no pending timeouts */
747 }
748
749 /* server main poll() loop */
750 void main_loop(void)
751 {
752     int i, ret, timeout;
753
754     set_current_time();
755     server_start_time = current_time;
756
757     main_loop_epoll();
758     /* fall through to normal poll loop */
759
760     while (active_users)
761     {
762         timeout = get_next_timeout();
763
764         if (!active_users) break;  /* last user removed by a timeout */
765
766         ret = poll( pollfd, nb_users, timeout );
767         set_current_time();
768
769         if (ret > 0)
770         {
771             for (i = 0; i < nb_users; i++)
772             {
773                 if (pollfd[i].revents)
774                 {
775                     fd_poll_event( poll_users[i], pollfd[i].revents );
776                     if (!--ret) break;
777                 }
778             }
779         }
780     }
781 }
782
783
784 /****************************************************************/
785 /* device functions */
786
787 static struct list device_hash[DEVICE_HASH_SIZE];
788
789 static int is_device_removable( dev_t dev, int unix_fd )
790 {
791 #if defined(linux) && defined(HAVE_FSTATFS)
792     struct statfs stfs;
793
794     /* check for floppy disk */
795     if (major(dev) == FLOPPY_MAJOR) return 1;
796
797     if (fstatfs( unix_fd, &stfs ) == -1) return 0;
798     return (stfs.f_type == 0x9660 ||    /* iso9660 */
799             stfs.f_type == 0x9fa1 ||    /* supermount */
800             stfs.f_type == 0x15013346); /* udf */
801 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
802     struct statfs stfs;
803
804     if (fstatfs( unix_fd, &stfs ) == -1) return 0;
805     return (!strncmp("cd9660", stfs.f_fstypename, sizeof(stfs.f_fstypename)) ||
806             !strncmp("udf", stfs.f_fstypename, sizeof(stfs.f_fstypename)));
807 #elif defined(__NetBSD__)
808     struct statvfs stfs;
809
810     if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
811     return (!strncmp("cd9660", stfs.f_fstypename, sizeof(stfs.f_fstypename)) ||
812             !strncmp("udf", stfs.f_fstypename, sizeof(stfs.f_fstypename)));
813 #elif defined(sun)
814 # include <sys/dkio.h>
815 # include <sys/vtoc.h>
816     struct dk_cinfo dkinf;
817     if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
818     return (dkinf.dki_ctype == DKC_CDROM ||
819             dkinf.dki_ctype == DKC_NCRFLOPPY ||
820             dkinf.dki_ctype == DKC_SMSFLOPPY ||
821             dkinf.dki_ctype == DKC_INTEL82072 ||
822             dkinf.dki_ctype == DKC_INTEL82077);
823 #else
824     return 0;
825 #endif
826 }
827
828 /* retrieve the device object for a given fd, creating it if needed */
829 static struct device *get_device( dev_t dev, int unix_fd )
830 {
831     struct device *device;
832     unsigned int i, hash = dev % DEVICE_HASH_SIZE;
833
834     if (device_hash[hash].next)
835     {
836         LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
837             if (device->dev == dev) return (struct device *)grab_object( device );
838     }
839     else list_init( &device_hash[hash] );
840
841     /* not found, create it */
842
843     if (unix_fd == -1) return NULL;
844     if ((device = alloc_object( &device_ops )))
845     {
846         device->dev = dev;
847         device->removable = is_device_removable( dev, unix_fd );
848         for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
849         list_add_head( &device_hash[hash], &device->entry );
850     }
851     return device;
852 }
853
854 static void device_dump( struct object *obj, int verbose )
855 {
856     struct device *device = (struct device *)obj;
857     fprintf( stderr, "Device dev=" );
858     DUMP_LONG_LONG( device->dev );
859     fprintf( stderr, "\n" );
860 }
861
862 static void device_destroy( struct object *obj )
863 {
864     struct device *device = (struct device *)obj;
865     unsigned int i;
866
867     for (i = 0; i < INODE_HASH_SIZE; i++)
868         assert( list_empty(&device->inode_hash[i]) );
869
870     list_remove( &device->entry );  /* remove it from the hash table */
871 }
872
873
874 /****************************************************************/
875 /* inode functions */
876
877 /* close all pending file descriptors in the closed list */
878 static void inode_close_pending( struct inode *inode, int keep_unlinks )
879 {
880     struct list *ptr = list_head( &inode->closed );
881
882     while (ptr)
883     {
884         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
885         struct list *next = list_next( &inode->closed, ptr );
886
887         if (fd->unix_fd != -1)
888         {
889             close( fd->unix_fd );
890             fd->unix_fd = -1;
891         }
892         if (!keep_unlinks || !fd->unlink[0])  /* get rid of it unless there's an unlink pending on that file */
893         {
894             list_remove( ptr );
895             free( fd );
896         }
897         ptr = next;
898     }
899 }
900
901 static void inode_dump( struct object *obj, int verbose )
902 {
903     struct inode *inode = (struct inode *)obj;
904     fprintf( stderr, "Inode device=%p ino=", inode->device );
905     DUMP_LONG_LONG( inode->ino );
906     fprintf( stderr, "\n" );
907 }
908
909 static void inode_destroy( struct object *obj )
910 {
911     struct inode *inode = (struct inode *)obj;
912     struct list *ptr;
913
914     assert( list_empty(&inode->open) );
915     assert( list_empty(&inode->locks) );
916
917     list_remove( &inode->entry );
918
919     while ((ptr = list_head( &inode->closed )))
920     {
921         struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
922         list_remove( ptr );
923         if (fd->unix_fd != -1) close( fd->unix_fd );
924         if (fd->unlink[0])
925         {
926             /* make sure it is still the same file */
927             struct stat st;
928             if (!stat( fd->unlink, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
929             {
930                 if (S_ISDIR(st.st_mode)) rmdir( fd->unlink );
931                 else unlink( fd->unlink );
932             }
933         }
934         free( fd );
935     }
936     release_object( inode->device );
937 }
938
939 /* retrieve the inode object for a given fd, creating it if needed */
940 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
941 {
942     struct device *device;
943     struct inode *inode;
944     unsigned int hash = ino % INODE_HASH_SIZE;
945
946     if (!(device = get_device( dev, unix_fd ))) return NULL;
947
948     LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
949     {
950         if (inode->ino == ino)
951         {
952             release_object( device );
953             return (struct inode *)grab_object( inode );
954         }
955     }
956
957     /* not found, create it */
958     if ((inode = alloc_object( &inode_ops )))
959     {
960         inode->device = device;
961         inode->ino    = ino;
962         list_init( &inode->open );
963         list_init( &inode->locks );
964         list_init( &inode->closed );
965         list_add_head( &device->inode_hash[hash], &inode->entry );
966     }
967     else release_object( device );
968
969     return inode;
970 }
971
972 /* add fd to the inode list of file descriptors to close */
973 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
974 {
975     if (!list_empty( &inode->locks ))
976     {
977         list_add_head( &inode->closed, &fd->entry );
978     }
979     else if (fd->unlink[0])  /* close the fd but keep the structure around for unlink */
980     {
981         if (fd->unix_fd != -1) close( fd->unix_fd );
982         fd->unix_fd = -1;
983         list_add_head( &inode->closed, &fd->entry );
984     }
985     else  /* no locks on this inode and no unlink, get rid of the fd */
986     {
987         if (fd->unix_fd != -1) close( fd->unix_fd );
988         free( fd );
989     }
990 }
991
992
993 /****************************************************************/
994 /* file lock functions */
995
996 static void file_lock_dump( struct object *obj, int verbose )
997 {
998     struct file_lock *lock = (struct file_lock *)obj;
999     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1000              lock->shared ? "shared" : "excl", lock->fd, lock->process );
1001     DUMP_LONG_LONG( lock->start );
1002     fprintf( stderr, " end=" );
1003     DUMP_LONG_LONG( lock->end );
1004     fprintf( stderr, "\n" );
1005 }
1006
1007 static int file_lock_signaled( struct object *obj, struct thread *thread )
1008 {
1009     struct file_lock *lock = (struct file_lock *)obj;
1010     /* lock is signaled if it has lost its owner */
1011     return !lock->process;
1012 }
1013
1014 /* set (or remove) a Unix lock if possible for the given range */
1015 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1016 {
1017     struct flock fl;
1018
1019     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
1020     for (;;)
1021     {
1022         if (start == end) return 1;  /* can't set zero-byte lock */
1023         if (start > max_unix_offset) return 1;  /* ignore it */
1024         fl.l_type   = type;
1025         fl.l_whence = SEEK_SET;
1026         fl.l_start  = start;
1027         if (!end || end > max_unix_offset) fl.l_len = 0;
1028         else fl.l_len = end - start;
1029         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1030
1031         switch(errno)
1032         {
1033         case EACCES:
1034             /* check whether locks work at all on this file system */
1035             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1036             {
1037                 set_error( STATUS_FILE_LOCK_CONFLICT );
1038                 return 0;
1039             }
1040             /* fall through */
1041         case EIO:
1042         case ENOLCK:
1043             /* no locking on this fs, just ignore it */
1044             fd->fs_locks = 0;
1045             return 1;
1046         case EAGAIN:
1047             set_error( STATUS_FILE_LOCK_CONFLICT );
1048             return 0;
1049         case EBADF:
1050             /* this can happen if we try to set a write lock on a read-only file */
1051             /* we just ignore that error */
1052             if (fl.l_type == F_WRLCK) return 1;
1053             set_error( STATUS_ACCESS_DENIED );
1054             return 0;
1055 #ifdef EOVERFLOW
1056         case EOVERFLOW:
1057 #endif
1058         case EINVAL:
1059             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1060             /* in that case we shrink the limit and retry */
1061             if (max_unix_offset > INT_MAX)
1062             {
1063                 max_unix_offset = INT_MAX;
1064                 break;  /* retry */
1065             }
1066             /* fall through */
1067         default:
1068             file_set_error();
1069             return 0;
1070         }
1071     }
1072 }
1073
1074 /* check if interval [start;end) overlaps the lock */
1075 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1076 {
1077     if (lock->end && start >= lock->end) return 0;
1078     if (end && lock->start >= end) return 0;
1079     return 1;
1080 }
1081
1082 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1083 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1084 {
1085     struct hole
1086     {
1087         struct hole *next;
1088         struct hole *prev;
1089         file_pos_t   start;
1090         file_pos_t   end;
1091     } *first, *cur, *next, *buffer;
1092
1093     struct list *ptr;
1094     int count = 0;
1095
1096     if (!fd->inode) return;
1097     if (!fd->fs_locks) return;
1098     if (start == end || start > max_unix_offset) return;
1099     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1100
1101     /* count the number of locks overlapping the specified area */
1102
1103     LIST_FOR_EACH( ptr, &fd->inode->locks )
1104     {
1105         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1106         if (lock->start == lock->end) continue;
1107         if (lock_overlaps( lock, start, end )) count++;
1108     }
1109
1110     if (!count)  /* no locks at all, we can unlock everything */
1111     {
1112         set_unix_lock( fd, start, end, F_UNLCK );
1113         return;
1114     }
1115
1116     /* allocate space for the list of holes */
1117     /* max. number of holes is number of locks + 1 */
1118
1119     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1120     first = buffer;
1121     first->next  = NULL;
1122     first->prev  = NULL;
1123     first->start = start;
1124     first->end   = end;
1125     next = first + 1;
1126
1127     /* build a sorted list of unlocked holes in the specified area */
1128
1129     LIST_FOR_EACH( ptr, &fd->inode->locks )
1130     {
1131         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1132         if (lock->start == lock->end) continue;
1133         if (!lock_overlaps( lock, start, end )) continue;
1134
1135         /* go through all the holes touched by this lock */
1136         for (cur = first; cur; cur = cur->next)
1137         {
1138             if (cur->end <= lock->start) continue; /* hole is before start of lock */
1139             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
1140
1141             /* now we know that lock is overlapping hole */
1142
1143             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
1144             {
1145                 cur->start = lock->end;
1146                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
1147                 /* now hole is empty, remove it */
1148                 if (cur->next) cur->next->prev = cur->prev;
1149                 if (cur->prev) cur->prev->next = cur->next;
1150                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
1151             }
1152             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
1153             {
1154                 cur->end = lock->start;
1155                 assert( cur->start < cur->end );
1156             }
1157             else  /* lock is in the middle of hole, split hole in two */
1158             {
1159                 next->prev = cur;
1160                 next->next = cur->next;
1161                 cur->next = next;
1162                 next->start = lock->end;
1163                 next->end = cur->end;
1164                 cur->end = lock->start;
1165                 assert( next->start < next->end );
1166                 assert( cur->end < next->start );
1167                 next++;
1168                 break;  /* done with this lock */
1169             }
1170         }
1171     }
1172
1173     /* clear Unix locks for all the holes */
1174
1175     for (cur = first; cur; cur = cur->next)
1176         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1177
1178  done:
1179     free( buffer );
1180 }
1181
1182 /* create a new lock on a fd */
1183 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1184 {
1185     struct file_lock *lock;
1186
1187     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1188     lock->shared  = shared;
1189     lock->start   = start;
1190     lock->end     = end;
1191     lock->fd      = fd;
1192     lock->process = current->process;
1193
1194     /* now try to set a Unix lock */
1195     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1196     {
1197         release_object( lock );
1198         return NULL;
1199     }
1200     list_add_head( &fd->locks, &lock->fd_entry );
1201     list_add_head( &fd->inode->locks, &lock->inode_entry );
1202     list_add_head( &lock->process->locks, &lock->proc_entry );
1203     return lock;
1204 }
1205
1206 /* remove an existing lock */
1207 static void remove_lock( struct file_lock *lock, int remove_unix )
1208 {
1209     struct inode *inode = lock->fd->inode;
1210
1211     list_remove( &lock->fd_entry );
1212     list_remove( &lock->inode_entry );
1213     list_remove( &lock->proc_entry );
1214     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1215     if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1216     lock->process = NULL;
1217     wake_up( &lock->obj, 0 );
1218     release_object( lock );
1219 }
1220
1221 /* remove all locks owned by a given process */
1222 void remove_process_locks( struct process *process )
1223 {
1224     struct list *ptr;
1225
1226     while ((ptr = list_head( &process->locks )))
1227     {
1228         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1229         remove_lock( lock, 1 );  /* this removes it from the list */
1230     }
1231 }
1232
1233 /* remove all locks on a given fd */
1234 static void remove_fd_locks( struct fd *fd )
1235 {
1236     file_pos_t start = FILE_POS_T_MAX, end = 0;
1237     struct list *ptr;
1238
1239     while ((ptr = list_head( &fd->locks )))
1240     {
1241         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1242         if (lock->start < start) start = lock->start;
1243         if (!lock->end || lock->end > end) end = lock->end - 1;
1244         remove_lock( lock, 0 );
1245     }
1246     if (start < end) remove_unix_locks( fd, start, end + 1 );
1247 }
1248
1249 /* add a lock on an fd */
1250 /* returns handle to wait on */
1251 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1252 {
1253     struct list *ptr;
1254     file_pos_t end = start + count;
1255
1256     if (!fd->inode)  /* not a regular file */
1257     {
1258         set_error( STATUS_INVALID_DEVICE_REQUEST );
1259         return 0;
1260     }
1261
1262     /* don't allow wrapping locks */
1263     if (end && end < start)
1264     {
1265         set_error( STATUS_INVALID_PARAMETER );
1266         return 0;
1267     }
1268
1269     /* check if another lock on that file overlaps the area */
1270     LIST_FOR_EACH( ptr, &fd->inode->locks )
1271     {
1272         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1273         if (!lock_overlaps( lock, start, end )) continue;
1274         if (lock->shared && shared) continue;
1275         /* found one */
1276         if (!wait)
1277         {
1278             set_error( STATUS_FILE_LOCK_CONFLICT );
1279             return 0;
1280         }
1281         set_error( STATUS_PENDING );
1282         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1283     }
1284
1285     /* not found, add it */
1286     if (add_lock( fd, shared, start, end )) return 0;
1287     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1288     {
1289         /* Unix lock conflict -> tell client to wait and retry */
1290         if (wait) set_error( STATUS_PENDING );
1291     }
1292     return 0;
1293 }
1294
1295 /* remove a lock on an fd */
1296 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1297 {
1298     struct list *ptr;
1299     file_pos_t end = start + count;
1300
1301     /* find an existing lock with the exact same parameters */
1302     LIST_FOR_EACH( ptr, &fd->locks )
1303     {
1304         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1305         if ((lock->start == start) && (lock->end == end))
1306         {
1307             remove_lock( lock, 1 );
1308             return;
1309         }
1310     }
1311     set_error( STATUS_FILE_LOCK_CONFLICT );
1312 }
1313
1314
1315 /****************************************************************/
1316 /* file descriptor functions */
1317
1318 static void fd_dump( struct object *obj, int verbose )
1319 {
1320     struct fd *fd = (struct fd *)obj;
1321     fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1322     if (fd->inode) fprintf( stderr, " inode=%p unlink='%s'", fd->inode, fd->closed->unlink );
1323     fprintf( stderr, "\n" );
1324 }
1325
1326 static void fd_destroy( struct object *obj )
1327 {
1328     struct fd *fd = (struct fd *)obj;
1329
1330     free_async_queue( fd->read_q );
1331     free_async_queue( fd->write_q );
1332     free_async_queue( fd->wait_q );
1333
1334     remove_fd_locks( fd );
1335     list_remove( &fd->inode_entry );
1336     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1337     if (fd->inode)
1338     {
1339         inode_add_closed_fd( fd->inode, fd->closed );
1340         release_object( fd->inode );
1341     }
1342     else  /* no inode, close it right away */
1343     {
1344         if (fd->unix_fd != -1) close( fd->unix_fd );
1345     }
1346 }
1347
1348 /* set the events that select waits for on this fd */
1349 void set_fd_events( struct fd *fd, int events )
1350 {
1351     int user = fd->poll_index;
1352     assert( poll_users[user] == fd );
1353
1354     set_fd_epoll_events( fd, user, events );
1355
1356     if (events == -1)  /* stop waiting on this fd completely */
1357     {
1358         pollfd[user].fd = -1;
1359         pollfd[user].events = POLLERR;
1360         pollfd[user].revents = 0;
1361     }
1362     else if (pollfd[user].fd != -1 || !pollfd[user].events)
1363     {
1364         pollfd[user].fd = fd->unix_fd;
1365         pollfd[user].events = events;
1366     }
1367 }
1368
1369 /* prepare an fd for unmounting its corresponding device */
1370 static inline void unmount_fd( struct fd *fd )
1371 {
1372     assert( fd->inode );
1373
1374     async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1375     async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1376
1377     if (fd->poll_index != -1) set_fd_events( fd, -1 );
1378
1379     if (fd->unix_fd != -1) close( fd->unix_fd );
1380
1381     fd->unix_fd = -1;
1382     fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1383     fd->closed->unix_fd = -1;
1384     fd->closed->unlink[0] = 0;
1385
1386     /* stop using Unix locks on this fd (existing locks have been removed by close) */
1387     fd->fs_locks = 0;
1388 }
1389
1390 /* allocate an fd object, without setting the unix fd yet */
1391 static struct fd *alloc_fd_object(void)
1392 {
1393     struct fd *fd = alloc_object( &fd_ops );
1394
1395     if (!fd) return NULL;
1396
1397     fd->fd_ops     = NULL;
1398     fd->user       = NULL;
1399     fd->inode      = NULL;
1400     fd->closed     = NULL;
1401     fd->access     = 0;
1402     fd->options    = 0;
1403     fd->sharing    = 0;
1404     fd->unix_fd    = -1;
1405     fd->signaled   = 1;
1406     fd->fs_locks   = 1;
1407     fd->poll_index = -1;
1408     fd->read_q     = NULL;
1409     fd->write_q    = NULL;
1410     fd->wait_q     = NULL;
1411     list_init( &fd->inode_entry );
1412     list_init( &fd->locks );
1413
1414     if ((fd->poll_index = add_poll_user( fd )) == -1)
1415     {
1416         release_object( fd );
1417         return NULL;
1418     }
1419     return fd;
1420 }
1421
1422 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1423 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1424 {
1425     struct fd *fd = alloc_object( &fd_ops );
1426
1427     if (!fd) return NULL;
1428
1429     fd->fd_ops     = fd_user_ops;
1430     fd->user       = user;
1431     fd->inode      = NULL;
1432     fd->closed     = NULL;
1433     fd->access     = 0;
1434     fd->options    = options;
1435     fd->sharing    = 0;
1436     fd->unix_fd    = -1;
1437     fd->signaled   = 0;
1438     fd->fs_locks   = 0;
1439     fd->poll_index = -1;
1440     fd->read_q     = NULL;
1441     fd->write_q    = NULL;
1442     fd->wait_q     = NULL;
1443     fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1444     list_init( &fd->inode_entry );
1445     list_init( &fd->locks );
1446     return fd;
1447 }
1448
1449 /* set the status to return when the fd has no associated unix fd */
1450 void set_no_fd_status( struct fd *fd, unsigned int status )
1451 {
1452     fd->no_fd_status = status;
1453 }
1454
1455 /* check if the desired access is possible without violating */
1456 /* the sharing mode of other opens of the same file */
1457 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
1458 {
1459     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1460     unsigned int existing_access = 0;
1461     struct list *ptr;
1462
1463     /* if access mode is 0, sharing mode is ignored */
1464     if (!access) sharing = existing_sharing;
1465     fd->access = access;
1466     fd->sharing = sharing;
1467
1468     LIST_FOR_EACH( ptr, &fd->inode->open )
1469     {
1470         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1471         if (fd_ptr != fd)
1472         {
1473             existing_sharing &= fd_ptr->sharing;
1474             existing_access  |= fd_ptr->access;
1475         }
1476     }
1477
1478     if ((access & FILE_UNIX_READ_ACCESS) && !(existing_sharing & FILE_SHARE_READ)) return 0;
1479     if ((access & FILE_UNIX_WRITE_ACCESS) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
1480     if ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)) return 0;
1481     if ((existing_access & FILE_UNIX_READ_ACCESS) && !(sharing & FILE_SHARE_READ)) return 0;
1482     if ((existing_access & FILE_UNIX_WRITE_ACCESS) && !(sharing & FILE_SHARE_WRITE)) return 0;
1483     if ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)) return 0;
1484     return 1;
1485 }
1486
1487 /* sets the user of an fd that previously had no user */
1488 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1489 {
1490     assert( fd->fd_ops == NULL );
1491     fd->fd_ops = user_ops;
1492     fd->user   = user;
1493 }
1494
1495 /* open() wrapper that returns a struct fd with no fd user set */
1496 struct fd *open_fd( const char *name, int flags, mode_t *mode, unsigned int access,
1497                     unsigned int sharing, unsigned int options )
1498 {
1499     struct stat st;
1500     struct closed_fd *closed_fd;
1501     struct fd *fd;
1502     const char *unlink_name = "";
1503     int rw_mode;
1504
1505     if ((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE))
1506     {
1507         set_error( STATUS_INVALID_PARAMETER );
1508         return NULL;
1509     }
1510
1511     if (!(fd = alloc_fd_object())) return NULL;
1512
1513     fd->options = options;
1514     if (options & FILE_DELETE_ON_CLOSE) unlink_name = name;
1515     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) + strlen(unlink_name) )))
1516     {
1517         release_object( fd );
1518         return NULL;
1519     }
1520
1521     /* create the directory if needed */
1522     if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1523     {
1524         if (mkdir( name, 0777 ) == -1)
1525         {
1526             if (errno != EEXIST || (flags & O_EXCL))
1527             {
1528                 file_set_error();
1529                 goto error;
1530             }
1531         }
1532         flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1533     }
1534
1535     if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1536     {
1537         if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1538         else rw_mode = O_WRONLY;
1539     }
1540     else rw_mode = O_RDONLY;
1541
1542     if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1543     {
1544         /* if we tried to open a directory for write access, retry read-only */
1545         if (errno != EISDIR ||
1546             !(access & FILE_UNIX_WRITE_ACCESS) ||
1547             (fd->unix_fd = open( name, O_RDONLY | (flags & ~O_TRUNC), *mode )) == -1)
1548         {
1549             file_set_error();
1550             goto error;
1551         }
1552     }
1553
1554     closed_fd->unix_fd = fd->unix_fd;
1555     closed_fd->unlink[0] = 0;
1556     fstat( fd->unix_fd, &st );
1557     *mode = st.st_mode;
1558
1559     /* only bother with an inode for normal files and directories */
1560     if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1561     {
1562         struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1563
1564         if (!inode)
1565         {
1566             /* we can close the fd because there are no others open on the same file,
1567              * otherwise we wouldn't have failed to allocate a new inode
1568              */
1569             goto error;
1570         }
1571         fd->inode = inode;
1572         fd->closed = closed_fd;
1573         list_add_head( &inode->open, &fd->inode_entry );
1574
1575         /* check directory options */
1576         if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1577         {
1578             release_object( fd );
1579             set_error( STATUS_NOT_A_DIRECTORY );
1580             return NULL;
1581         }
1582         if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1583         {
1584             release_object( fd );
1585             set_error( STATUS_FILE_IS_A_DIRECTORY );
1586             return NULL;
1587         }
1588         if (!check_sharing( fd, access, sharing ))
1589         {
1590             release_object( fd );
1591             set_error( STATUS_SHARING_VIOLATION );
1592             return NULL;
1593         }
1594         strcpy( closed_fd->unlink, unlink_name );
1595         if (flags & O_TRUNC) ftruncate( fd->unix_fd, 0 );
1596     }
1597     else  /* special file */
1598     {
1599         if (options & FILE_DIRECTORY_FILE)
1600         {
1601             set_error( STATUS_NOT_A_DIRECTORY );
1602             goto error;
1603         }
1604         if (unlink_name[0])  /* we can't unlink special files */
1605         {
1606             set_error( STATUS_INVALID_PARAMETER );
1607             goto error;
1608         }
1609         free( closed_fd );
1610     }
1611     return fd;
1612
1613 error:
1614     release_object( fd );
1615     free( closed_fd );
1616     return NULL;
1617 }
1618
1619 /* create an fd for an anonymous file */
1620 /* if the function fails the unix fd is closed */
1621 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1622                                 unsigned int options )
1623 {
1624     struct fd *fd = alloc_fd_object();
1625
1626     if (fd)
1627     {
1628         set_fd_user( fd, fd_user_ops, user );
1629         fd->unix_fd = unix_fd;
1630         fd->options = options;
1631         return fd;
1632     }
1633     close( unix_fd );
1634     return NULL;
1635 }
1636
1637 /* retrieve the object that is using an fd */
1638 void *get_fd_user( struct fd *fd )
1639 {
1640     return fd->user;
1641 }
1642
1643 /* retrieve the opening options for the fd */
1644 unsigned int get_fd_options( struct fd *fd )
1645 {
1646     return fd->options;
1647 }
1648
1649 /* retrieve the unix fd for an object */
1650 int get_unix_fd( struct fd *fd )
1651 {
1652     if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1653     return fd->unix_fd;
1654 }
1655
1656 /* check if two file descriptors point to the same file */
1657 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1658 {
1659     return fd1->inode == fd2->inode;
1660 }
1661
1662 /* check if fd is on a removable device */
1663 int is_fd_removable( struct fd *fd )
1664 {
1665     return (fd->inode && fd->inode->device->removable);
1666 }
1667
1668 /* set or clear the fd signaled state */
1669 void set_fd_signaled( struct fd *fd, int signaled )
1670 {
1671     fd->signaled = signaled;
1672     if (signaled) wake_up( fd->user, 0 );
1673 }
1674
1675 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1676 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1677 {
1678     return (!current || current->process == process);
1679 }
1680
1681 /* callback for event happening in the main poll() loop */
1682 void fd_poll_event( struct fd *fd, int event )
1683 {
1684     return fd->fd_ops->poll_event( fd, event );
1685 }
1686
1687 /* check if events are pending and if yes return which one(s) */
1688 int check_fd_events( struct fd *fd, int events )
1689 {
1690     struct pollfd pfd;
1691
1692     if (fd->unix_fd == -1) return POLLERR;
1693     if (fd->inode) return events;  /* regular files are always signaled */
1694
1695     pfd.fd     = fd->unix_fd;
1696     pfd.events = events;
1697     if (poll( &pfd, 1, 0 ) <= 0) return 0;
1698     return pfd.revents;
1699 }
1700
1701 /* default signaled() routine for objects that poll() on an fd */
1702 int default_fd_signaled( struct object *obj, struct thread *thread )
1703 {
1704     struct fd *fd = get_obj_fd( obj );
1705     int ret = fd->signaled;
1706     release_object( fd );
1707     return ret;
1708 }
1709
1710 int default_fd_get_poll_events( struct fd *fd )
1711 {
1712     int events = 0;
1713
1714     if (async_waiting( fd->read_q )) events |= POLLIN;
1715     if (async_waiting( fd->write_q )) events |= POLLOUT;
1716     return events;
1717 }
1718
1719 /* default handler for poll() events */
1720 void default_poll_event( struct fd *fd, int event )
1721 {
1722     if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
1723     if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
1724
1725     /* if an error occurred, stop polling this fd to avoid busy-looping */
1726     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1727     else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1728 }
1729
1730 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1731 {
1732     struct async_queue *queue;
1733     struct async *async;
1734
1735     switch (type)
1736     {
1737     case ASYNC_TYPE_READ:
1738         if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
1739         queue = fd->read_q;
1740         break;
1741     case ASYNC_TYPE_WRITE:
1742         if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
1743         queue = fd->write_q;
1744         break;
1745     case ASYNC_TYPE_WAIT:
1746         if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
1747         queue = fd->wait_q;
1748         break;
1749     default:
1750         queue = NULL;
1751         assert(0);
1752     }
1753
1754     if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
1755     {
1756         if (!fd->inode)
1757             set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
1758         else  /* regular files are always ready for read and write */
1759             async_wake_up( queue, STATUS_ALERTED );
1760     }
1761     return async;
1762 }
1763
1764 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
1765 {
1766     switch (type)
1767     {
1768     case ASYNC_TYPE_READ:
1769         async_wake_up( fd->read_q, status );
1770         break;
1771     case ASYNC_TYPE_WRITE:
1772         async_wake_up( fd->write_q, status );
1773         break;
1774     case ASYNC_TYPE_WAIT:
1775         async_wake_up( fd->wait_q, status );
1776         break;
1777     default:
1778         assert(0);
1779     }
1780 }
1781
1782 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
1783 {
1784     fd->fd_ops->reselect_async( fd, queue );
1785 }
1786
1787 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
1788 {
1789     struct async *async;
1790
1791     if ((async = fd_queue_async( fd, data, type, count )))
1792     {
1793         release_object( async );
1794         set_error( STATUS_PENDING );
1795     }
1796 }
1797
1798 /* default reselect_async() fd routine */
1799 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
1800 {
1801     if (queue != fd->wait_q)
1802     {
1803         int poll_events = fd->fd_ops->get_poll_events( fd );
1804         int events = check_fd_events( fd, poll_events );
1805         if (events) fd->fd_ops->poll_event( fd, events );
1806         else set_fd_events( fd, poll_events );
1807     }
1808 }
1809
1810 /* default cancel_async() fd routine */
1811 void default_fd_cancel_async( struct fd *fd )
1812 {
1813     async_wake_up( fd->read_q, STATUS_CANCELLED );
1814     async_wake_up( fd->write_q, STATUS_CANCELLED );
1815     async_wake_up( fd->wait_q, STATUS_CANCELLED );
1816 }
1817
1818 /* default flush() routine */
1819 void no_flush( struct fd *fd, struct event **event )
1820 {
1821     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1822 }
1823
1824 static inline int is_valid_mounted_device( struct stat *st )
1825 {
1826 #if defined(linux) || defined(__sun__)
1827     return S_ISBLK( st->st_mode );
1828 #else
1829     /* disks are char devices on *BSD */
1830     return S_ISCHR( st->st_mode );
1831 #endif
1832 }
1833
1834 /* close all Unix file descriptors on a device to allow unmounting it */
1835 static void unmount_device( struct fd *device_fd )
1836 {
1837     unsigned int i;
1838     struct stat st;
1839     struct device *device;
1840     struct inode *inode;
1841     struct fd *fd;
1842     int unix_fd = get_unix_fd( device_fd );
1843
1844     if (unix_fd == -1) return;
1845
1846     if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
1847     {
1848         set_error( STATUS_INVALID_PARAMETER );
1849         return;
1850     }
1851
1852     if (!(device = get_device( st.st_rdev, -1 ))) return;
1853
1854     for (i = 0; i < INODE_HASH_SIZE; i++)
1855     {
1856         LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
1857         {
1858             LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
1859             {
1860                 unmount_fd( fd );
1861             }
1862             inode_close_pending( inode, 0 );
1863         }
1864     }
1865     /* remove it from the hash table */
1866     list_remove( &device->entry );
1867     list_init( &device->entry );
1868     release_object( device );
1869 }
1870
1871 /* default ioctl() routine */
1872 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async,
1873                                const void *data, data_size_t size )
1874 {
1875     switch(code)
1876     {
1877     case FSCTL_DISMOUNT_VOLUME:
1878         unmount_device( fd );
1879         return 0;
1880     default:
1881         set_error( STATUS_NOT_SUPPORTED );
1882         return 0;
1883     }
1884 }
1885
1886 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1887 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1888                                      unsigned int access )
1889 {
1890     struct fd *fd = NULL;
1891     struct object *obj;
1892
1893     if ((obj = get_handle_obj( process, handle, access, NULL )))
1894     {
1895         fd = get_obj_fd( obj );
1896         release_object( obj );
1897     }
1898     return fd;
1899 }
1900
1901 /* flush a file buffers */
1902 DECL_HANDLER(flush_file)
1903 {
1904     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1905     struct event * event = NULL;
1906
1907     if (fd)
1908     {
1909         fd->fd_ops->flush( fd, &event );
1910         if ( event )
1911         {
1912             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1913         }
1914         release_object( fd );
1915     }
1916 }
1917
1918 /* open a file object */
1919 DECL_HANDLER(open_file_object)
1920 {
1921     struct unicode_str name;
1922     struct directory *root = NULL;
1923     struct object *obj, *result;
1924
1925     get_req_unicode_str( &name );
1926     if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
1927         return;
1928
1929     if ((obj = open_object_dir( root, &name, req->attributes, NULL )))
1930     {
1931         if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
1932         {
1933             reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
1934             release_object( result );
1935         }
1936         release_object( obj );
1937     }
1938
1939     if (root) release_object( root );
1940 }
1941
1942 /* get a Unix fd to access a file */
1943 DECL_HANDLER(get_handle_fd)
1944 {
1945     struct fd *fd;
1946
1947     if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
1948     {
1949         int unix_fd = get_unix_fd( fd );
1950         if (unix_fd != -1)
1951         {
1952             send_client_fd( current->process, unix_fd, req->handle );
1953             reply->type = fd->fd_ops->get_fd_type( fd );
1954             reply->removable = is_fd_removable(fd);
1955             reply->options = fd->options;
1956             reply->access = get_handle_access( current->process, req->handle );
1957         }
1958         release_object( fd );
1959     }
1960 }
1961
1962 /* perform an ioctl on a file */
1963 DECL_HANDLER(ioctl)
1964 {
1965     unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
1966     struct fd *fd = get_handle_fd_obj( current->process, req->handle, access );
1967
1968     if (fd)
1969     {
1970         reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async,
1971                                          get_req_data(), get_req_data_size() );
1972         reply->options = fd->options;
1973         release_object( fd );
1974     }
1975 }
1976
1977 /* create / reschedule an async I/O */
1978 DECL_HANDLER(register_async)
1979 {
1980     unsigned int access;
1981     struct fd *fd;
1982
1983     switch(req->type)
1984     {
1985     case ASYNC_TYPE_READ:
1986         access = FILE_READ_DATA;
1987         break;
1988     case ASYNC_TYPE_WRITE:
1989         access = FILE_WRITE_DATA;
1990         break;
1991     default:
1992         set_error( STATUS_INVALID_PARAMETER );
1993         return;
1994     }
1995
1996     if ((fd = get_handle_fd_obj( current->process, req->handle, access )))
1997     {
1998         if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
1999         release_object( fd );
2000     }
2001 }
2002
2003 /* cancels all async I/O */
2004 DECL_HANDLER(cancel_async)
2005 {
2006     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2007
2008     if (fd)
2009     {
2010         if (get_unix_fd( fd ) != -1) fd->fd_ops->cancel_async( fd );
2011         release_object( fd );
2012     }
2013 }