winhttp: Don't remove content-type/length headers in handle_redirect().
[wine.git] / server / fd.c
blobad1b7a1bd4a07c2ee315e93c56be147f2eeb2d18
1 /*
2 * Server-side file descriptor management
4 * Copyright (C) 2000, 2003 Alexandre Julliard
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.
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.
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <dirent.h>
27 #include <errno.h>
28 #include <fcntl.h>
29 #include <limits.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <stdlib.h>
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SYS_POLL_H
39 #include <sys/poll.h>
40 #endif
41 #ifdef HAVE_LINUX_MAJOR_H
42 #include <linux/major.h>
43 #endif
44 #ifdef HAVE_SYS_STATVFS_H
45 #include <sys/statvfs.h>
46 #endif
47 #ifdef HAVE_SYS_VFS_H
48 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
49 #define list SYSLIST
50 #define list_next SYSLIST_NEXT
51 #define list_prev SYSLIST_PREV
52 #define list_head SYSLIST_HEAD
53 #define list_tail SYSLIST_TAIL
54 #define list_move_tail SYSLIST_MOVE_TAIL
55 #define list_remove SYSLIST_REMOVE
56 #include <sys/vfs.h>
57 #undef list
58 #undef list_next
59 #undef list_prev
60 #undef list_head
61 #undef list_tail
62 #undef list_move_tail
63 #undef list_remove
64 #endif
65 #ifdef HAVE_SYS_PARAM_H
66 #include <sys/param.h>
67 #endif
68 #ifdef HAVE_SYS_MOUNT_H
69 #include <sys/mount.h>
70 #endif
71 #ifdef HAVE_SYS_STATFS_H
72 #include <sys/statfs.h>
73 #endif
74 #ifdef HAVE_SYS_SYSCTL_H
75 #include <sys/sysctl.h>
76 #endif
77 #ifdef HAVE_SYS_EVENT_H
78 #include <sys/event.h>
79 #undef LIST_INIT
80 #undef LIST_ENTRY
81 #endif
82 #ifdef HAVE_STDINT_H
83 #include <stdint.h>
84 #endif
85 #include <sys/stat.h>
86 #include <sys/time.h>
87 #ifdef MAJOR_IN_MKDEV
88 #include <sys/mkdev.h>
89 #elif defined(MAJOR_IN_SYSMACROS)
90 #include <sys/sysmacros.h>
91 #endif
92 #include <sys/types.h>
93 #include <unistd.h>
94 #ifdef HAVE_SYS_SYSCALL_H
95 #include <sys/syscall.h>
96 #endif
98 #include "ntstatus.h"
99 #define WIN32_NO_STATUS
100 #include "object.h"
101 #include "file.h"
102 #include "handle.h"
103 #include "process.h"
104 #include "request.h"
106 #include "winternl.h"
107 #include "winioctl.h"
108 #include "ddk/wdm.h"
110 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
111 # include <sys/epoll.h>
112 # define USE_EPOLL
113 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
114 # define USE_EPOLL
115 # define EPOLLIN POLLIN
116 # define EPOLLOUT POLLOUT
117 # define EPOLLERR POLLERR
118 # define EPOLLHUP POLLHUP
119 # define EPOLL_CTL_ADD 1
120 # define EPOLL_CTL_DEL 2
121 # define EPOLL_CTL_MOD 3
123 typedef union epoll_data
125 void *ptr;
126 int fd;
127 uint32_t u32;
128 uint64_t u64;
129 } epoll_data_t;
131 struct epoll_event
133 uint32_t events;
134 epoll_data_t data;
137 static inline int epoll_create( int size )
139 return syscall( 254 /*NR_epoll_create*/, size );
142 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
144 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
147 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
149 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
152 #endif /* linux && __i386__ && HAVE_STDINT_H */
154 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
155 # include <port.h>
156 # define USE_EVENT_PORTS
157 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
159 /* Because of the stupid Posix locking semantics, we need to keep
160 * track of all file descriptors referencing a given file, and not
161 * close a single one until all the locks are gone (sigh).
164 /* file descriptor object */
166 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
167 struct closed_fd
169 struct list entry; /* entry in inode closed list */
170 int unix_fd; /* the unix file descriptor */
171 int unlink; /* whether to unlink on close: -1 - implicit FILE_DELETE_ON_CLOSE, 1 - explicit disposition */
172 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
175 struct fd
177 struct object obj; /* object header */
178 const struct fd_ops *fd_ops; /* file descriptor operations */
179 struct inode *inode; /* inode that this fd belongs to */
180 struct list inode_entry; /* entry in inode fd list */
181 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
182 struct object *user; /* object using this file descriptor */
183 struct list locks; /* list of locks on this fd */
184 unsigned int access; /* file access (FILE_READ_DATA etc.) */
185 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
186 unsigned int sharing; /* file sharing mode */
187 char *unix_name; /* unix file name */
188 WCHAR *nt_name; /* NT file name */
189 data_size_t nt_namelen; /* length of NT file name */
190 int unix_fd; /* unix file descriptor */
191 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
192 unsigned int cacheable :1;/* can the fd be cached on the client side? */
193 unsigned int signaled :1; /* is the fd signaled? */
194 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
195 int poll_index; /* index of fd in poll array */
196 struct async_queue read_q; /* async readers of this fd */
197 struct async_queue write_q; /* async writers of this fd */
198 struct async_queue wait_q; /* other async waiters of this fd */
199 struct completion *completion; /* completion object attached to this fd */
200 apc_param_t comp_key; /* completion key to set in completion events */
201 unsigned int comp_flags; /* completion flags */
204 static void fd_dump( struct object *obj, int verbose );
205 static void fd_destroy( struct object *obj );
207 static const struct object_ops fd_ops =
209 sizeof(struct fd), /* size */
210 &no_type, /* type */
211 fd_dump, /* dump */
212 no_add_queue, /* add_queue */
213 NULL, /* remove_queue */
214 NULL, /* signaled */
215 NULL, /* satisfied */
216 no_signal, /* signal */
217 no_get_fd, /* get_fd */
218 default_map_access, /* map_access */
219 default_get_sd, /* get_sd */
220 default_set_sd, /* set_sd */
221 no_get_full_name, /* get_full_name */
222 no_lookup_name, /* lookup_name */
223 no_link_name, /* link_name */
224 NULL, /* unlink_name */
225 no_open_file, /* open_file */
226 no_kernel_obj_list, /* get_kernel_obj_list */
227 no_close_handle, /* close_handle */
228 fd_destroy /* destroy */
231 /* device object */
233 #define DEVICE_HASH_SIZE 7
234 #define INODE_HASH_SIZE 17
236 struct device
238 struct object obj; /* object header */
239 struct list entry; /* entry in device hash list */
240 dev_t dev; /* device number */
241 int removable; /* removable device? (or -1 if unknown) */
242 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
245 static void device_dump( struct object *obj, int verbose );
246 static void device_destroy( struct object *obj );
248 static const struct object_ops device_ops =
250 sizeof(struct device), /* size */
251 &no_type, /* type */
252 device_dump, /* dump */
253 no_add_queue, /* add_queue */
254 NULL, /* remove_queue */
255 NULL, /* signaled */
256 NULL, /* satisfied */
257 no_signal, /* signal */
258 no_get_fd, /* get_fd */
259 default_map_access, /* map_access */
260 default_get_sd, /* get_sd */
261 default_set_sd, /* set_sd */
262 no_get_full_name, /* get_full_name */
263 no_lookup_name, /* lookup_name */
264 no_link_name, /* link_name */
265 NULL, /* unlink_name */
266 no_open_file, /* open_file */
267 no_kernel_obj_list, /* get_kernel_obj_list */
268 no_close_handle, /* close_handle */
269 device_destroy /* destroy */
272 /* inode object */
274 struct inode
276 struct object obj; /* object header */
277 struct list entry; /* inode hash list entry */
278 struct device *device; /* device containing this inode */
279 ino_t ino; /* inode number */
280 struct list open; /* list of open file descriptors */
281 struct list locks; /* list of file locks */
282 struct list closed; /* list of file descriptors to close at destroy time */
285 static void inode_dump( struct object *obj, int verbose );
286 static void inode_destroy( struct object *obj );
288 static const struct object_ops inode_ops =
290 sizeof(struct inode), /* size */
291 &no_type, /* type */
292 inode_dump, /* dump */
293 no_add_queue, /* add_queue */
294 NULL, /* remove_queue */
295 NULL, /* signaled */
296 NULL, /* satisfied */
297 no_signal, /* signal */
298 no_get_fd, /* get_fd */
299 default_map_access, /* map_access */
300 default_get_sd, /* get_sd */
301 default_set_sd, /* set_sd */
302 no_get_full_name, /* get_full_name */
303 no_lookup_name, /* lookup_name */
304 no_link_name, /* link_name */
305 NULL, /* unlink_name */
306 no_open_file, /* open_file */
307 no_kernel_obj_list, /* get_kernel_obj_list */
308 no_close_handle, /* close_handle */
309 inode_destroy /* destroy */
312 /* file lock object */
314 struct file_lock
316 struct object obj; /* object header */
317 struct fd *fd; /* fd owning this lock */
318 struct list fd_entry; /* entry in list of locks on a given fd */
319 struct list inode_entry; /* entry in inode list of locks */
320 int shared; /* shared lock? */
321 file_pos_t start; /* locked region is interval [start;end) */
322 file_pos_t end;
323 struct process *process; /* process owning this lock */
324 struct list proc_entry; /* entry in list of locks owned by the process */
327 static void file_lock_dump( struct object *obj, int verbose );
328 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
330 static const struct object_ops file_lock_ops =
332 sizeof(struct file_lock), /* size */
333 &no_type, /* type */
334 file_lock_dump, /* dump */
335 add_queue, /* add_queue */
336 remove_queue, /* remove_queue */
337 file_lock_signaled, /* signaled */
338 no_satisfied, /* satisfied */
339 no_signal, /* signal */
340 no_get_fd, /* get_fd */
341 default_map_access, /* map_access */
342 default_get_sd, /* get_sd */
343 default_set_sd, /* set_sd */
344 no_get_full_name, /* get_full_name */
345 no_lookup_name, /* lookup_name */
346 no_link_name, /* link_name */
347 NULL, /* unlink_name */
348 no_open_file, /* open_file */
349 no_kernel_obj_list, /* get_kernel_obj_list */
350 no_close_handle, /* close_handle */
351 no_destroy /* destroy */
355 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
356 #define FILE_POS_T_MAX (~(file_pos_t)0)
358 static file_pos_t max_unix_offset = OFF_T_MAX;
360 #define DUMP_LONG_LONG(val) do { \
361 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
362 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
363 else \
364 fprintf( stderr, "%lx", (unsigned long)(val) ); \
365 } while (0)
369 /****************************************************************/
370 /* timeouts support */
372 struct timeout_user
374 struct list entry; /* entry in sorted timeout list */
375 abstime_t when; /* timeout expiry */
376 timeout_callback callback; /* callback function */
377 void *private; /* callback private data */
380 static struct list abs_timeout_list = LIST_INIT(abs_timeout_list); /* sorted absolute timeouts list */
381 static struct list rel_timeout_list = LIST_INIT(rel_timeout_list); /* sorted relative timeouts list */
382 timeout_t current_time;
383 timeout_t monotonic_time;
385 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
386 static const int user_shared_data_timeout = 16;
388 static void atomic_store_ulong(volatile ULONG *ptr, ULONG value)
390 /* on x86 there should be total store order guarantees, so volatile is
391 * enough to ensure the stores aren't reordered by the compiler, and then
392 * they will always be seen in-order from other CPUs. On other archs, we
393 * need atomic intrinsics to guarantee that. */
394 #if defined(__i386__) || defined(__x86_64__)
395 *ptr = value;
396 #else
397 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
398 #endif
401 static void atomic_store_long(volatile LONG *ptr, LONG value)
403 #if defined(__i386__) || defined(__x86_64__)
404 *ptr = value;
405 #else
406 __atomic_store_n(ptr, value, __ATOMIC_SEQ_CST);
407 #endif
410 static void set_user_shared_data_time(void)
412 timeout_t tick_count = monotonic_time / 10000;
413 static timeout_t last_timezone_update;
414 timeout_t timezone_bias;
415 struct tm *tm;
416 time_t now;
418 if (monotonic_time - last_timezone_update > TICKS_PER_SEC)
420 now = time( NULL );
421 tm = gmtime( &now );
422 timezone_bias = mktime( tm ) - now;
423 tm = localtime( &now );
424 if (tm->tm_isdst) timezone_bias -= 3600;
425 timezone_bias *= TICKS_PER_SEC;
427 atomic_store_long(&user_shared_data->TimeZoneBias.High2Time, timezone_bias >> 32);
428 atomic_store_ulong(&user_shared_data->TimeZoneBias.LowPart, timezone_bias);
429 atomic_store_long(&user_shared_data->TimeZoneBias.High1Time, timezone_bias >> 32);
431 last_timezone_update = monotonic_time;
434 atomic_store_long(&user_shared_data->SystemTime.High2Time, current_time >> 32);
435 atomic_store_ulong(&user_shared_data->SystemTime.LowPart, current_time);
436 atomic_store_long(&user_shared_data->SystemTime.High1Time, current_time >> 32);
438 atomic_store_long(&user_shared_data->InterruptTime.High2Time, monotonic_time >> 32);
439 atomic_store_ulong(&user_shared_data->InterruptTime.LowPart, monotonic_time);
440 atomic_store_long(&user_shared_data->InterruptTime.High1Time, monotonic_time >> 32);
442 atomic_store_long(&user_shared_data->TickCount.High2Time, tick_count >> 32);
443 atomic_store_ulong(&user_shared_data->TickCount.LowPart, tick_count);
444 atomic_store_long(&user_shared_data->TickCount.High1Time, tick_count >> 32);
445 atomic_store_ulong(&user_shared_data->TickCountLowDeprecated, tick_count);
448 void set_current_time(void)
450 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
451 struct timeval now;
452 gettimeofday( &now, NULL );
453 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
454 monotonic_time = monotonic_counter();
455 if (user_shared_data) set_user_shared_data_time();
458 /* add a timeout user */
459 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
461 struct timeout_user *user;
462 struct list *ptr;
464 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
465 user->when = timeout_to_abstime( when );
466 user->callback = func;
467 user->private = private;
469 /* Now insert it in the linked list */
471 if (user->when > 0)
473 LIST_FOR_EACH( ptr, &abs_timeout_list )
475 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
476 if (timeout->when >= user->when) break;
479 else
481 LIST_FOR_EACH( ptr, &rel_timeout_list )
483 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
484 if (timeout->when <= user->when) break;
487 list_add_before( ptr, &user->entry );
488 return user;
491 /* remove a timeout user */
492 void remove_timeout_user( struct timeout_user *user )
494 list_remove( &user->entry );
495 free( user );
498 /* return a text description of a timeout for debugging purposes */
499 const char *get_timeout_str( timeout_t timeout )
501 static char buffer[64];
502 long secs, nsecs;
504 if (!timeout) return "0";
505 if (timeout == TIMEOUT_INFINITE) return "infinite";
507 if (timeout < 0) /* relative */
509 secs = -timeout / TICKS_PER_SEC;
510 nsecs = -timeout % TICKS_PER_SEC;
511 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
513 else /* absolute */
515 secs = (timeout - current_time) / TICKS_PER_SEC;
516 nsecs = (timeout - current_time) % TICKS_PER_SEC;
517 if (nsecs < 0)
519 nsecs += TICKS_PER_SEC;
520 secs--;
522 if (secs >= 0)
523 sprintf( buffer, "%x%08x (+%ld.%07ld)",
524 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
525 else
526 sprintf( buffer, "%x%08x (-%ld.%07ld)",
527 (unsigned int)(timeout >> 32), (unsigned int)timeout,
528 -(secs + 1), TICKS_PER_SEC - nsecs );
530 return buffer;
534 /****************************************************************/
535 /* poll support */
537 static struct fd **poll_users; /* users array */
538 static struct pollfd *pollfd; /* poll fd array */
539 static int nb_users; /* count of array entries actually in use */
540 static int active_users; /* current number of active users */
541 static int allocated_users; /* count of allocated entries in the array */
542 static struct fd **freelist; /* list of free entries in the array */
544 static int get_next_timeout(void);
546 static inline void fd_poll_event( struct fd *fd, int event )
548 fd->fd_ops->poll_event( fd, event );
551 #ifdef USE_EPOLL
553 static int epoll_fd = -1;
555 static inline void init_epoll(void)
557 epoll_fd = epoll_create( 128 );
560 /* set the events that epoll waits for on this fd; helper for set_fd_events */
561 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
563 struct epoll_event ev;
564 int ctl;
566 if (epoll_fd == -1) return;
568 if (events == -1) /* stop waiting on this fd completely */
570 if (pollfd[user].fd == -1) return; /* already removed */
571 ctl = EPOLL_CTL_DEL;
573 else if (pollfd[user].fd == -1)
575 ctl = EPOLL_CTL_ADD;
577 else
579 if (pollfd[user].events == events) return; /* nothing to do */
580 ctl = EPOLL_CTL_MOD;
583 ev.events = events;
584 memset(&ev.data, 0, sizeof(ev.data));
585 ev.data.u32 = user;
587 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
589 if (errno == ENOMEM) /* not enough memory, give up on epoll */
591 close( epoll_fd );
592 epoll_fd = -1;
594 else perror( "epoll_ctl" ); /* should not happen */
598 static inline void remove_epoll_user( struct fd *fd, int user )
600 if (epoll_fd == -1) return;
602 if (pollfd[user].fd != -1)
604 struct epoll_event dummy;
605 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
609 static inline void main_loop_epoll(void)
611 int i, ret, timeout;
612 struct epoll_event events[128];
614 assert( POLLIN == EPOLLIN );
615 assert( POLLOUT == EPOLLOUT );
616 assert( POLLERR == EPOLLERR );
617 assert( POLLHUP == EPOLLHUP );
619 if (epoll_fd == -1) return;
621 while (active_users)
623 timeout = get_next_timeout();
625 if (!active_users) break; /* last user removed by a timeout */
626 if (epoll_fd == -1) break; /* an error occurred with epoll */
628 ret = epoll_wait( epoll_fd, events, ARRAY_SIZE( events ), timeout );
629 set_current_time();
631 /* put the events into the pollfd array first, like poll does */
632 for (i = 0; i < ret; i++)
634 int user = events[i].data.u32;
635 pollfd[user].revents = events[i].events;
638 /* read events from the pollfd array, as set_fd_events may modify them */
639 for (i = 0; i < ret; i++)
641 int user = events[i].data.u32;
642 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
647 #elif defined(HAVE_KQUEUE)
649 static int kqueue_fd = -1;
651 static inline void init_epoll(void)
653 kqueue_fd = kqueue();
656 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
658 struct kevent ev[2];
660 if (kqueue_fd == -1) return;
662 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)(long)user );
663 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)(long)user );
665 if (events == -1) /* stop waiting on this fd completely */
667 if (pollfd[user].fd == -1) return; /* already removed */
668 ev[0].flags |= EV_DELETE;
669 ev[1].flags |= EV_DELETE;
671 else if (pollfd[user].fd == -1)
673 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
674 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
676 else
678 if (pollfd[user].events == events) return; /* nothing to do */
679 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
680 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
683 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
685 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
687 close( kqueue_fd );
688 kqueue_fd = -1;
690 else perror( "kevent" ); /* should not happen */
694 static inline void remove_epoll_user( struct fd *fd, int user )
696 if (kqueue_fd == -1) return;
698 if (pollfd[user].fd != -1)
700 struct kevent ev[2];
702 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
703 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
704 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
708 static inline void main_loop_epoll(void)
710 int i, ret, timeout;
711 struct kevent events[128];
713 if (kqueue_fd == -1) return;
715 while (active_users)
717 timeout = get_next_timeout();
719 if (!active_users) break; /* last user removed by a timeout */
720 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
722 if (timeout != -1)
724 struct timespec ts;
726 ts.tv_sec = timeout / 1000;
727 ts.tv_nsec = (timeout % 1000) * 1000000;
728 ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), &ts );
730 else ret = kevent( kqueue_fd, NULL, 0, events, ARRAY_SIZE( events ), NULL );
732 set_current_time();
734 /* put the events into the pollfd array first, like poll does */
735 for (i = 0; i < ret; i++)
737 long user = (long)events[i].udata;
738 pollfd[user].revents = 0;
740 for (i = 0; i < ret; i++)
742 long user = (long)events[i].udata;
743 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
744 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
745 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
746 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
749 /* read events from the pollfd array, as set_fd_events may modify them */
750 for (i = 0; i < ret; i++)
752 long user = (long)events[i].udata;
753 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
754 pollfd[user].revents = 0;
759 #elif defined(USE_EVENT_PORTS)
761 static int port_fd = -1;
763 static inline void init_epoll(void)
765 port_fd = port_create();
768 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
770 int ret;
772 if (port_fd == -1) return;
774 if (events == -1) /* stop waiting on this fd completely */
776 if (pollfd[user].fd == -1) return; /* already removed */
777 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
779 else if (pollfd[user].fd == -1)
781 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
783 else
785 if (pollfd[user].events == events) return; /* nothing to do */
786 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
789 if (ret == -1)
791 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
793 close( port_fd );
794 port_fd = -1;
796 else perror( "port_associate" ); /* should not happen */
800 static inline void remove_epoll_user( struct fd *fd, int user )
802 if (port_fd == -1) return;
804 if (pollfd[user].fd != -1)
806 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
810 static inline void main_loop_epoll(void)
812 int i, nget, ret, timeout;
813 port_event_t events[128];
815 if (port_fd == -1) return;
817 while (active_users)
819 timeout = get_next_timeout();
820 nget = 1;
822 if (!active_users) break; /* last user removed by a timeout */
823 if (port_fd == -1) break; /* an error occurred with event completion */
825 if (timeout != -1)
827 struct timespec ts;
829 ts.tv_sec = timeout / 1000;
830 ts.tv_nsec = (timeout % 1000) * 1000000;
831 ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, &ts );
833 else ret = port_getn( port_fd, events, ARRAY_SIZE( events ), &nget, NULL );
835 if (ret == -1) break; /* an error occurred with event completion */
837 set_current_time();
839 /* put the events into the pollfd array first, like poll does */
840 for (i = 0; i < nget; i++)
842 long user = (long)events[i].portev_user;
843 pollfd[user].revents = events[i].portev_events;
846 /* read events from the pollfd array, as set_fd_events may modify them */
847 for (i = 0; i < nget; i++)
849 long user = (long)events[i].portev_user;
850 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
851 /* if we are still interested, reassociate the fd */
852 if (pollfd[user].fd != -1) {
853 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
859 #else /* HAVE_KQUEUE */
861 static inline void init_epoll(void) { }
862 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
863 static inline void remove_epoll_user( struct fd *fd, int user ) { }
864 static inline void main_loop_epoll(void) { }
866 #endif /* USE_EPOLL */
869 /* add a user in the poll array and return its index, or -1 on failure */
870 static int add_poll_user( struct fd *fd )
872 int ret;
873 if (freelist)
875 ret = freelist - poll_users;
876 freelist = (struct fd **)poll_users[ret];
878 else
880 if (nb_users == allocated_users)
882 struct fd **newusers;
883 struct pollfd *newpoll;
884 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
885 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
886 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
888 if (allocated_users)
889 poll_users = newusers;
890 else
891 free( newusers );
892 return -1;
894 poll_users = newusers;
895 pollfd = newpoll;
896 if (!allocated_users) init_epoll();
897 allocated_users = new_count;
899 ret = nb_users++;
901 pollfd[ret].fd = -1;
902 pollfd[ret].events = 0;
903 pollfd[ret].revents = 0;
904 poll_users[ret] = fd;
905 active_users++;
906 return ret;
909 /* remove a user from the poll list */
910 static void remove_poll_user( struct fd *fd, int user )
912 assert( user >= 0 );
913 assert( poll_users[user] == fd );
915 remove_epoll_user( fd, user );
916 pollfd[user].fd = -1;
917 pollfd[user].events = 0;
918 pollfd[user].revents = 0;
919 poll_users[user] = (struct fd *)freelist;
920 freelist = &poll_users[user];
921 active_users--;
924 /* process pending timeouts and return the time until the next timeout, in milliseconds */
925 static int get_next_timeout(void)
927 int ret = user_shared_data ? user_shared_data_timeout : -1;
929 if (!list_empty( &abs_timeout_list ) || !list_empty( &rel_timeout_list ))
931 struct list expired_list, *ptr;
933 /* first remove all expired timers from the list */
935 list_init( &expired_list );
936 while ((ptr = list_head( &abs_timeout_list )) != NULL)
938 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
940 if (timeout->when <= current_time)
942 list_remove( &timeout->entry );
943 list_add_tail( &expired_list, &timeout->entry );
945 else break;
947 while ((ptr = list_head( &rel_timeout_list )) != NULL)
949 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
951 if (-timeout->when <= monotonic_time)
953 list_remove( &timeout->entry );
954 list_add_tail( &expired_list, &timeout->entry );
956 else break;
959 /* now call the callback for all the removed timers */
961 while ((ptr = list_head( &expired_list )) != NULL)
963 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
964 list_remove( &timeout->entry );
965 timeout->callback( timeout->private );
966 free( timeout );
969 if ((ptr = list_head( &abs_timeout_list )) != NULL)
971 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
972 timeout_t diff = (timeout->when - current_time + 9999) / 10000;
973 if (diff > INT_MAX) diff = INT_MAX;
974 else if (diff < 0) diff = 0;
975 if (ret == -1 || diff < ret) ret = diff;
978 if ((ptr = list_head( &rel_timeout_list )) != NULL)
980 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
981 timeout_t diff = (-timeout->when - monotonic_time + 9999) / 10000;
982 if (diff > INT_MAX) diff = INT_MAX;
983 else if (diff < 0) diff = 0;
984 if (ret == -1 || diff < ret) ret = diff;
987 return ret;
990 /* server main poll() loop */
991 void main_loop(void)
993 int i, ret, timeout;
995 set_current_time();
996 server_start_time = current_time;
998 main_loop_epoll();
999 /* fall through to normal poll loop */
1001 while (active_users)
1003 timeout = get_next_timeout();
1005 if (!active_users) break; /* last user removed by a timeout */
1007 ret = poll( pollfd, nb_users, timeout );
1008 set_current_time();
1010 if (ret > 0)
1012 for (i = 0; i < nb_users; i++)
1014 if (pollfd[i].revents)
1016 fd_poll_event( poll_users[i], pollfd[i].revents );
1017 if (!--ret) break;
1025 /****************************************************************/
1026 /* device functions */
1028 static struct list device_hash[DEVICE_HASH_SIZE];
1030 static int is_device_removable( dev_t dev, int unix_fd )
1032 #if defined(linux) && defined(HAVE_FSTATFS)
1033 struct statfs stfs;
1035 /* check for floppy disk */
1036 if (major(dev) == FLOPPY_MAJOR) return 1;
1038 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1039 return (stfs.f_type == 0x9660 || /* iso9660 */
1040 stfs.f_type == 0x9fa1 || /* supermount */
1041 stfs.f_type == 0x15013346); /* udf */
1042 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
1043 struct statfs stfs;
1045 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
1046 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1047 #elif defined(__NetBSD__)
1048 struct statvfs stfs;
1050 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
1051 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
1052 #elif defined(sun)
1053 # include <sys/dkio.h>
1054 # include <sys/vtoc.h>
1055 struct dk_cinfo dkinf;
1056 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
1057 return (dkinf.dki_ctype == DKC_CDROM ||
1058 dkinf.dki_ctype == DKC_NCRFLOPPY ||
1059 dkinf.dki_ctype == DKC_SMSFLOPPY ||
1060 dkinf.dki_ctype == DKC_INTEL82072 ||
1061 dkinf.dki_ctype == DKC_INTEL82077);
1062 #else
1063 return 0;
1064 #endif
1067 /* retrieve the device object for a given fd, creating it if needed */
1068 static struct device *get_device( dev_t dev, int unix_fd )
1070 struct device *device;
1071 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
1073 if (device_hash[hash].next)
1075 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
1076 if (device->dev == dev) return (struct device *)grab_object( device );
1078 else list_init( &device_hash[hash] );
1080 /* not found, create it */
1082 if (unix_fd == -1) return NULL;
1083 if ((device = alloc_object( &device_ops )))
1085 device->dev = dev;
1086 device->removable = is_device_removable( dev, unix_fd );
1087 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
1088 list_add_head( &device_hash[hash], &device->entry );
1090 return device;
1093 static void device_dump( struct object *obj, int verbose )
1095 struct device *device = (struct device *)obj;
1096 fprintf( stderr, "Device dev=" );
1097 DUMP_LONG_LONG( device->dev );
1098 fprintf( stderr, "\n" );
1101 static void device_destroy( struct object *obj )
1103 struct device *device = (struct device *)obj;
1104 unsigned int i;
1106 for (i = 0; i < INODE_HASH_SIZE; i++)
1107 assert( list_empty(&device->inode_hash[i]) );
1109 list_remove( &device->entry ); /* remove it from the hash table */
1113 /****************************************************************/
1114 /* inode functions */
1116 /* close all pending file descriptors in the closed list */
1117 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1119 struct list *ptr = list_head( &inode->closed );
1121 while (ptr)
1123 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1124 struct list *next = list_next( &inode->closed, ptr );
1126 if (fd->unix_fd != -1)
1128 close( fd->unix_fd );
1129 fd->unix_fd = -1;
1131 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1133 list_remove( ptr );
1134 free( fd->unix_name );
1135 free( fd );
1137 ptr = next;
1141 static void inode_dump( struct object *obj, int verbose )
1143 struct inode *inode = (struct inode *)obj;
1144 fprintf( stderr, "Inode device=%p ino=", inode->device );
1145 DUMP_LONG_LONG( inode->ino );
1146 fprintf( stderr, "\n" );
1149 static void inode_destroy( struct object *obj )
1151 struct inode *inode = (struct inode *)obj;
1152 struct list *ptr;
1154 assert( list_empty(&inode->open) );
1155 assert( list_empty(&inode->locks) );
1157 list_remove( &inode->entry );
1159 while ((ptr = list_head( &inode->closed )))
1161 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1162 list_remove( ptr );
1163 if (fd->unix_fd != -1) close( fd->unix_fd );
1164 if (fd->unlink)
1166 /* make sure it is still the same file */
1167 struct stat st;
1168 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1170 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1171 else unlink( fd->unix_name );
1174 free( fd->unix_name );
1175 free( fd );
1177 release_object( inode->device );
1180 /* retrieve the inode object for a given fd, creating it if needed */
1181 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1183 struct device *device;
1184 struct inode *inode;
1185 unsigned int hash = ino % INODE_HASH_SIZE;
1187 if (!(device = get_device( dev, unix_fd ))) return NULL;
1189 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1191 if (inode->ino == ino)
1193 release_object( device );
1194 return (struct inode *)grab_object( inode );
1198 /* not found, create it */
1199 if ((inode = alloc_object( &inode_ops )))
1201 inode->device = device;
1202 inode->ino = ino;
1203 list_init( &inode->open );
1204 list_init( &inode->locks );
1205 list_init( &inode->closed );
1206 list_add_head( &device->inode_hash[hash], &inode->entry );
1208 else release_object( device );
1210 return inode;
1213 /* add fd to the inode list of file descriptors to close */
1214 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1216 if (!list_empty( &inode->locks ))
1218 list_add_head( &inode->closed, &fd->entry );
1220 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1222 if (fd->unix_fd != -1) close( fd->unix_fd );
1223 fd->unix_fd = -1;
1224 list_add_head( &inode->closed, &fd->entry );
1226 else /* no locks on this inode and no unlink, get rid of the fd */
1228 if (fd->unix_fd != -1) close( fd->unix_fd );
1229 free( fd->unix_name );
1230 free( fd );
1235 /****************************************************************/
1236 /* file lock functions */
1238 static void file_lock_dump( struct object *obj, int verbose )
1240 struct file_lock *lock = (struct file_lock *)obj;
1241 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1242 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1243 DUMP_LONG_LONG( lock->start );
1244 fprintf( stderr, " end=" );
1245 DUMP_LONG_LONG( lock->end );
1246 fprintf( stderr, "\n" );
1249 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1251 struct file_lock *lock = (struct file_lock *)obj;
1252 /* lock is signaled if it has lost its owner */
1253 return !lock->process;
1256 /* set (or remove) a Unix lock if possible for the given range */
1257 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1259 struct flock fl;
1261 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1262 for (;;)
1264 if (start == end) return 1; /* can't set zero-byte lock */
1265 if (start > max_unix_offset) return 1; /* ignore it */
1266 fl.l_type = type;
1267 fl.l_whence = SEEK_SET;
1268 fl.l_start = start;
1269 if (!end || end > max_unix_offset) fl.l_len = 0;
1270 else fl.l_len = end - start;
1271 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1273 switch(errno)
1275 case EACCES:
1276 /* check whether locks work at all on this file system */
1277 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1279 set_error( STATUS_FILE_LOCK_CONFLICT );
1280 return 0;
1282 /* fall through */
1283 case EIO:
1284 case ENOLCK:
1285 case ENOTSUP:
1286 /* no locking on this fs, just ignore it */
1287 fd->fs_locks = 0;
1288 return 1;
1289 case EAGAIN:
1290 set_error( STATUS_FILE_LOCK_CONFLICT );
1291 return 0;
1292 case EBADF:
1293 /* this can happen if we try to set a write lock on a read-only file */
1294 /* try to at least grab a read lock */
1295 if (fl.l_type == F_WRLCK)
1297 type = F_RDLCK;
1298 break; /* retry */
1300 set_error( STATUS_ACCESS_DENIED );
1301 return 0;
1302 #ifdef EOVERFLOW
1303 case EOVERFLOW:
1304 #endif
1305 case EINVAL:
1306 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1307 /* in that case we shrink the limit and retry */
1308 if (max_unix_offset > INT_MAX)
1310 max_unix_offset = INT_MAX;
1311 break; /* retry */
1313 /* fall through */
1314 default:
1315 file_set_error();
1316 return 0;
1321 /* check if interval [start;end) overlaps the lock */
1322 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1324 if (lock->end && start >= lock->end) return 0;
1325 if (end && lock->start >= end) return 0;
1326 return 1;
1329 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1330 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1332 struct hole
1334 struct hole *next;
1335 struct hole *prev;
1336 file_pos_t start;
1337 file_pos_t end;
1338 } *first, *cur, *next, *buffer;
1340 struct list *ptr;
1341 int count = 0;
1343 if (!fd->inode) return;
1344 if (!fd->fs_locks) return;
1345 if (start == end || start > max_unix_offset) return;
1346 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1348 /* count the number of locks overlapping the specified area */
1350 LIST_FOR_EACH( ptr, &fd->inode->locks )
1352 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1353 if (lock->start == lock->end) continue;
1354 if (lock_overlaps( lock, start, end )) count++;
1357 if (!count) /* no locks at all, we can unlock everything */
1359 set_unix_lock( fd, start, end, F_UNLCK );
1360 return;
1363 /* allocate space for the list of holes */
1364 /* max. number of holes is number of locks + 1 */
1366 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1367 first = buffer;
1368 first->next = NULL;
1369 first->prev = NULL;
1370 first->start = start;
1371 first->end = end;
1372 next = first + 1;
1374 /* build a sorted list of unlocked holes in the specified area */
1376 LIST_FOR_EACH( ptr, &fd->inode->locks )
1378 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1379 if (lock->start == lock->end) continue;
1380 if (!lock_overlaps( lock, start, end )) continue;
1382 /* go through all the holes touched by this lock */
1383 for (cur = first; cur; cur = cur->next)
1385 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1386 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1388 /* now we know that lock is overlapping hole */
1390 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1392 cur->start = lock->end;
1393 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1394 /* now hole is empty, remove it */
1395 if (cur->next) cur->next->prev = cur->prev;
1396 if (cur->prev) cur->prev->next = cur->next;
1397 else if (!(first = cur->next)) goto done; /* no more holes at all */
1399 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1401 cur->end = lock->start;
1402 assert( cur->start < cur->end );
1404 else /* lock is in the middle of hole, split hole in two */
1406 next->prev = cur;
1407 next->next = cur->next;
1408 cur->next = next;
1409 next->start = lock->end;
1410 next->end = cur->end;
1411 cur->end = lock->start;
1412 assert( next->start < next->end );
1413 assert( cur->end < next->start );
1414 next++;
1415 break; /* done with this lock */
1420 /* clear Unix locks for all the holes */
1422 for (cur = first; cur; cur = cur->next)
1423 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1425 done:
1426 free( buffer );
1429 /* create a new lock on a fd */
1430 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1432 struct file_lock *lock;
1434 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1435 lock->shared = shared;
1436 lock->start = start;
1437 lock->end = end;
1438 lock->fd = fd;
1439 lock->process = current->process;
1441 /* now try to set a Unix lock */
1442 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1444 release_object( lock );
1445 return NULL;
1447 list_add_tail( &fd->locks, &lock->fd_entry );
1448 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1449 list_add_tail( &lock->process->locks, &lock->proc_entry );
1450 return lock;
1453 /* remove an existing lock */
1454 static void remove_lock( struct file_lock *lock, int remove_unix )
1456 struct inode *inode = lock->fd->inode;
1458 list_remove( &lock->fd_entry );
1459 list_remove( &lock->inode_entry );
1460 list_remove( &lock->proc_entry );
1461 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1462 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1463 lock->process = NULL;
1464 wake_up( &lock->obj, 0 );
1465 release_object( lock );
1468 /* remove all locks owned by a given process */
1469 void remove_process_locks( struct process *process )
1471 struct list *ptr;
1473 while ((ptr = list_head( &process->locks )))
1475 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1476 remove_lock( lock, 1 ); /* this removes it from the list */
1480 /* remove all locks on a given fd */
1481 static void remove_fd_locks( struct fd *fd )
1483 file_pos_t start = FILE_POS_T_MAX, end = 0;
1484 struct list *ptr;
1486 while ((ptr = list_head( &fd->locks )))
1488 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1489 if (lock->start < start) start = lock->start;
1490 if (!lock->end || lock->end > end) end = lock->end - 1;
1491 remove_lock( lock, 0 );
1493 if (start < end) remove_unix_locks( fd, start, end + 1 );
1496 /* add a lock on an fd */
1497 /* returns handle to wait on */
1498 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1500 struct list *ptr;
1501 file_pos_t end = start + count;
1503 if (!fd->inode) /* not a regular file */
1505 set_error( STATUS_INVALID_DEVICE_REQUEST );
1506 return 0;
1509 /* don't allow wrapping locks */
1510 if (end && end < start)
1512 set_error( STATUS_INVALID_PARAMETER );
1513 return 0;
1516 /* check if another lock on that file overlaps the area */
1517 LIST_FOR_EACH( ptr, &fd->inode->locks )
1519 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1520 if (!lock_overlaps( lock, start, end )) continue;
1521 if (shared && (lock->shared || lock->fd == fd)) continue;
1522 /* found one */
1523 if (!wait)
1525 set_error( STATUS_FILE_LOCK_CONFLICT );
1526 return 0;
1528 set_error( STATUS_PENDING );
1529 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1532 /* not found, add it */
1533 if (add_lock( fd, shared, start, end )) return 0;
1534 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1536 /* Unix lock conflict -> tell client to wait and retry */
1537 if (wait) set_error( STATUS_PENDING );
1539 return 0;
1542 /* remove a lock on an fd */
1543 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1545 struct list *ptr;
1546 file_pos_t end = start + count;
1548 /* find an existing lock with the exact same parameters */
1549 LIST_FOR_EACH( ptr, &fd->locks )
1551 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1552 if ((lock->start == start) && (lock->end == end))
1554 remove_lock( lock, 1 );
1555 return;
1558 set_error( STATUS_FILE_LOCK_CONFLICT );
1562 /****************************************************************/
1563 /* file descriptor functions */
1565 static void fd_dump( struct object *obj, int verbose )
1567 struct fd *fd = (struct fd *)obj;
1568 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1569 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1570 fprintf( stderr, "\n" );
1573 static void fd_destroy( struct object *obj )
1575 struct fd *fd = (struct fd *)obj;
1577 free_async_queue( &fd->read_q );
1578 free_async_queue( &fd->write_q );
1579 free_async_queue( &fd->wait_q );
1581 if (fd->completion) release_object( fd->completion );
1582 remove_fd_locks( fd );
1583 list_remove( &fd->inode_entry );
1584 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1585 free( fd->nt_name );
1586 if (fd->inode)
1588 inode_add_closed_fd( fd->inode, fd->closed );
1589 release_object( fd->inode );
1591 else /* no inode, close it right away */
1593 if (fd->unix_fd != -1) close( fd->unix_fd );
1594 free( fd->unix_name );
1598 /* check if the desired access is possible without violating */
1599 /* the sharing mode of other opens of the same file */
1600 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1601 unsigned int open_flags, unsigned int options )
1603 /* only a few access bits are meaningful wrt sharing */
1604 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1605 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1606 const unsigned int all_access = read_access | write_access | DELETE;
1608 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1609 unsigned int existing_access = 0;
1610 struct list *ptr;
1612 fd->access = access;
1613 fd->sharing = sharing;
1615 LIST_FOR_EACH( ptr, &fd->inode->open )
1617 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1618 if (fd_ptr != fd)
1620 /* if access mode is 0, sharing mode is ignored */
1621 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1622 existing_access |= fd_ptr->access;
1626 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1627 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1628 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1629 return STATUS_SHARING_VIOLATION;
1630 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1631 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1632 return STATUS_SHARING_VIOLATION;
1633 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1634 return STATUS_CANNOT_DELETE;
1635 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1636 return STATUS_USER_MAPPED_FILE;
1637 if (!(access & all_access))
1638 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1639 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1640 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1641 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1642 return STATUS_SHARING_VIOLATION;
1643 return 0;
1646 /* set the events that select waits for on this fd */
1647 void set_fd_events( struct fd *fd, int events )
1649 int user = fd->poll_index;
1650 assert( poll_users[user] == fd );
1652 set_fd_epoll_events( fd, user, events );
1654 if (events == -1) /* stop waiting on this fd completely */
1656 pollfd[user].fd = -1;
1657 pollfd[user].events = POLLERR;
1658 pollfd[user].revents = 0;
1660 else
1662 pollfd[user].fd = fd->unix_fd;
1663 pollfd[user].events = events;
1667 /* prepare an fd for unmounting its corresponding device */
1668 static inline void unmount_fd( struct fd *fd )
1670 assert( fd->inode );
1672 async_wake_up( &fd->read_q, STATUS_VOLUME_DISMOUNTED );
1673 async_wake_up( &fd->write_q, STATUS_VOLUME_DISMOUNTED );
1675 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1677 if (fd->unix_fd != -1) close( fd->unix_fd );
1679 fd->unix_fd = -1;
1680 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1681 fd->closed->unix_fd = -1;
1682 fd->closed->unlink = 0;
1684 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1685 fd->fs_locks = 0;
1688 /* allocate an fd object, without setting the unix fd yet */
1689 static struct fd *alloc_fd_object(void)
1691 struct fd *fd = alloc_object( &fd_ops );
1693 if (!fd) return NULL;
1695 fd->fd_ops = NULL;
1696 fd->user = NULL;
1697 fd->inode = NULL;
1698 fd->closed = NULL;
1699 fd->access = 0;
1700 fd->options = 0;
1701 fd->sharing = 0;
1702 fd->unix_fd = -1;
1703 fd->unix_name = NULL;
1704 fd->nt_name = NULL;
1705 fd->nt_namelen = 0;
1706 fd->cacheable = 0;
1707 fd->signaled = 1;
1708 fd->fs_locks = 1;
1709 fd->poll_index = -1;
1710 fd->completion = NULL;
1711 fd->comp_flags = 0;
1712 init_async_queue( &fd->read_q );
1713 init_async_queue( &fd->write_q );
1714 init_async_queue( &fd->wait_q );
1715 list_init( &fd->inode_entry );
1716 list_init( &fd->locks );
1718 if ((fd->poll_index = add_poll_user( fd )) == -1)
1720 release_object( fd );
1721 return NULL;
1723 return fd;
1726 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1727 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1729 struct fd *fd = alloc_object( &fd_ops );
1731 if (!fd) return NULL;
1733 fd->fd_ops = fd_user_ops;
1734 fd->user = user;
1735 fd->inode = NULL;
1736 fd->closed = NULL;
1737 fd->access = 0;
1738 fd->options = options;
1739 fd->sharing = 0;
1740 fd->unix_name = NULL;
1741 fd->nt_name = NULL;
1742 fd->nt_namelen = 0;
1743 fd->unix_fd = -1;
1744 fd->cacheable = 0;
1745 fd->signaled = 1;
1746 fd->fs_locks = 0;
1747 fd->poll_index = -1;
1748 fd->completion = NULL;
1749 fd->comp_flags = 0;
1750 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1751 init_async_queue( &fd->read_q );
1752 init_async_queue( &fd->write_q );
1753 init_async_queue( &fd->wait_q );
1754 list_init( &fd->inode_entry );
1755 list_init( &fd->locks );
1756 return fd;
1759 /* duplicate an fd object for a different user */
1760 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1762 unsigned int err;
1763 struct fd *fd = alloc_fd_object();
1765 if (!fd) return NULL;
1767 fd->options = options;
1768 fd->cacheable = orig->cacheable;
1770 if (orig->unix_name)
1772 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1773 strcpy( fd->unix_name, orig->unix_name );
1775 if (orig->nt_namelen)
1777 if (!(fd->nt_name = memdup( orig->nt_name, orig->nt_namelen ))) goto failed;
1778 fd->nt_namelen = orig->nt_namelen;
1781 if (orig->inode)
1783 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1784 if (!closed) goto failed;
1785 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1787 file_set_error();
1788 free( closed );
1789 goto failed;
1791 closed->unix_fd = fd->unix_fd;
1792 closed->unlink = 0;
1793 closed->unix_name = fd->unix_name;
1794 fd->closed = closed;
1795 fd->inode = (struct inode *)grab_object( orig->inode );
1796 list_add_head( &fd->inode->open, &fd->inode_entry );
1797 if ((err = check_sharing( fd, access, sharing, 0, options )))
1799 set_error( err );
1800 goto failed;
1803 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1805 file_set_error();
1806 goto failed;
1808 return fd;
1810 failed:
1811 release_object( fd );
1812 return NULL;
1815 /* find an existing fd object that can be reused for a mapping */
1816 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1818 struct fd *fd_ptr;
1820 if (!fd->inode) return NULL;
1822 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1823 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1824 return (struct fd *)grab_object( fd_ptr );
1826 return NULL;
1829 /* sets the user of an fd that previously had no user */
1830 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1832 assert( fd->fd_ops == NULL );
1833 fd->fd_ops = user_ops;
1834 fd->user = user;
1837 char *dup_fd_name( struct fd *root, const char *name )
1839 char *ret;
1841 if (!root) return strdup( name );
1842 if (!root->unix_name) return NULL;
1844 /* skip . prefix */
1845 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1847 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1849 strcpy( ret, root->unix_name );
1850 if (name[0] && name[0] != '/') strcat( ret, "/" );
1851 strcat( ret, name );
1853 return ret;
1856 static WCHAR *dup_nt_name( struct fd *root, struct unicode_str name, data_size_t *len )
1858 WCHAR *ret;
1859 data_size_t retlen;
1861 if (!root)
1863 *len = name.len;
1864 if (!name.len) return NULL;
1865 return memdup( name.str, name.len );
1867 if (!root->nt_namelen) return NULL;
1868 retlen = root->nt_namelen;
1870 /* skip . prefix */
1871 if (name.len && name.str[0] == '.' && (name.len == sizeof(WCHAR) || name.str[1] == '\\'))
1873 name.str++;
1874 name.len -= sizeof(WCHAR);
1876 if ((ret = malloc( retlen + name.len + 1 )))
1878 memcpy( ret, root->nt_name, root->nt_namelen );
1879 if (name.len && name.str[0] != '\\' &&
1880 root->nt_namelen && root->nt_name[root->nt_namelen / sizeof(WCHAR) - 1] != '\\')
1882 ret[retlen / sizeof(WCHAR)] = '\\';
1883 retlen += sizeof(WCHAR);
1885 memcpy( ret + retlen / sizeof(WCHAR), name.str, name.len );
1886 *len = retlen + name.len;
1888 return ret;
1891 void get_nt_name( struct fd *fd, struct unicode_str *name )
1893 name->str = fd->nt_name;
1894 name->len = fd->nt_namelen;
1897 /* open() wrapper that returns a struct fd with no fd user set */
1898 struct fd *open_fd( struct fd *root, const char *name, struct unicode_str nt_name,
1899 int flags, mode_t *mode, unsigned int access,
1900 unsigned int sharing, unsigned int options )
1902 struct stat st;
1903 struct closed_fd *closed_fd;
1904 struct fd *fd;
1905 int root_fd = -1;
1906 int rw_mode;
1907 char *path;
1909 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1910 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1912 set_error( STATUS_INVALID_PARAMETER );
1913 return NULL;
1916 if (!(fd = alloc_fd_object())) return NULL;
1918 fd->options = options;
1919 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1921 release_object( fd );
1922 return NULL;
1925 if (root)
1927 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1928 if (fchdir( root_fd ) == -1)
1930 file_set_error();
1931 root_fd = -1;
1932 goto error;
1936 /* create the directory if needed */
1937 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1939 if (mkdir( name, *mode ) == -1)
1941 if (errno != EEXIST || (flags & O_EXCL))
1943 file_set_error();
1944 goto error;
1947 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1950 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1952 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1953 else rw_mode = O_WRONLY;
1955 else rw_mode = O_RDONLY;
1957 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1959 /* if we tried to open a directory for write access, retry read-only */
1960 if (errno == EISDIR)
1962 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1963 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1966 if (fd->unix_fd == -1)
1968 file_set_error();
1969 goto error;
1973 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
1974 fd->unix_name = NULL;
1975 if ((path = dup_fd_name( root, name )))
1977 fd->unix_name = realpath( path, NULL );
1978 free( path );
1981 closed_fd->unix_fd = fd->unix_fd;
1982 closed_fd->unlink = 0;
1983 closed_fd->unix_name = fd->unix_name;
1984 fstat( fd->unix_fd, &st );
1985 *mode = st.st_mode;
1987 /* only bother with an inode for normal files and directories */
1988 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1990 unsigned int err;
1991 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1993 if (!inode)
1995 /* we can close the fd because there are no others open on the same file,
1996 * otherwise we wouldn't have failed to allocate a new inode
1998 goto error;
2000 fd->inode = inode;
2001 fd->closed = closed_fd;
2002 fd->cacheable = !inode->device->removable;
2003 list_add_head( &inode->open, &fd->inode_entry );
2004 closed_fd = NULL;
2006 /* check directory options */
2007 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
2009 set_error( STATUS_NOT_A_DIRECTORY );
2010 goto error;
2012 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
2014 set_error( STATUS_FILE_IS_A_DIRECTORY );
2015 goto error;
2017 if ((err = check_sharing( fd, access, sharing, flags, options )))
2019 set_error( err );
2020 goto error;
2023 /* can't unlink files if we don't have permission to access */
2024 if ((options & FILE_DELETE_ON_CLOSE) && !(flags & O_CREAT) &&
2025 !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2027 set_error( STATUS_CANNOT_DELETE );
2028 goto error;
2031 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) ? -1 : 0;
2032 if (flags & O_TRUNC)
2034 if (S_ISDIR(st.st_mode))
2036 set_error( STATUS_OBJECT_NAME_COLLISION );
2037 goto error;
2039 ftruncate( fd->unix_fd, 0 );
2042 else /* special file */
2044 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
2046 set_error( STATUS_INVALID_PARAMETER );
2047 goto error;
2049 free( closed_fd );
2050 fd->cacheable = 1;
2053 #ifdef HAVE_POSIX_FADVISE
2054 switch (options & (FILE_SEQUENTIAL_ONLY | FILE_RANDOM_ACCESS))
2056 case FILE_SEQUENTIAL_ONLY:
2057 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_SEQUENTIAL );
2058 break;
2059 case FILE_RANDOM_ACCESS:
2060 posix_fadvise( fd->unix_fd, 0, 0, POSIX_FADV_RANDOM );
2061 break;
2063 #endif
2065 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2066 return fd;
2068 error:
2069 release_object( fd );
2070 free( closed_fd );
2071 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
2072 return NULL;
2075 /* create an fd for an anonymous file */
2076 /* if the function fails the unix fd is closed */
2077 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
2078 unsigned int options )
2080 struct fd *fd = alloc_fd_object();
2082 if (fd)
2084 set_fd_user( fd, fd_user_ops, user );
2085 fd->unix_fd = unix_fd;
2086 fd->options = options;
2087 return fd;
2089 close( unix_fd );
2090 return NULL;
2093 /* retrieve the object that is using an fd */
2094 void *get_fd_user( struct fd *fd )
2096 return fd->user;
2099 /* retrieve the opening options for the fd */
2100 unsigned int get_fd_options( struct fd *fd )
2102 return fd->options;
2105 /* retrieve the completion flags for the fd */
2106 unsigned int get_fd_comp_flags( struct fd *fd )
2108 return fd->comp_flags;
2111 /* check if fd is in overlapped mode */
2112 int is_fd_overlapped( struct fd *fd )
2114 return !(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
2117 /* retrieve the unix fd for an object */
2118 int get_unix_fd( struct fd *fd )
2120 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
2121 return fd->unix_fd;
2124 /* check if two file descriptors point to the same file */
2125 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
2127 return fd1->inode == fd2->inode;
2130 /* allow the fd to be cached (can't be reset once set) */
2131 void allow_fd_caching( struct fd *fd )
2133 fd->cacheable = 1;
2136 /* check if fd is on a removable device */
2137 int is_fd_removable( struct fd *fd )
2139 return (fd->inode && fd->inode->device->removable);
2142 /* set or clear the fd signaled state */
2143 void set_fd_signaled( struct fd *fd, int signaled )
2145 if (fd->comp_flags & FILE_SKIP_SET_EVENT_ON_HANDLE) return;
2146 fd->signaled = signaled;
2147 if (signaled) wake_up( fd->user, 0 );
2150 /* check if events are pending and if yes return which one(s) */
2151 int check_fd_events( struct fd *fd, int events )
2153 struct pollfd pfd;
2155 if (fd->unix_fd == -1) return POLLERR;
2156 if (fd->inode) return events; /* regular files are always signaled */
2158 pfd.fd = fd->unix_fd;
2159 pfd.events = events;
2160 if (poll( &pfd, 1, 0 ) <= 0) return 0;
2161 return pfd.revents;
2164 /* default signaled() routine for objects that poll() on an fd */
2165 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
2167 struct fd *fd = get_obj_fd( obj );
2168 int ret = fd->signaled;
2169 release_object( fd );
2170 return ret;
2173 int default_fd_get_poll_events( struct fd *fd )
2175 int events = 0;
2177 if (async_waiting( &fd->read_q )) events |= POLLIN;
2178 if (async_waiting( &fd->write_q )) events |= POLLOUT;
2179 return events;
2182 /* default handler for poll() events */
2183 void default_poll_event( struct fd *fd, int event )
2185 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( &fd->read_q, STATUS_ALERTED );
2186 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( &fd->write_q, STATUS_ALERTED );
2188 /* if an error occurred, stop polling this fd to avoid busy-looping */
2189 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2190 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2193 void fd_queue_async( struct fd *fd, struct async *async, int type )
2195 struct async_queue *queue;
2197 switch (type)
2199 case ASYNC_TYPE_READ:
2200 queue = &fd->read_q;
2201 break;
2202 case ASYNC_TYPE_WRITE:
2203 queue = &fd->write_q;
2204 break;
2205 case ASYNC_TYPE_WAIT:
2206 queue = &fd->wait_q;
2207 break;
2208 default:
2209 queue = NULL;
2210 assert(0);
2213 queue_async( queue, async );
2215 if (type != ASYNC_TYPE_WAIT)
2217 if (!fd->inode)
2218 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2219 else /* regular files are always ready for read and write */
2220 async_wake_up( queue, STATUS_ALERTED );
2224 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2226 switch (type)
2228 case ASYNC_TYPE_READ:
2229 async_wake_up( &fd->read_q, status );
2230 break;
2231 case ASYNC_TYPE_WRITE:
2232 async_wake_up( &fd->write_q, status );
2233 break;
2234 case ASYNC_TYPE_WAIT:
2235 async_wake_up( &fd->wait_q, status );
2236 break;
2237 default:
2238 assert(0);
2242 void fd_cancel_async( struct fd *fd, struct async *async )
2244 fd->fd_ops->cancel_async( fd, async );
2247 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2249 fd->fd_ops->reselect_async( fd, queue );
2252 void no_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2254 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2257 void default_fd_cancel_async( struct fd *fd, struct async *async )
2259 async_terminate( async, STATUS_CANCELLED );
2262 void default_fd_queue_async( struct fd *fd, struct async *async, int type, int count )
2264 fd_queue_async( fd, async, type );
2265 set_error( STATUS_PENDING );
2268 /* default reselect_async() fd routine */
2269 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2271 if (queue == &fd->read_q || queue == &fd->write_q)
2273 int poll_events = fd->fd_ops->get_poll_events( fd );
2274 int events = check_fd_events( fd, poll_events );
2275 if (events) fd->fd_ops->poll_event( fd, events );
2276 else set_fd_events( fd, poll_events );
2280 static inline int is_valid_mounted_device( struct stat *st )
2282 #if defined(linux) || defined(__sun__)
2283 return S_ISBLK( st->st_mode );
2284 #else
2285 /* disks are char devices on *BSD */
2286 return S_ISCHR( st->st_mode );
2287 #endif
2290 /* close all Unix file descriptors on a device to allow unmounting it */
2291 static void unmount_device( struct fd *device_fd )
2293 unsigned int i;
2294 struct stat st;
2295 struct device *device;
2296 struct inode *inode;
2297 struct fd *fd;
2298 int unix_fd = get_unix_fd( device_fd );
2300 if (unix_fd == -1) return;
2302 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2304 set_error( STATUS_INVALID_PARAMETER );
2305 return;
2308 if (!(device = get_device( st.st_rdev, -1 ))) return;
2310 for (i = 0; i < INODE_HASH_SIZE; i++)
2312 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2314 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2316 unmount_fd( fd );
2318 inode_close_pending( inode, 0 );
2321 /* remove it from the hash table */
2322 list_remove( &device->entry );
2323 list_init( &device->entry );
2324 release_object( device );
2327 /* default read() routine */
2328 void no_fd_read( struct fd *fd, struct async *async, file_pos_t pos )
2330 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2333 /* default write() routine */
2334 void no_fd_write( struct fd *fd, struct async *async, file_pos_t pos )
2336 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2339 /* default flush() routine */
2340 void no_fd_flush( struct fd *fd, struct async *async )
2342 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2345 /* default get_file_info() routine */
2346 void no_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2348 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2351 /* default get_file_info() routine */
2352 void default_fd_get_file_info( struct fd *fd, obj_handle_t handle, unsigned int info_class )
2354 switch (info_class)
2356 case FileAccessInformation:
2358 FILE_ACCESS_INFORMATION info;
2359 if (get_reply_max_size() < sizeof(info))
2361 set_error( STATUS_INFO_LENGTH_MISMATCH );
2362 return;
2364 info.AccessFlags = get_handle_access( current->process, handle );
2365 set_reply_data( &info, sizeof(info) );
2366 break;
2368 case FileModeInformation:
2370 FILE_MODE_INFORMATION info;
2371 if (get_reply_max_size() < sizeof(info))
2373 set_error( STATUS_INFO_LENGTH_MISMATCH );
2374 return;
2376 info.Mode = fd->options & ( FILE_WRITE_THROUGH
2377 | FILE_SEQUENTIAL_ONLY
2378 | FILE_NO_INTERMEDIATE_BUFFERING
2379 | FILE_SYNCHRONOUS_IO_ALERT
2380 | FILE_SYNCHRONOUS_IO_NONALERT );
2381 set_reply_data( &info, sizeof(info) );
2382 break;
2384 case FileIoCompletionNotificationInformation:
2386 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
2387 if (get_reply_max_size() < sizeof(info))
2389 set_error( STATUS_INFO_LENGTH_MISMATCH );
2390 return;
2392 info.Flags = fd->comp_flags;
2393 set_reply_data( &info, sizeof(info) );
2394 break;
2396 default:
2397 set_error( STATUS_NOT_IMPLEMENTED );
2401 /* default get_volume_info() routine */
2402 void no_fd_get_volume_info( struct fd *fd, struct async *async, unsigned int info_class )
2404 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2407 /* default ioctl() routine */
2408 void no_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2410 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2413 /* default ioctl() routine */
2414 void default_fd_ioctl( struct fd *fd, ioctl_code_t code, struct async *async )
2416 switch(code)
2418 case FSCTL_DISMOUNT_VOLUME:
2419 unmount_device( fd );
2420 break;
2422 default:
2423 set_error( STATUS_NOT_SUPPORTED );
2427 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2428 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2429 unsigned int access )
2431 struct fd *fd = NULL;
2432 struct object *obj;
2434 if ((obj = get_handle_obj( process, handle, access, NULL )))
2436 fd = get_obj_fd( obj );
2437 release_object( obj );
2439 return fd;
2442 static int is_dir_empty( int fd )
2444 DIR *dir;
2445 int empty;
2446 struct dirent *de;
2448 if ((fd = dup( fd )) == -1)
2449 return -1;
2451 if (!(dir = fdopendir( fd )))
2453 close( fd );
2454 return -1;
2457 empty = 1;
2458 while (empty && (de = readdir( dir )))
2460 if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2461 empty = 0;
2463 closedir( dir );
2464 return empty;
2467 /* set disposition for the fd */
2468 static void set_fd_disposition( struct fd *fd, int unlink )
2470 struct stat st;
2472 if (!fd->inode)
2474 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2475 return;
2478 if (fd->unix_fd == -1)
2480 set_error( fd->no_fd_status );
2481 return;
2484 if (unlink)
2486 struct fd *fd_ptr;
2488 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2490 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2492 set_error( STATUS_CANNOT_DELETE );
2493 return;
2497 if (fstat( fd->unix_fd, &st ) == -1)
2499 file_set_error();
2500 return;
2502 if (S_ISREG( st.st_mode )) /* can't unlink files we don't have permission to write */
2504 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2506 set_error( STATUS_CANNOT_DELETE );
2507 return;
2510 else if (S_ISDIR( st.st_mode )) /* can't remove non-empty directories */
2512 switch (is_dir_empty( fd->unix_fd ))
2514 case -1:
2515 file_set_error();
2516 return;
2517 case 0:
2518 set_error( STATUS_DIRECTORY_NOT_EMPTY );
2519 return;
2522 else /* can't unlink special files */
2524 set_error( STATUS_INVALID_PARAMETER );
2525 return;
2529 fd->closed->unlink = unlink ? 1 : 0;
2530 if (fd->options & FILE_DELETE_ON_CLOSE)
2531 fd->closed->unlink = -1;
2534 /* set new name for the fd */
2535 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr, data_size_t len,
2536 struct unicode_str nt_name, int create_link, int replace )
2538 struct inode *inode;
2539 struct stat st, st2;
2540 char *name;
2542 if (!fd->inode || !fd->unix_name)
2544 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2545 return;
2547 if (fd->unix_fd == -1)
2549 set_error( fd->no_fd_status );
2550 return;
2553 if (!len || ((nameptr[0] == '/') ^ !root))
2555 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2556 return;
2558 if (!(name = mem_alloc( len + 1 ))) return;
2559 memcpy( name, nameptr, len );
2560 name[len] = 0;
2562 if (root)
2564 char *combined_name = dup_fd_name( root, name );
2565 if (!combined_name)
2567 set_error( STATUS_NO_MEMORY );
2568 goto failed;
2570 free( name );
2571 name = combined_name;
2574 /* when creating a hard link, source cannot be a dir */
2575 if (create_link && !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2577 set_error( STATUS_FILE_IS_A_DIRECTORY );
2578 goto failed;
2581 if (!stat( name, &st ))
2583 if (!fstat( fd->unix_fd, &st2 ) && st.st_ino == st2.st_ino && st.st_dev == st2.st_dev)
2585 if (create_link && !replace) set_error( STATUS_OBJECT_NAME_COLLISION );
2586 free( name );
2587 return;
2590 if (!replace)
2592 set_error( STATUS_OBJECT_NAME_COLLISION );
2593 goto failed;
2596 /* can't replace directories or special files */
2597 if (!S_ISREG( st.st_mode ))
2599 set_error( STATUS_ACCESS_DENIED );
2600 goto failed;
2603 /* can't replace an opened file */
2604 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2606 int is_empty = list_empty( &inode->open );
2607 release_object( inode );
2608 if (!is_empty)
2610 set_error( STATUS_ACCESS_DENIED );
2611 goto failed;
2615 /* link() expects that the target doesn't exist */
2616 /* rename() cannot replace files with directories */
2617 if (create_link || S_ISDIR( st2.st_mode ))
2619 if (unlink( name ))
2621 file_set_error();
2622 goto failed;
2627 if (create_link)
2629 if (link( fd->unix_name, name ))
2630 file_set_error();
2631 free( name );
2632 return;
2635 if (rename( fd->unix_name, name ))
2637 file_set_error();
2638 goto failed;
2641 if (is_file_executable( fd->unix_name ) != is_file_executable( name ) && !fstat( fd->unix_fd, &st ))
2643 if (is_file_executable( name ))
2644 /* set executable bit where read bit is set */
2645 st.st_mode |= (st.st_mode & 0444) >> 2;
2646 else
2647 st.st_mode &= ~0111;
2648 fchmod( fd->unix_fd, st.st_mode );
2651 free( fd->nt_name );
2652 fd->nt_name = dup_nt_name( root, nt_name, &fd->nt_namelen );
2653 free( fd->unix_name );
2654 fd->closed->unix_name = fd->unix_name = realpath( name, NULL );
2655 free( name );
2656 if (!fd->unix_name)
2657 set_error( STATUS_NO_MEMORY );
2658 return;
2660 failed:
2661 free( name );
2664 static void set_fd_eof( struct fd *fd, file_pos_t eof )
2666 struct stat st;
2668 if (!fd->inode)
2670 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2671 return;
2674 if (fd->unix_fd == -1)
2676 set_error( fd->no_fd_status );
2677 return;
2679 if (fstat( fd->unix_fd, &st) == -1)
2681 file_set_error();
2682 return;
2684 if (eof < st.st_size)
2686 struct fd *fd_ptr;
2687 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
2689 if (fd_ptr->access & FILE_MAPPING_ACCESS)
2691 set_error( STATUS_USER_MAPPED_FILE );
2692 return;
2695 if (ftruncate( fd->unix_fd, eof ) == -1) file_set_error();
2697 else grow_file( fd->unix_fd, eof );
2700 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2702 *p_key = fd->comp_key;
2703 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2706 void fd_copy_completion( struct fd *src, struct fd *dst )
2708 assert( !dst->completion );
2709 dst->completion = fd_get_completion( src, &dst->comp_key );
2710 dst->comp_flags = src->comp_flags;
2713 /* flush a file buffers */
2714 DECL_HANDLER(flush)
2716 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2717 struct async *async;
2719 if (!fd) return;
2721 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2723 fd->fd_ops->flush( fd, async );
2724 reply->event = async_handoff( async, NULL, 1 );
2725 release_object( async );
2727 release_object( fd );
2730 /* query file info */
2731 DECL_HANDLER(get_file_info)
2733 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2735 if (fd)
2737 fd->fd_ops->get_file_info( fd, req->handle, req->info_class );
2738 release_object( fd );
2742 /* query volume info */
2743 DECL_HANDLER(get_volume_info)
2745 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2746 struct async *async;
2748 if (!fd) return;
2750 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2752 fd->fd_ops->get_volume_info( fd, async, req->info_class );
2753 reply->wait = async_handoff( async, NULL, 1 );
2754 release_object( async );
2756 release_object( fd );
2759 /* open a file object */
2760 DECL_HANDLER(open_file_object)
2762 struct unicode_str name = get_req_unicode_str();
2763 struct object *obj, *result, *root = NULL;
2765 if (req->rootdir && !(root = get_handle_obj( current->process, req->rootdir, 0, NULL ))) return;
2767 obj = open_named_object( root, NULL, &name, req->attributes );
2768 if (root) release_object( root );
2769 if (!obj) return;
2771 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2773 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2774 release_object( result );
2776 release_object( obj );
2779 /* get the Unix name from a file handle */
2780 DECL_HANDLER(get_handle_unix_name)
2782 struct fd *fd;
2784 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2786 if (fd->unix_name)
2788 data_size_t name_len = strlen( fd->unix_name );
2789 reply->name_len = name_len;
2790 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2791 else set_error( STATUS_BUFFER_OVERFLOW );
2793 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2794 release_object( fd );
2798 /* get a Unix fd to access a file */
2799 DECL_HANDLER(get_handle_fd)
2801 struct fd *fd;
2803 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2805 int unix_fd = get_unix_fd( fd );
2806 reply->cacheable = fd->cacheable;
2807 if (unix_fd != -1)
2809 reply->type = fd->fd_ops->get_fd_type( fd );
2810 reply->options = fd->options;
2811 reply->access = get_handle_access( current->process, req->handle );
2812 send_client_fd( current->process, unix_fd, req->handle );
2814 release_object( fd );
2818 /* perform a read on a file object */
2819 DECL_HANDLER(read)
2821 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2822 struct async *async;
2824 if (!fd) return;
2826 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2828 fd->fd_ops->read( fd, async, req->pos );
2829 reply->wait = async_handoff( async, NULL, 0 );
2830 reply->options = fd->options;
2831 release_object( async );
2833 release_object( fd );
2836 /* perform a write on a file object */
2837 DECL_HANDLER(write)
2839 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2840 struct async *async;
2842 if (!fd) return;
2844 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2846 fd->fd_ops->write( fd, async, req->pos );
2847 reply->wait = async_handoff( async, &reply->size, 0 );
2848 reply->options = fd->options;
2849 release_object( async );
2851 release_object( fd );
2854 /* perform an ioctl on a file */
2855 DECL_HANDLER(ioctl)
2857 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2858 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2859 struct async *async;
2861 if (!fd) return;
2863 if ((async = create_request_async( fd, fd->comp_flags, &req->async )))
2865 fd->fd_ops->ioctl( fd, req->code, async );
2866 reply->wait = async_handoff( async, NULL, 0 );
2867 reply->options = fd->options;
2868 release_object( async );
2870 release_object( fd );
2873 /* create / reschedule an async I/O */
2874 DECL_HANDLER(register_async)
2876 unsigned int access;
2877 struct async *async;
2878 struct fd *fd;
2880 switch(req->type)
2882 case ASYNC_TYPE_READ:
2883 access = FILE_READ_DATA;
2884 break;
2885 case ASYNC_TYPE_WRITE:
2886 access = FILE_WRITE_DATA;
2887 break;
2888 default:
2889 set_error( STATUS_INVALID_PARAMETER );
2890 return;
2893 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2895 if (get_unix_fd( fd ) != -1 && (async = create_async( fd, current, &req->async, NULL )))
2897 fd->fd_ops->queue_async( fd, async, req->type, req->count );
2898 release_object( async );
2900 release_object( fd );
2904 /* attach completion object to a fd */
2905 DECL_HANDLER(set_completion_info)
2907 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2909 if (fd)
2911 if (is_fd_overlapped( fd ) && !fd->completion)
2913 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2914 fd->comp_key = req->ckey;
2916 else set_error( STATUS_INVALID_PARAMETER );
2917 release_object( fd );
2921 /* push new completion msg into a completion queue attached to the fd */
2922 DECL_HANDLER(add_fd_completion)
2924 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2925 if (fd)
2927 if (fd->completion && (req->async || !(fd->comp_flags & FILE_SKIP_COMPLETION_PORT_ON_SUCCESS)))
2928 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2929 release_object( fd );
2933 /* set fd completion information */
2934 DECL_HANDLER(set_fd_completion_mode)
2936 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2937 if (fd)
2939 if (is_fd_overlapped( fd ))
2941 if (req->flags & FILE_SKIP_SET_EVENT_ON_HANDLE)
2942 set_fd_signaled( fd, 0 );
2943 /* removing flags is not allowed */
2944 fd->comp_flags |= req->flags & ( FILE_SKIP_COMPLETION_PORT_ON_SUCCESS
2945 | FILE_SKIP_SET_EVENT_ON_HANDLE
2946 | FILE_SKIP_SET_USER_EVENT_ON_FAST_IO );
2948 else
2949 set_error( STATUS_INVALID_PARAMETER );
2950 release_object( fd );
2954 /* set fd disposition information */
2955 DECL_HANDLER(set_fd_disp_info)
2957 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2958 if (fd)
2960 set_fd_disposition( fd, req->unlink );
2961 release_object( fd );
2965 /* set fd name information */
2966 DECL_HANDLER(set_fd_name_info)
2968 struct fd *fd, *root_fd = NULL;
2969 struct unicode_str nt_name;
2971 if (req->namelen > get_req_data_size())
2973 set_error( STATUS_INVALID_PARAMETER );
2974 return;
2976 nt_name.str = get_req_data();
2977 nt_name.len = (req->namelen / sizeof(WCHAR)) * sizeof(WCHAR);
2979 if (req->rootdir)
2981 struct dir *root;
2983 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2984 root_fd = get_obj_fd( (struct object *)root );
2985 release_object( root );
2986 if (!root_fd) return;
2989 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2991 set_fd_name( fd, root_fd, (const char *)get_req_data() + req->namelen,
2992 get_req_data_size() - req->namelen, nt_name, req->link, req->replace );
2993 release_object( fd );
2995 if (root_fd) release_object( root_fd );
2998 /* set fd eof information */
2999 DECL_HANDLER(set_fd_eof_info)
3001 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
3002 if (fd)
3004 set_fd_eof( fd, req->eof );
3005 release_object( fd );