secur32/tests: Handle skip cleanup in negotiate more cleanly.
[wine.git] / server / fd.c
blob6c78a0acf0ad7d3f3036579a48815efa065757d1
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 <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
48 * Solaris defines its system list in sys/list.h.
49 * This need to be workaround it here.
51 #define list SYSLIST
52 #define list_next SYSLIST_NEXT
53 #define list_prev SYSLIST_PREV
54 #define list_head SYSLIST_HEAD
55 #define list_tail SYSLIST_TAIL
56 #define list_move_tail SYSLIST_MOVE_TAIL
57 #define list_remove SYSLIST_REMOVE
58 #include <sys/vfs.h>
59 #undef list
60 #undef list_next
61 #undef list_prev
62 #undef list_head
63 #undef list_tail
64 #undef list_move_tail
65 #undef list_remove
66 #endif
67 #ifdef HAVE_SYS_PARAM_H
68 #include <sys/param.h>
69 #endif
70 #ifdef HAVE_SYS_MOUNT_H
71 #include <sys/mount.h>
72 #endif
73 #ifdef HAVE_SYS_STATFS_H
74 #include <sys/statfs.h>
75 #endif
76 #ifdef HAVE_SYS_SYSCTL_H
77 #include <sys/sysctl.h>
78 #endif
79 #ifdef HAVE_SYS_EVENT_H
80 #include <sys/event.h>
81 #undef LIST_INIT
82 #undef LIST_ENTRY
83 #endif
84 #ifdef HAVE_STDINT_H
85 #include <stdint.h>
86 #endif
87 #include <sys/stat.h>
88 #include <sys/time.h>
89 #include <sys/types.h>
90 #include <unistd.h>
91 #ifdef HAVE_SYS_SYSCALL_H
92 #include <sys/syscall.h>
93 #endif
95 #include "ntstatus.h"
96 #define WIN32_NO_STATUS
97 #include "object.h"
98 #include "file.h"
99 #include "handle.h"
100 #include "process.h"
101 #include "request.h"
103 #include "winternl.h"
104 #include "winioctl.h"
106 #if defined(HAVE_SYS_EPOLL_H) && defined(HAVE_EPOLL_CREATE)
107 # include <sys/epoll.h>
108 # define USE_EPOLL
109 #elif defined(linux) && defined(__i386__) && defined(HAVE_STDINT_H)
110 # define USE_EPOLL
111 # define EPOLLIN POLLIN
112 # define EPOLLOUT POLLOUT
113 # define EPOLLERR POLLERR
114 # define EPOLLHUP POLLHUP
115 # define EPOLL_CTL_ADD 1
116 # define EPOLL_CTL_DEL 2
117 # define EPOLL_CTL_MOD 3
119 typedef union epoll_data
121 void *ptr;
122 int fd;
123 uint32_t u32;
124 uint64_t u64;
125 } epoll_data_t;
127 struct epoll_event
129 uint32_t events;
130 epoll_data_t data;
133 static inline int epoll_create( int size )
135 return syscall( 254 /*NR_epoll_create*/, size );
138 static inline int epoll_ctl( int epfd, int op, int fd, const struct epoll_event *event )
140 return syscall( 255 /*NR_epoll_ctl*/, epfd, op, fd, event );
143 static inline int epoll_wait( int epfd, struct epoll_event *events, int maxevents, int timeout )
145 return syscall( 256 /*NR_epoll_wait*/, epfd, events, maxevents, timeout );
148 #endif /* linux && __i386__ && HAVE_STDINT_H */
150 #if defined(HAVE_PORT_H) && defined(HAVE_PORT_CREATE)
151 # include <port.h>
152 # define USE_EVENT_PORTS
153 #endif /* HAVE_PORT_H && HAVE_PORT_CREATE */
155 /* Because of the stupid Posix locking semantics, we need to keep
156 * track of all file descriptors referencing a given file, and not
157 * close a single one until all the locks are gone (sigh).
160 /* file descriptor object */
162 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
163 struct closed_fd
165 struct list entry; /* entry in inode closed list */
166 int unix_fd; /* the unix file descriptor */
167 int unlink; /* whether to unlink on close */
168 char *unix_name; /* name to unlink on close, points to parent fd unix_name */
171 struct fd
173 struct object obj; /* object header */
174 const struct fd_ops *fd_ops; /* file descriptor operations */
175 struct inode *inode; /* inode that this fd belongs to */
176 struct list inode_entry; /* entry in inode fd list */
177 struct closed_fd *closed; /* structure to store the unix fd at destroy time */
178 struct object *user; /* object using this file descriptor */
179 struct list locks; /* list of locks on this fd */
180 unsigned int access; /* file access (FILE_READ_DATA etc.) */
181 unsigned int options; /* file options (FILE_DELETE_ON_CLOSE, FILE_SYNCHRONOUS...) */
182 unsigned int sharing; /* file sharing mode */
183 char *unix_name; /* unix file name */
184 int unix_fd; /* unix file descriptor */
185 unsigned int no_fd_status;/* status to return when unix_fd is -1 */
186 unsigned int cacheable :1;/* can the fd be cached on the client side? */
187 unsigned int signaled :1; /* is the fd signaled? */
188 unsigned int fs_locks :1; /* can we use filesystem locks for this fd? */
189 int poll_index; /* index of fd in poll array */
190 struct async_queue *read_q; /* async readers of this fd */
191 struct async_queue *write_q; /* async writers of this fd */
192 struct async_queue *wait_q; /* other async waiters of this fd */
193 struct completion *completion; /* completion object attached to this fd */
194 apc_param_t comp_key; /* completion key to set in completion events */
197 static void fd_dump( struct object *obj, int verbose );
198 static void fd_destroy( struct object *obj );
200 static const struct object_ops fd_ops =
202 sizeof(struct fd), /* size */
203 fd_dump, /* dump */
204 no_get_type, /* get_type */
205 no_add_queue, /* add_queue */
206 NULL, /* remove_queue */
207 NULL, /* signaled */
208 NULL, /* satisfied */
209 no_signal, /* signal */
210 no_get_fd, /* get_fd */
211 no_map_access, /* map_access */
212 default_get_sd, /* get_sd */
213 default_set_sd, /* set_sd */
214 no_lookup_name, /* lookup_name */
215 no_open_file, /* open_file */
216 no_close_handle, /* close_handle */
217 fd_destroy /* destroy */
220 /* device object */
222 #define DEVICE_HASH_SIZE 7
223 #define INODE_HASH_SIZE 17
225 struct device
227 struct object obj; /* object header */
228 struct list entry; /* entry in device hash list */
229 dev_t dev; /* device number */
230 int removable; /* removable device? (or -1 if unknown) */
231 struct list inode_hash[INODE_HASH_SIZE]; /* inodes hash table */
234 static void device_dump( struct object *obj, int verbose );
235 static void device_destroy( struct object *obj );
237 static const struct object_ops device_ops =
239 sizeof(struct device), /* size */
240 device_dump, /* dump */
241 no_get_type, /* get_type */
242 no_add_queue, /* add_queue */
243 NULL, /* remove_queue */
244 NULL, /* signaled */
245 NULL, /* satisfied */
246 no_signal, /* signal */
247 no_get_fd, /* get_fd */
248 no_map_access, /* map_access */
249 default_get_sd, /* get_sd */
250 default_set_sd, /* set_sd */
251 no_lookup_name, /* lookup_name */
252 no_open_file, /* open_file */
253 no_close_handle, /* close_handle */
254 device_destroy /* destroy */
257 /* inode object */
259 struct inode
261 struct object obj; /* object header */
262 struct list entry; /* inode hash list entry */
263 struct device *device; /* device containing this inode */
264 ino_t ino; /* inode number */
265 struct list open; /* list of open file descriptors */
266 struct list locks; /* list of file locks */
267 struct list closed; /* list of file descriptors to close at destroy time */
270 static void inode_dump( struct object *obj, int verbose );
271 static void inode_destroy( struct object *obj );
273 static const struct object_ops inode_ops =
275 sizeof(struct inode), /* size */
276 inode_dump, /* dump */
277 no_get_type, /* get_type */
278 no_add_queue, /* add_queue */
279 NULL, /* remove_queue */
280 NULL, /* signaled */
281 NULL, /* satisfied */
282 no_signal, /* signal */
283 no_get_fd, /* get_fd */
284 no_map_access, /* map_access */
285 default_get_sd, /* get_sd */
286 default_set_sd, /* set_sd */
287 no_lookup_name, /* lookup_name */
288 no_open_file, /* open_file */
289 no_close_handle, /* close_handle */
290 inode_destroy /* destroy */
293 /* file lock object */
295 struct file_lock
297 struct object obj; /* object header */
298 struct fd *fd; /* fd owning this lock */
299 struct list fd_entry; /* entry in list of locks on a given fd */
300 struct list inode_entry; /* entry in inode list of locks */
301 int shared; /* shared lock? */
302 file_pos_t start; /* locked region is interval [start;end) */
303 file_pos_t end;
304 struct process *process; /* process owning this lock */
305 struct list proc_entry; /* entry in list of locks owned by the process */
308 static void file_lock_dump( struct object *obj, int verbose );
309 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry );
311 static const struct object_ops file_lock_ops =
313 sizeof(struct file_lock), /* size */
314 file_lock_dump, /* dump */
315 no_get_type, /* get_type */
316 add_queue, /* add_queue */
317 remove_queue, /* remove_queue */
318 file_lock_signaled, /* signaled */
319 no_satisfied, /* satisfied */
320 no_signal, /* signal */
321 no_get_fd, /* get_fd */
322 no_map_access, /* map_access */
323 default_get_sd, /* get_sd */
324 default_set_sd, /* set_sd */
325 no_lookup_name, /* lookup_name */
326 no_open_file, /* open_file */
327 no_close_handle, /* close_handle */
328 no_destroy /* destroy */
332 #define OFF_T_MAX (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
333 #define FILE_POS_T_MAX (~(file_pos_t)0)
335 static file_pos_t max_unix_offset = OFF_T_MAX;
337 #define DUMP_LONG_LONG(val) do { \
338 if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
339 fprintf( stderr, "%lx%08lx", (unsigned long)((unsigned long long)(val) >> 32), (unsigned long)(val) ); \
340 else \
341 fprintf( stderr, "%lx", (unsigned long)(val) ); \
342 } while (0)
346 /****************************************************************/
347 /* timeouts support */
349 struct timeout_user
351 struct list entry; /* entry in sorted timeout list */
352 timeout_t when; /* timeout expiry (absolute time) */
353 timeout_callback callback; /* callback function */
354 void *private; /* callback private data */
357 static struct list timeout_list = LIST_INIT(timeout_list); /* sorted timeouts list */
358 timeout_t current_time;
360 static inline void set_current_time(void)
362 static const timeout_t ticks_1601_to_1970 = (timeout_t)86400 * (369 * 365 + 89) * TICKS_PER_SEC;
363 struct timeval now;
364 gettimeofday( &now, NULL );
365 current_time = (timeout_t)now.tv_sec * TICKS_PER_SEC + now.tv_usec * 10 + ticks_1601_to_1970;
368 /* add a timeout user */
369 struct timeout_user *add_timeout_user( timeout_t when, timeout_callback func, void *private )
371 struct timeout_user *user;
372 struct list *ptr;
374 if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
375 user->when = (when > 0) ? when : current_time - when;
376 user->callback = func;
377 user->private = private;
379 /* Now insert it in the linked list */
381 LIST_FOR_EACH( ptr, &timeout_list )
383 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
384 if (timeout->when >= user->when) break;
386 list_add_before( ptr, &user->entry );
387 return user;
390 /* remove a timeout user */
391 void remove_timeout_user( struct timeout_user *user )
393 list_remove( &user->entry );
394 free( user );
397 /* return a text description of a timeout for debugging purposes */
398 const char *get_timeout_str( timeout_t timeout )
400 static char buffer[64];
401 long secs, nsecs;
403 if (!timeout) return "0";
404 if (timeout == TIMEOUT_INFINITE) return "infinite";
406 if (timeout < 0) /* relative */
408 secs = -timeout / TICKS_PER_SEC;
409 nsecs = -timeout % TICKS_PER_SEC;
410 sprintf( buffer, "+%ld.%07ld", secs, nsecs );
412 else /* absolute */
414 secs = (timeout - current_time) / TICKS_PER_SEC;
415 nsecs = (timeout - current_time) % TICKS_PER_SEC;
416 if (nsecs < 0)
418 nsecs += TICKS_PER_SEC;
419 secs--;
421 if (secs >= 0)
422 sprintf( buffer, "%x%08x (+%ld.%07ld)",
423 (unsigned int)(timeout >> 32), (unsigned int)timeout, secs, nsecs );
424 else
425 sprintf( buffer, "%x%08x (-%ld.%07ld)",
426 (unsigned int)(timeout >> 32), (unsigned int)timeout,
427 -(secs + 1), TICKS_PER_SEC - nsecs );
429 return buffer;
433 /****************************************************************/
434 /* poll support */
436 static struct fd **poll_users; /* users array */
437 static struct pollfd *pollfd; /* poll fd array */
438 static int nb_users; /* count of array entries actually in use */
439 static int active_users; /* current number of active users */
440 static int allocated_users; /* count of allocated entries in the array */
441 static struct fd **freelist; /* list of free entries in the array */
443 static int get_next_timeout(void);
445 static inline void fd_poll_event( struct fd *fd, int event )
447 fd->fd_ops->poll_event( fd, event );
450 #ifdef USE_EPOLL
452 static int epoll_fd = -1;
454 static inline void init_epoll(void)
456 epoll_fd = epoll_create( 128 );
459 /* set the events that epoll waits for on this fd; helper for set_fd_events */
460 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
462 struct epoll_event ev;
463 int ctl;
465 if (epoll_fd == -1) return;
467 if (events == -1) /* stop waiting on this fd completely */
469 if (pollfd[user].fd == -1) return; /* already removed */
470 ctl = EPOLL_CTL_DEL;
472 else if (pollfd[user].fd == -1)
474 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
475 ctl = EPOLL_CTL_ADD;
477 else
479 if (pollfd[user].events == events) return; /* nothing to do */
480 ctl = EPOLL_CTL_MOD;
483 ev.events = events;
484 memset(&ev.data, 0, sizeof(ev.data));
485 ev.data.u32 = user;
487 if (epoll_ctl( epoll_fd, ctl, fd->unix_fd, &ev ) == -1)
489 if (errno == ENOMEM) /* not enough memory, give up on epoll */
491 close( epoll_fd );
492 epoll_fd = -1;
494 else perror( "epoll_ctl" ); /* should not happen */
498 static inline void remove_epoll_user( struct fd *fd, int user )
500 if (epoll_fd == -1) return;
502 if (pollfd[user].fd != -1)
504 struct epoll_event dummy;
505 epoll_ctl( epoll_fd, EPOLL_CTL_DEL, fd->unix_fd, &dummy );
509 static inline void main_loop_epoll(void)
511 int i, ret, timeout;
512 struct epoll_event events[128];
514 assert( POLLIN == EPOLLIN );
515 assert( POLLOUT == EPOLLOUT );
516 assert( POLLERR == EPOLLERR );
517 assert( POLLHUP == EPOLLHUP );
519 if (epoll_fd == -1) return;
521 while (active_users)
523 timeout = get_next_timeout();
525 if (!active_users) break; /* last user removed by a timeout */
526 if (epoll_fd == -1) break; /* an error occurred with epoll */
528 ret = epoll_wait( epoll_fd, events, sizeof(events)/sizeof(events[0]), timeout );
529 set_current_time();
531 /* put the events into the pollfd array first, like poll does */
532 for (i = 0; i < ret; i++)
534 int user = events[i].data.u32;
535 pollfd[user].revents = events[i].events;
538 /* read events from the pollfd array, as set_fd_events may modify them */
539 for (i = 0; i < ret; i++)
541 int user = events[i].data.u32;
542 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
547 #elif defined(HAVE_KQUEUE)
549 static int kqueue_fd = -1;
551 static inline void init_epoll(void)
553 #ifdef __APPLE__ /* kqueue support is broken in Mac OS < 10.5 */
554 int mib[2];
555 char release[32];
556 size_t len = sizeof(release);
558 mib[0] = CTL_KERN;
559 mib[1] = KERN_OSRELEASE;
560 if (sysctl( mib, 2, release, &len, NULL, 0 ) == -1) return;
561 if (atoi(release) < 9) return;
562 #endif
563 kqueue_fd = kqueue();
566 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
568 struct kevent ev[2];
570 if (kqueue_fd == -1) return;
572 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, 0, NOTE_LOWAT, 1, (void *)user );
573 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, 0, NOTE_LOWAT, 1, (void *)user );
575 if (events == -1) /* stop waiting on this fd completely */
577 if (pollfd[user].fd == -1) return; /* already removed */
578 ev[0].flags |= EV_DELETE;
579 ev[1].flags |= EV_DELETE;
581 else if (pollfd[user].fd == -1)
583 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
584 ev[0].flags |= EV_ADD | ((events & POLLIN) ? EV_ENABLE : EV_DISABLE);
585 ev[1].flags |= EV_ADD | ((events & POLLOUT) ? EV_ENABLE : EV_DISABLE);
587 else
589 if (pollfd[user].events == events) return; /* nothing to do */
590 ev[0].flags |= (events & POLLIN) ? EV_ENABLE : EV_DISABLE;
591 ev[1].flags |= (events & POLLOUT) ? EV_ENABLE : EV_DISABLE;
594 if (kevent( kqueue_fd, ev, 2, NULL, 0, NULL ) == -1)
596 if (errno == ENOMEM) /* not enough memory, give up on kqueue */
598 close( kqueue_fd );
599 kqueue_fd = -1;
601 else perror( "kevent" ); /* should not happen */
605 static inline void remove_epoll_user( struct fd *fd, int user )
607 if (kqueue_fd == -1) return;
609 if (pollfd[user].fd != -1)
611 struct kevent ev[2];
613 EV_SET( &ev[0], fd->unix_fd, EVFILT_READ, EV_DELETE, 0, 0, 0 );
614 EV_SET( &ev[1], fd->unix_fd, EVFILT_WRITE, EV_DELETE, 0, 0, 0 );
615 kevent( kqueue_fd, ev, 2, NULL, 0, NULL );
619 static inline void main_loop_epoll(void)
621 int i, ret, timeout;
622 struct kevent events[128];
624 if (kqueue_fd == -1) return;
626 while (active_users)
628 timeout = get_next_timeout();
630 if (!active_users) break; /* last user removed by a timeout */
631 if (kqueue_fd == -1) break; /* an error occurred with kqueue */
633 if (timeout != -1)
635 struct timespec ts;
637 ts.tv_sec = timeout / 1000;
638 ts.tv_nsec = (timeout % 1000) * 1000000;
639 ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), &ts );
641 else ret = kevent( kqueue_fd, NULL, 0, events, sizeof(events)/sizeof(events[0]), NULL );
643 set_current_time();
645 /* put the events into the pollfd array first, like poll does */
646 for (i = 0; i < ret; i++)
648 long user = (long)events[i].udata;
649 pollfd[user].revents = 0;
651 for (i = 0; i < ret; i++)
653 long user = (long)events[i].udata;
654 if (events[i].filter == EVFILT_READ) pollfd[user].revents |= POLLIN;
655 else if (events[i].filter == EVFILT_WRITE) pollfd[user].revents |= POLLOUT;
656 if (events[i].flags & EV_EOF) pollfd[user].revents |= POLLHUP;
657 if (events[i].flags & EV_ERROR) pollfd[user].revents |= POLLERR;
660 /* read events from the pollfd array, as set_fd_events may modify them */
661 for (i = 0; i < ret; i++)
663 long user = (long)events[i].udata;
664 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
665 pollfd[user].revents = 0;
670 #elif defined(USE_EVENT_PORTS)
672 static int port_fd = -1;
674 static inline void init_epoll(void)
676 port_fd = port_create();
679 static inline void set_fd_epoll_events( struct fd *fd, int user, int events )
681 int ret;
683 if (port_fd == -1) return;
685 if (events == -1) /* stop waiting on this fd completely */
687 if (pollfd[user].fd == -1) return; /* already removed */
688 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
690 else if (pollfd[user].fd == -1)
692 if (pollfd[user].events) return; /* stopped waiting on it, don't restart */
693 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
695 else
697 if (pollfd[user].events == events) return; /* nothing to do */
698 ret = port_associate( port_fd, PORT_SOURCE_FD, fd->unix_fd, events, (void *)user );
701 if (ret == -1)
703 if (errno == ENOMEM) /* not enough memory, give up on port_associate */
705 close( port_fd );
706 port_fd = -1;
708 else perror( "port_associate" ); /* should not happen */
712 static inline void remove_epoll_user( struct fd *fd, int user )
714 if (port_fd == -1) return;
716 if (pollfd[user].fd != -1)
718 port_dissociate( port_fd, PORT_SOURCE_FD, fd->unix_fd );
722 static inline void main_loop_epoll(void)
724 int i, nget, ret, timeout;
725 port_event_t events[128];
727 if (port_fd == -1) return;
729 while (active_users)
731 timeout = get_next_timeout();
732 nget = 1;
734 if (!active_users) break; /* last user removed by a timeout */
735 if (port_fd == -1) break; /* an error occurred with event completion */
737 if (timeout != -1)
739 struct timespec ts;
741 ts.tv_sec = timeout / 1000;
742 ts.tv_nsec = (timeout % 1000) * 1000000;
743 ret = port_getn( port_fd, events, sizeof(events)/sizeof(events[0]), &nget, &ts );
745 else ret = port_getn( port_fd, events, sizeof(events)/sizeof(events[0]), &nget, NULL );
747 if (ret == -1) break; /* an error occurred with event completion */
749 set_current_time();
751 /* put the events into the pollfd array first, like poll does */
752 for (i = 0; i < nget; i++)
754 long user = (long)events[i].portev_user;
755 pollfd[user].revents = events[i].portev_events;
758 /* read events from the pollfd array, as set_fd_events may modify them */
759 for (i = 0; i < nget; i++)
761 long user = (long)events[i].portev_user;
762 if (pollfd[user].revents) fd_poll_event( poll_users[user], pollfd[user].revents );
763 /* if we are still interested, reassociate the fd */
764 if (pollfd[user].fd != -1) {
765 port_associate( port_fd, PORT_SOURCE_FD, pollfd[user].fd, pollfd[user].events, (void *)user );
771 #else /* HAVE_KQUEUE */
773 static inline void init_epoll(void) { }
774 static inline void set_fd_epoll_events( struct fd *fd, int user, int events ) { }
775 static inline void remove_epoll_user( struct fd *fd, int user ) { }
776 static inline void main_loop_epoll(void) { }
778 #endif /* USE_EPOLL */
781 /* add a user in the poll array and return its index, or -1 on failure */
782 static int add_poll_user( struct fd *fd )
784 int ret;
785 if (freelist)
787 ret = freelist - poll_users;
788 freelist = (struct fd **)poll_users[ret];
790 else
792 if (nb_users == allocated_users)
794 struct fd **newusers;
795 struct pollfd *newpoll;
796 int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
797 if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
798 if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
800 if (allocated_users)
801 poll_users = newusers;
802 else
803 free( newusers );
804 return -1;
806 poll_users = newusers;
807 pollfd = newpoll;
808 if (!allocated_users) init_epoll();
809 allocated_users = new_count;
811 ret = nb_users++;
813 pollfd[ret].fd = -1;
814 pollfd[ret].events = 0;
815 pollfd[ret].revents = 0;
816 poll_users[ret] = fd;
817 active_users++;
818 return ret;
821 /* remove a user from the poll list */
822 static void remove_poll_user( struct fd *fd, int user )
824 assert( user >= 0 );
825 assert( poll_users[user] == fd );
827 remove_epoll_user( fd, user );
828 pollfd[user].fd = -1;
829 pollfd[user].events = 0;
830 pollfd[user].revents = 0;
831 poll_users[user] = (struct fd *)freelist;
832 freelist = &poll_users[user];
833 active_users--;
836 /* process pending timeouts and return the time until the next timeout, in milliseconds */
837 static int get_next_timeout(void)
839 if (!list_empty( &timeout_list ))
841 struct list expired_list, *ptr;
843 /* first remove all expired timers from the list */
845 list_init( &expired_list );
846 while ((ptr = list_head( &timeout_list )) != NULL)
848 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
850 if (timeout->when <= current_time)
852 list_remove( &timeout->entry );
853 list_add_tail( &expired_list, &timeout->entry );
855 else break;
858 /* now call the callback for all the removed timers */
860 while ((ptr = list_head( &expired_list )) != NULL)
862 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
863 list_remove( &timeout->entry );
864 timeout->callback( timeout->private );
865 free( timeout );
868 if ((ptr = list_head( &timeout_list )) != NULL)
870 struct timeout_user *timeout = LIST_ENTRY( ptr, struct timeout_user, entry );
871 int diff = (timeout->when - current_time + 9999) / 10000;
872 if (diff < 0) diff = 0;
873 return diff;
876 return -1; /* no pending timeouts */
879 /* server main poll() loop */
880 void main_loop(void)
882 int i, ret, timeout;
884 set_current_time();
885 server_start_time = current_time;
887 main_loop_epoll();
888 /* fall through to normal poll loop */
890 while (active_users)
892 timeout = get_next_timeout();
894 if (!active_users) break; /* last user removed by a timeout */
896 ret = poll( pollfd, nb_users, timeout );
897 set_current_time();
899 if (ret > 0)
901 for (i = 0; i < nb_users; i++)
903 if (pollfd[i].revents)
905 fd_poll_event( poll_users[i], pollfd[i].revents );
906 if (!--ret) break;
914 /****************************************************************/
915 /* device functions */
917 static struct list device_hash[DEVICE_HASH_SIZE];
919 static int is_device_removable( dev_t dev, int unix_fd )
921 #if defined(linux) && defined(HAVE_FSTATFS)
922 struct statfs stfs;
924 /* check for floppy disk */
925 if (major(dev) == FLOPPY_MAJOR) return 1;
927 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
928 return (stfs.f_type == 0x9660 || /* iso9660 */
929 stfs.f_type == 0x9fa1 || /* supermount */
930 stfs.f_type == 0x15013346); /* udf */
931 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
932 struct statfs stfs;
934 if (fstatfs( unix_fd, &stfs ) == -1) return 0;
935 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
936 #elif defined(__NetBSD__)
937 struct statvfs stfs;
939 if (fstatvfs( unix_fd, &stfs ) == -1) return 0;
940 return (!strcmp("cd9660", stfs.f_fstypename) || !strcmp("udf", stfs.f_fstypename));
941 #elif defined(sun)
942 # include <sys/dkio.h>
943 # include <sys/vtoc.h>
944 struct dk_cinfo dkinf;
945 if (ioctl( unix_fd, DKIOCINFO, &dkinf ) == -1) return 0;
946 return (dkinf.dki_ctype == DKC_CDROM ||
947 dkinf.dki_ctype == DKC_NCRFLOPPY ||
948 dkinf.dki_ctype == DKC_SMSFLOPPY ||
949 dkinf.dki_ctype == DKC_INTEL82072 ||
950 dkinf.dki_ctype == DKC_INTEL82077);
951 #else
952 return 0;
953 #endif
956 /* retrieve the device object for a given fd, creating it if needed */
957 static struct device *get_device( dev_t dev, int unix_fd )
959 struct device *device;
960 unsigned int i, hash = dev % DEVICE_HASH_SIZE;
962 if (device_hash[hash].next)
964 LIST_FOR_EACH_ENTRY( device, &device_hash[hash], struct device, entry )
965 if (device->dev == dev) return (struct device *)grab_object( device );
967 else list_init( &device_hash[hash] );
969 /* not found, create it */
971 if (unix_fd == -1) return NULL;
972 if ((device = alloc_object( &device_ops )))
974 device->dev = dev;
975 device->removable = is_device_removable( dev, unix_fd );
976 for (i = 0; i < INODE_HASH_SIZE; i++) list_init( &device->inode_hash[i] );
977 list_add_head( &device_hash[hash], &device->entry );
979 return device;
982 static void device_dump( struct object *obj, int verbose )
984 struct device *device = (struct device *)obj;
985 fprintf( stderr, "Device dev=" );
986 DUMP_LONG_LONG( device->dev );
987 fprintf( stderr, "\n" );
990 static void device_destroy( struct object *obj )
992 struct device *device = (struct device *)obj;
993 unsigned int i;
995 for (i = 0; i < INODE_HASH_SIZE; i++)
996 assert( list_empty(&device->inode_hash[i]) );
998 list_remove( &device->entry ); /* remove it from the hash table */
1002 /****************************************************************/
1003 /* inode functions */
1005 /* close all pending file descriptors in the closed list */
1006 static void inode_close_pending( struct inode *inode, int keep_unlinks )
1008 struct list *ptr = list_head( &inode->closed );
1010 while (ptr)
1012 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1013 struct list *next = list_next( &inode->closed, ptr );
1015 if (fd->unix_fd != -1)
1017 close( fd->unix_fd );
1018 fd->unix_fd = -1;
1020 if (!keep_unlinks || !fd->unlink) /* get rid of it unless there's an unlink pending on that file */
1022 list_remove( ptr );
1023 free( fd->unix_name );
1024 free( fd );
1026 ptr = next;
1030 static void inode_dump( struct object *obj, int verbose )
1032 struct inode *inode = (struct inode *)obj;
1033 fprintf( stderr, "Inode device=%p ino=", inode->device );
1034 DUMP_LONG_LONG( inode->ino );
1035 fprintf( stderr, "\n" );
1038 static void inode_destroy( struct object *obj )
1040 struct inode *inode = (struct inode *)obj;
1041 struct list *ptr;
1043 assert( list_empty(&inode->open) );
1044 assert( list_empty(&inode->locks) );
1046 list_remove( &inode->entry );
1048 while ((ptr = list_head( &inode->closed )))
1050 struct closed_fd *fd = LIST_ENTRY( ptr, struct closed_fd, entry );
1051 list_remove( ptr );
1052 if (fd->unix_fd != -1) close( fd->unix_fd );
1053 if (fd->unlink)
1055 /* make sure it is still the same file */
1056 struct stat st;
1057 if (!stat( fd->unix_name, &st ) && st.st_dev == inode->device->dev && st.st_ino == inode->ino)
1059 if (S_ISDIR(st.st_mode)) rmdir( fd->unix_name );
1060 else unlink( fd->unix_name );
1063 free( fd->unix_name );
1064 free( fd );
1066 release_object( inode->device );
1069 /* retrieve the inode object for a given fd, creating it if needed */
1070 static struct inode *get_inode( dev_t dev, ino_t ino, int unix_fd )
1072 struct device *device;
1073 struct inode *inode;
1074 unsigned int hash = ino % INODE_HASH_SIZE;
1076 if (!(device = get_device( dev, unix_fd ))) return NULL;
1078 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[hash], struct inode, entry )
1080 if (inode->ino == ino)
1082 release_object( device );
1083 return (struct inode *)grab_object( inode );
1087 /* not found, create it */
1088 if ((inode = alloc_object( &inode_ops )))
1090 inode->device = device;
1091 inode->ino = ino;
1092 list_init( &inode->open );
1093 list_init( &inode->locks );
1094 list_init( &inode->closed );
1095 list_add_head( &device->inode_hash[hash], &inode->entry );
1097 else release_object( device );
1099 return inode;
1102 /* add fd to the inode list of file descriptors to close */
1103 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
1105 if (!list_empty( &inode->locks ))
1107 list_add_head( &inode->closed, &fd->entry );
1109 else if (fd->unlink) /* close the fd but keep the structure around for unlink */
1111 if (fd->unix_fd != -1) close( fd->unix_fd );
1112 fd->unix_fd = -1;
1113 list_add_head( &inode->closed, &fd->entry );
1115 else /* no locks on this inode and no unlink, get rid of the fd */
1117 if (fd->unix_fd != -1) close( fd->unix_fd );
1118 free( fd->unix_name );
1119 free( fd );
1124 /****************************************************************/
1125 /* file lock functions */
1127 static void file_lock_dump( struct object *obj, int verbose )
1129 struct file_lock *lock = (struct file_lock *)obj;
1130 fprintf( stderr, "Lock %s fd=%p proc=%p start=",
1131 lock->shared ? "shared" : "excl", lock->fd, lock->process );
1132 DUMP_LONG_LONG( lock->start );
1133 fprintf( stderr, " end=" );
1134 DUMP_LONG_LONG( lock->end );
1135 fprintf( stderr, "\n" );
1138 static int file_lock_signaled( struct object *obj, struct wait_queue_entry *entry )
1140 struct file_lock *lock = (struct file_lock *)obj;
1141 /* lock is signaled if it has lost its owner */
1142 return !lock->process;
1145 /* set (or remove) a Unix lock if possible for the given range */
1146 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
1148 struct flock fl;
1150 if (!fd->fs_locks) return 1; /* no fs locks possible for this fd */
1151 for (;;)
1153 if (start == end) return 1; /* can't set zero-byte lock */
1154 if (start > max_unix_offset) return 1; /* ignore it */
1155 fl.l_type = type;
1156 fl.l_whence = SEEK_SET;
1157 fl.l_start = start;
1158 if (!end || end > max_unix_offset) fl.l_len = 0;
1159 else fl.l_len = end - start;
1160 if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
1162 switch(errno)
1164 case EACCES:
1165 /* check whether locks work at all on this file system */
1166 if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
1168 set_error( STATUS_FILE_LOCK_CONFLICT );
1169 return 0;
1171 /* fall through */
1172 case EIO:
1173 case ENOLCK:
1174 case ENOTSUP:
1175 /* no locking on this fs, just ignore it */
1176 fd->fs_locks = 0;
1177 return 1;
1178 case EAGAIN:
1179 set_error( STATUS_FILE_LOCK_CONFLICT );
1180 return 0;
1181 case EBADF:
1182 /* this can happen if we try to set a write lock on a read-only file */
1183 /* try to at least grab a read lock */
1184 if (fl.l_type == F_WRLCK)
1186 type = F_RDLCK;
1187 break; /* retry */
1189 set_error( STATUS_ACCESS_DENIED );
1190 return 0;
1191 #ifdef EOVERFLOW
1192 case EOVERFLOW:
1193 #endif
1194 case EINVAL:
1195 /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
1196 /* in that case we shrink the limit and retry */
1197 if (max_unix_offset > INT_MAX)
1199 max_unix_offset = INT_MAX;
1200 break; /* retry */
1202 /* fall through */
1203 default:
1204 file_set_error();
1205 return 0;
1210 /* check if interval [start;end) overlaps the lock */
1211 static inline int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
1213 if (lock->end && start >= lock->end) return 0;
1214 if (end && lock->start >= end) return 0;
1215 return 1;
1218 /* remove Unix locks for all bytes in the specified area that are no longer locked */
1219 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
1221 struct hole
1223 struct hole *next;
1224 struct hole *prev;
1225 file_pos_t start;
1226 file_pos_t end;
1227 } *first, *cur, *next, *buffer;
1229 struct list *ptr;
1230 int count = 0;
1232 if (!fd->inode) return;
1233 if (!fd->fs_locks) return;
1234 if (start == end || start > max_unix_offset) return;
1235 if (!end || end > max_unix_offset) end = max_unix_offset + 1;
1237 /* count the number of locks overlapping the specified area */
1239 LIST_FOR_EACH( ptr, &fd->inode->locks )
1241 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1242 if (lock->start == lock->end) continue;
1243 if (lock_overlaps( lock, start, end )) count++;
1246 if (!count) /* no locks at all, we can unlock everything */
1248 set_unix_lock( fd, start, end, F_UNLCK );
1249 return;
1252 /* allocate space for the list of holes */
1253 /* max. number of holes is number of locks + 1 */
1255 if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
1256 first = buffer;
1257 first->next = NULL;
1258 first->prev = NULL;
1259 first->start = start;
1260 first->end = end;
1261 next = first + 1;
1263 /* build a sorted list of unlocked holes in the specified area */
1265 LIST_FOR_EACH( ptr, &fd->inode->locks )
1267 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1268 if (lock->start == lock->end) continue;
1269 if (!lock_overlaps( lock, start, end )) continue;
1271 /* go through all the holes touched by this lock */
1272 for (cur = first; cur; cur = cur->next)
1274 if (cur->end <= lock->start) continue; /* hole is before start of lock */
1275 if (lock->end && cur->start >= lock->end) break; /* hole is after end of lock */
1277 /* now we know that lock is overlapping hole */
1279 if (cur->start >= lock->start) /* lock starts before hole, shrink from start */
1281 cur->start = lock->end;
1282 if (cur->start && cur->start < cur->end) break; /* done with this lock */
1283 /* now hole is empty, remove it */
1284 if (cur->next) cur->next->prev = cur->prev;
1285 if (cur->prev) cur->prev->next = cur->next;
1286 else if (!(first = cur->next)) goto done; /* no more holes at all */
1288 else if (!lock->end || cur->end <= lock->end) /* lock larger than hole, shrink from end */
1290 cur->end = lock->start;
1291 assert( cur->start < cur->end );
1293 else /* lock is in the middle of hole, split hole in two */
1295 next->prev = cur;
1296 next->next = cur->next;
1297 cur->next = next;
1298 next->start = lock->end;
1299 next->end = cur->end;
1300 cur->end = lock->start;
1301 assert( next->start < next->end );
1302 assert( cur->end < next->start );
1303 next++;
1304 break; /* done with this lock */
1309 /* clear Unix locks for all the holes */
1311 for (cur = first; cur; cur = cur->next)
1312 set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
1314 done:
1315 free( buffer );
1318 /* create a new lock on a fd */
1319 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
1321 struct file_lock *lock;
1323 if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
1324 lock->shared = shared;
1325 lock->start = start;
1326 lock->end = end;
1327 lock->fd = fd;
1328 lock->process = current->process;
1330 /* now try to set a Unix lock */
1331 if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
1333 release_object( lock );
1334 return NULL;
1336 list_add_tail( &fd->locks, &lock->fd_entry );
1337 list_add_tail( &fd->inode->locks, &lock->inode_entry );
1338 list_add_tail( &lock->process->locks, &lock->proc_entry );
1339 return lock;
1342 /* remove an existing lock */
1343 static void remove_lock( struct file_lock *lock, int remove_unix )
1345 struct inode *inode = lock->fd->inode;
1347 list_remove( &lock->fd_entry );
1348 list_remove( &lock->inode_entry );
1349 list_remove( &lock->proc_entry );
1350 if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
1351 if (list_empty( &inode->locks )) inode_close_pending( inode, 1 );
1352 lock->process = NULL;
1353 wake_up( &lock->obj, 0 );
1354 release_object( lock );
1357 /* remove all locks owned by a given process */
1358 void remove_process_locks( struct process *process )
1360 struct list *ptr;
1362 while ((ptr = list_head( &process->locks )))
1364 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
1365 remove_lock( lock, 1 ); /* this removes it from the list */
1369 /* remove all locks on a given fd */
1370 static void remove_fd_locks( struct fd *fd )
1372 file_pos_t start = FILE_POS_T_MAX, end = 0;
1373 struct list *ptr;
1375 while ((ptr = list_head( &fd->locks )))
1377 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1378 if (lock->start < start) start = lock->start;
1379 if (!lock->end || lock->end > end) end = lock->end - 1;
1380 remove_lock( lock, 0 );
1382 if (start < end) remove_unix_locks( fd, start, end + 1 );
1385 /* add a lock on an fd */
1386 /* returns handle to wait on */
1387 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
1389 struct list *ptr;
1390 file_pos_t end = start + count;
1392 if (!fd->inode) /* not a regular file */
1394 set_error( STATUS_INVALID_DEVICE_REQUEST );
1395 return 0;
1398 /* don't allow wrapping locks */
1399 if (end && end < start)
1401 set_error( STATUS_INVALID_PARAMETER );
1402 return 0;
1405 /* check if another lock on that file overlaps the area */
1406 LIST_FOR_EACH( ptr, &fd->inode->locks )
1408 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
1409 if (!lock_overlaps( lock, start, end )) continue;
1410 if (shared && (lock->shared || lock->fd == fd)) continue;
1411 /* found one */
1412 if (!wait)
1414 set_error( STATUS_FILE_LOCK_CONFLICT );
1415 return 0;
1417 set_error( STATUS_PENDING );
1418 return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
1421 /* not found, add it */
1422 if (add_lock( fd, shared, start, end )) return 0;
1423 if (get_error() == STATUS_FILE_LOCK_CONFLICT)
1425 /* Unix lock conflict -> tell client to wait and retry */
1426 if (wait) set_error( STATUS_PENDING );
1428 return 0;
1431 /* remove a lock on an fd */
1432 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
1434 struct list *ptr;
1435 file_pos_t end = start + count;
1437 /* find an existing lock with the exact same parameters */
1438 LIST_FOR_EACH( ptr, &fd->locks )
1440 struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
1441 if ((lock->start == start) && (lock->end == end))
1443 remove_lock( lock, 1 );
1444 return;
1447 set_error( STATUS_FILE_LOCK_CONFLICT );
1451 /****************************************************************/
1452 /* file descriptor functions */
1454 static void fd_dump( struct object *obj, int verbose )
1456 struct fd *fd = (struct fd *)obj;
1457 fprintf( stderr, "Fd unix_fd=%d user=%p options=%08x", fd->unix_fd, fd->user, fd->options );
1458 if (fd->inode) fprintf( stderr, " inode=%p unlink=%d", fd->inode, fd->closed->unlink );
1459 fprintf( stderr, "\n" );
1462 static void fd_destroy( struct object *obj )
1464 struct fd *fd = (struct fd *)obj;
1466 free_async_queue( fd->read_q );
1467 free_async_queue( fd->write_q );
1468 free_async_queue( fd->wait_q );
1470 if (fd->completion) release_object( fd->completion );
1471 remove_fd_locks( fd );
1472 list_remove( &fd->inode_entry );
1473 if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
1474 if (fd->inode)
1476 inode_add_closed_fd( fd->inode, fd->closed );
1477 release_object( fd->inode );
1479 else /* no inode, close it right away */
1481 if (fd->unix_fd != -1) close( fd->unix_fd );
1482 free( fd->unix_name );
1486 /* check if the desired access is possible without violating */
1487 /* the sharing mode of other opens of the same file */
1488 static unsigned int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing,
1489 unsigned int open_flags, unsigned int options )
1491 /* only a few access bits are meaningful wrt sharing */
1492 const unsigned int read_access = FILE_READ_DATA | FILE_EXECUTE;
1493 const unsigned int write_access = FILE_WRITE_DATA | FILE_APPEND_DATA;
1494 const unsigned int all_access = read_access | write_access | DELETE;
1496 unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1497 unsigned int existing_access = 0;
1498 struct list *ptr;
1500 fd->access = access;
1501 fd->sharing = sharing;
1503 LIST_FOR_EACH( ptr, &fd->inode->open )
1505 struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
1506 if (fd_ptr != fd)
1508 /* if access mode is 0, sharing mode is ignored */
1509 if (fd_ptr->access & all_access) existing_sharing &= fd_ptr->sharing;
1510 existing_access |= fd_ptr->access;
1514 if (((access & read_access) && !(existing_sharing & FILE_SHARE_READ)) ||
1515 ((access & write_access) && !(existing_sharing & FILE_SHARE_WRITE)) ||
1516 ((access & DELETE) && !(existing_sharing & FILE_SHARE_DELETE)))
1517 return STATUS_SHARING_VIOLATION;
1518 if (((existing_access & FILE_MAPPING_WRITE) && !(sharing & FILE_SHARE_WRITE)) ||
1519 ((existing_access & FILE_MAPPING_IMAGE) && (access & FILE_WRITE_DATA)))
1520 return STATUS_SHARING_VIOLATION;
1521 if ((existing_access & FILE_MAPPING_IMAGE) && (options & FILE_DELETE_ON_CLOSE))
1522 return STATUS_CANNOT_DELETE;
1523 if ((existing_access & FILE_MAPPING_ACCESS) && (open_flags & O_TRUNC))
1524 return STATUS_USER_MAPPED_FILE;
1525 if (!(access & all_access))
1526 return 0; /* if access mode is 0, sharing mode is ignored (except for mappings) */
1527 if (((existing_access & read_access) && !(sharing & FILE_SHARE_READ)) ||
1528 ((existing_access & write_access) && !(sharing & FILE_SHARE_WRITE)) ||
1529 ((existing_access & DELETE) && !(sharing & FILE_SHARE_DELETE)))
1530 return STATUS_SHARING_VIOLATION;
1531 return 0;
1534 /* set the events that select waits for on this fd */
1535 void set_fd_events( struct fd *fd, int events )
1537 int user = fd->poll_index;
1538 assert( poll_users[user] == fd );
1540 set_fd_epoll_events( fd, user, events );
1542 if (events == -1) /* stop waiting on this fd completely */
1544 pollfd[user].fd = -1;
1545 pollfd[user].events = POLLERR;
1546 pollfd[user].revents = 0;
1548 else if (pollfd[user].fd != -1 || !pollfd[user].events)
1550 pollfd[user].fd = fd->unix_fd;
1551 pollfd[user].events = events;
1555 /* prepare an fd for unmounting its corresponding device */
1556 static inline void unmount_fd( struct fd *fd )
1558 assert( fd->inode );
1560 async_wake_up( fd->read_q, STATUS_VOLUME_DISMOUNTED );
1561 async_wake_up( fd->write_q, STATUS_VOLUME_DISMOUNTED );
1563 if (fd->poll_index != -1) set_fd_events( fd, -1 );
1565 if (fd->unix_fd != -1) close( fd->unix_fd );
1567 fd->unix_fd = -1;
1568 fd->no_fd_status = STATUS_VOLUME_DISMOUNTED;
1569 fd->closed->unix_fd = -1;
1570 fd->closed->unlink = 0;
1572 /* stop using Unix locks on this fd (existing locks have been removed by close) */
1573 fd->fs_locks = 0;
1576 /* allocate an fd object, without setting the unix fd yet */
1577 static struct fd *alloc_fd_object(void)
1579 struct fd *fd = alloc_object( &fd_ops );
1581 if (!fd) return NULL;
1583 fd->fd_ops = NULL;
1584 fd->user = NULL;
1585 fd->inode = NULL;
1586 fd->closed = NULL;
1587 fd->access = 0;
1588 fd->options = 0;
1589 fd->sharing = 0;
1590 fd->unix_fd = -1;
1591 fd->unix_name = NULL;
1592 fd->cacheable = 0;
1593 fd->signaled = 1;
1594 fd->fs_locks = 1;
1595 fd->poll_index = -1;
1596 fd->read_q = NULL;
1597 fd->write_q = NULL;
1598 fd->wait_q = NULL;
1599 fd->completion = NULL;
1600 list_init( &fd->inode_entry );
1601 list_init( &fd->locks );
1603 if ((fd->poll_index = add_poll_user( fd )) == -1)
1605 release_object( fd );
1606 return NULL;
1608 return fd;
1611 /* allocate a pseudo fd object, for objects that need to behave like files but don't have a unix fd */
1612 struct fd *alloc_pseudo_fd( const struct fd_ops *fd_user_ops, struct object *user, unsigned int options )
1614 struct fd *fd = alloc_object( &fd_ops );
1616 if (!fd) return NULL;
1618 fd->fd_ops = fd_user_ops;
1619 fd->user = user;
1620 fd->inode = NULL;
1621 fd->closed = NULL;
1622 fd->access = 0;
1623 fd->options = options;
1624 fd->sharing = 0;
1625 fd->unix_name = NULL;
1626 fd->unix_fd = -1;
1627 fd->cacheable = 0;
1628 fd->signaled = 0;
1629 fd->fs_locks = 0;
1630 fd->poll_index = -1;
1631 fd->read_q = NULL;
1632 fd->write_q = NULL;
1633 fd->wait_q = NULL;
1634 fd->completion = NULL;
1635 fd->no_fd_status = STATUS_BAD_DEVICE_TYPE;
1636 list_init( &fd->inode_entry );
1637 list_init( &fd->locks );
1638 return fd;
1641 /* duplicate an fd object for a different user */
1642 struct fd *dup_fd_object( struct fd *orig, unsigned int access, unsigned int sharing, unsigned int options )
1644 unsigned int err;
1645 struct fd *fd = alloc_fd_object();
1647 if (!fd) return NULL;
1649 fd->options = options;
1650 fd->cacheable = orig->cacheable;
1652 if (orig->unix_name)
1654 if (!(fd->unix_name = mem_alloc( strlen(orig->unix_name) + 1 ))) goto failed;
1655 strcpy( fd->unix_name, orig->unix_name );
1658 if (orig->inode)
1660 struct closed_fd *closed = mem_alloc( sizeof(*closed) );
1661 if (!closed) goto failed;
1662 if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1664 file_set_error();
1665 free( closed );
1666 goto failed;
1668 closed->unix_fd = fd->unix_fd;
1669 closed->unlink = 0;
1670 closed->unix_name = fd->unix_name;
1671 fd->closed = closed;
1672 fd->inode = (struct inode *)grab_object( orig->inode );
1673 list_add_head( &fd->inode->open, &fd->inode_entry );
1674 if ((err = check_sharing( fd, access, sharing, 0, options )))
1676 set_error( err );
1677 goto failed;
1680 else if ((fd->unix_fd = dup( orig->unix_fd )) == -1)
1682 file_set_error();
1683 goto failed;
1685 return fd;
1687 failed:
1688 release_object( fd );
1689 return NULL;
1692 /* find an existing fd object that can be reused for a mapping */
1693 struct fd *get_fd_object_for_mapping( struct fd *fd, unsigned int access, unsigned int sharing )
1695 struct fd *fd_ptr;
1697 if (!fd->inode) return NULL;
1699 LIST_FOR_EACH_ENTRY( fd_ptr, &fd->inode->open, struct fd, inode_entry )
1700 if (fd_ptr->access == access && fd_ptr->sharing == sharing)
1701 return (struct fd *)grab_object( fd_ptr );
1703 return NULL;
1706 /* set the status to return when the fd has no associated unix fd */
1707 void set_no_fd_status( struct fd *fd, unsigned int status )
1709 fd->no_fd_status = status;
1712 /* sets the user of an fd that previously had no user */
1713 void set_fd_user( struct fd *fd, const struct fd_ops *user_ops, struct object *user )
1715 assert( fd->fd_ops == NULL );
1716 fd->fd_ops = user_ops;
1717 fd->user = user;
1720 char *dup_fd_name( struct fd *root, const char *name )
1722 char *ret;
1724 if (!root) return strdup( name );
1725 if (!root->unix_name) return NULL;
1727 /* skip . prefix */
1728 if (name[0] == '.' && (!name[1] || name[1] == '/')) name++;
1730 if ((ret = malloc( strlen(root->unix_name) + strlen(name) + 2 )))
1732 strcpy( ret, root->unix_name );
1733 if (name[0] && name[0] != '/') strcat( ret, "/" );
1734 strcat( ret, name );
1736 return ret;
1739 /* open() wrapper that returns a struct fd with no fd user set */
1740 struct fd *open_fd( struct fd *root, const char *name, int flags, mode_t *mode, unsigned int access,
1741 unsigned int sharing, unsigned int options )
1743 struct stat st;
1744 struct closed_fd *closed_fd;
1745 struct fd *fd;
1746 int root_fd = -1;
1747 int rw_mode;
1749 if (((options & FILE_DELETE_ON_CLOSE) && !(access & DELETE)) ||
1750 ((options & FILE_DIRECTORY_FILE) && (flags & O_TRUNC)))
1752 set_error( STATUS_INVALID_PARAMETER );
1753 return NULL;
1756 if (!(fd = alloc_fd_object())) return NULL;
1758 fd->options = options;
1759 if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
1761 release_object( fd );
1762 return NULL;
1765 if (root)
1767 if ((root_fd = get_unix_fd( root )) == -1) goto error;
1768 if (fchdir( root_fd ) == -1)
1770 file_set_error();
1771 root_fd = -1;
1772 goto error;
1776 /* create the directory if needed */
1777 if ((options & FILE_DIRECTORY_FILE) && (flags & O_CREAT))
1779 if (mkdir( name, *mode ) == -1)
1781 if (errno != EEXIST || (flags & O_EXCL))
1783 file_set_error();
1784 goto error;
1787 flags &= ~(O_CREAT | O_EXCL | O_TRUNC);
1790 if ((access & FILE_UNIX_WRITE_ACCESS) && !(options & FILE_DIRECTORY_FILE))
1792 if (access & FILE_UNIX_READ_ACCESS) rw_mode = O_RDWR;
1793 else rw_mode = O_WRONLY;
1795 else rw_mode = O_RDONLY;
1797 fd->unix_name = dup_fd_name( root, name );
1799 if ((fd->unix_fd = open( name, rw_mode | (flags & ~O_TRUNC), *mode )) == -1)
1801 /* if we tried to open a directory for write access, retry read-only */
1802 if (errno == EISDIR)
1804 if ((access & FILE_UNIX_WRITE_ACCESS) || (flags & O_CREAT))
1805 fd->unix_fd = open( name, O_RDONLY | (flags & ~(O_TRUNC | O_CREAT | O_EXCL)), *mode );
1808 if (fd->unix_fd == -1)
1810 file_set_error();
1811 goto error;
1815 closed_fd->unix_fd = fd->unix_fd;
1816 closed_fd->unlink = 0;
1817 closed_fd->unix_name = fd->unix_name;
1818 fstat( fd->unix_fd, &st );
1819 *mode = st.st_mode;
1821 /* only bother with an inode for normal files and directories */
1822 if (S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))
1824 unsigned int err;
1825 struct inode *inode = get_inode( st.st_dev, st.st_ino, fd->unix_fd );
1827 if (!inode)
1829 /* we can close the fd because there are no others open on the same file,
1830 * otherwise we wouldn't have failed to allocate a new inode
1832 goto error;
1834 fd->inode = inode;
1835 fd->closed = closed_fd;
1836 fd->cacheable = !inode->device->removable;
1837 list_add_head( &inode->open, &fd->inode_entry );
1838 closed_fd = NULL;
1840 /* check directory options */
1841 if ((options & FILE_DIRECTORY_FILE) && !S_ISDIR(st.st_mode))
1843 set_error( STATUS_NOT_A_DIRECTORY );
1844 goto error;
1846 if ((options & FILE_NON_DIRECTORY_FILE) && S_ISDIR(st.st_mode))
1848 set_error( STATUS_FILE_IS_A_DIRECTORY );
1849 goto error;
1851 if ((err = check_sharing( fd, access, sharing, flags, options )))
1853 set_error( err );
1854 goto error;
1856 fd->closed->unlink = (options & FILE_DELETE_ON_CLOSE) != 0;
1857 if (flags & O_TRUNC)
1859 if (S_ISDIR(st.st_mode))
1861 set_error( STATUS_OBJECT_NAME_COLLISION );
1862 goto error;
1864 ftruncate( fd->unix_fd, 0 );
1867 else /* special file */
1869 if (options & FILE_DELETE_ON_CLOSE) /* we can't unlink special files */
1871 set_error( STATUS_INVALID_PARAMETER );
1872 goto error;
1874 free( closed_fd );
1875 fd->cacheable = 1;
1877 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1878 return fd;
1880 error:
1881 release_object( fd );
1882 free( closed_fd );
1883 if (root_fd != -1) fchdir( server_dir_fd ); /* go back to the server dir */
1884 return NULL;
1887 /* create an fd for an anonymous file */
1888 /* if the function fails the unix fd is closed */
1889 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user,
1890 unsigned int options )
1892 struct fd *fd = alloc_fd_object();
1894 if (fd)
1896 set_fd_user( fd, fd_user_ops, user );
1897 fd->unix_fd = unix_fd;
1898 fd->options = options;
1899 return fd;
1901 close( unix_fd );
1902 return NULL;
1905 /* retrieve the object that is using an fd */
1906 void *get_fd_user( struct fd *fd )
1908 return fd->user;
1911 /* retrieve the opening options for the fd */
1912 unsigned int get_fd_options( struct fd *fd )
1914 return fd->options;
1917 /* retrieve the unix fd for an object */
1918 int get_unix_fd( struct fd *fd )
1920 if (fd->unix_fd == -1) set_error( fd->no_fd_status );
1921 return fd->unix_fd;
1924 /* check if two file descriptors point to the same file */
1925 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
1927 return fd1->inode == fd2->inode;
1930 /* allow the fd to be cached (can't be reset once set) */
1931 void allow_fd_caching( struct fd *fd )
1933 fd->cacheable = 1;
1936 /* check if fd is on a removable device */
1937 int is_fd_removable( struct fd *fd )
1939 return (fd->inode && fd->inode->device->removable);
1942 /* set or clear the fd signaled state */
1943 void set_fd_signaled( struct fd *fd, int signaled )
1945 fd->signaled = signaled;
1946 if (signaled) wake_up( fd->user, 0 );
1949 /* set or clear the fd signaled state */
1950 int is_fd_signaled( struct fd *fd )
1952 return fd->signaled;
1955 /* handler for close_handle that refuses to close fd-associated handles in other processes */
1956 int fd_close_handle( struct object *obj, struct process *process, obj_handle_t handle )
1958 return (!current || current->process == process);
1961 /* check if events are pending and if yes return which one(s) */
1962 int check_fd_events( struct fd *fd, int events )
1964 struct pollfd pfd;
1966 if (fd->unix_fd == -1) return POLLERR;
1967 if (fd->inode) return events; /* regular files are always signaled */
1969 pfd.fd = fd->unix_fd;
1970 pfd.events = events;
1971 if (poll( &pfd, 1, 0 ) <= 0) return 0;
1972 return pfd.revents;
1975 /* default signaled() routine for objects that poll() on an fd */
1976 int default_fd_signaled( struct object *obj, struct wait_queue_entry *entry )
1978 struct fd *fd = get_obj_fd( obj );
1979 int ret = fd->signaled;
1980 release_object( fd );
1981 return ret;
1984 /* default map_access() routine for objects that behave like an fd */
1985 unsigned int default_fd_map_access( struct object *obj, unsigned int access )
1987 if (access & GENERIC_READ) access |= FILE_GENERIC_READ;
1988 if (access & GENERIC_WRITE) access |= FILE_GENERIC_WRITE;
1989 if (access & GENERIC_EXECUTE) access |= FILE_GENERIC_EXECUTE;
1990 if (access & GENERIC_ALL) access |= FILE_ALL_ACCESS;
1991 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
1994 int default_fd_get_poll_events( struct fd *fd )
1996 int events = 0;
1998 if (async_waiting( fd->read_q )) events |= POLLIN;
1999 if (async_waiting( fd->write_q )) events |= POLLOUT;
2000 return events;
2003 /* default handler for poll() events */
2004 void default_poll_event( struct fd *fd, int event )
2006 if (event & (POLLIN | POLLERR | POLLHUP)) async_wake_up( fd->read_q, STATUS_ALERTED );
2007 if (event & (POLLOUT | POLLERR | POLLHUP)) async_wake_up( fd->write_q, STATUS_ALERTED );
2009 /* if an error occurred, stop polling this fd to avoid busy-looping */
2010 if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
2011 else if (!fd->inode) set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2014 struct async *fd_queue_async( struct fd *fd, const async_data_t *data, int type )
2016 struct async_queue *queue;
2017 struct async *async;
2019 switch (type)
2021 case ASYNC_TYPE_READ:
2022 if (!fd->read_q && !(fd->read_q = create_async_queue( fd ))) return NULL;
2023 queue = fd->read_q;
2024 break;
2025 case ASYNC_TYPE_WRITE:
2026 if (!fd->write_q && !(fd->write_q = create_async_queue( fd ))) return NULL;
2027 queue = fd->write_q;
2028 break;
2029 case ASYNC_TYPE_WAIT:
2030 if (!fd->wait_q && !(fd->wait_q = create_async_queue( fd ))) return NULL;
2031 queue = fd->wait_q;
2032 break;
2033 default:
2034 queue = NULL;
2035 assert(0);
2038 if ((async = create_async( current, queue, data )) && type != ASYNC_TYPE_WAIT)
2040 if (!fd->inode)
2041 set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
2042 else /* regular files are always ready for read and write */
2043 async_wake_up( queue, STATUS_ALERTED );
2045 return async;
2048 void fd_async_wake_up( struct fd *fd, int type, unsigned int status )
2050 switch (type)
2052 case ASYNC_TYPE_READ:
2053 async_wake_up( fd->read_q, status );
2054 break;
2055 case ASYNC_TYPE_WRITE:
2056 async_wake_up( fd->write_q, status );
2057 break;
2058 case ASYNC_TYPE_WAIT:
2059 async_wake_up( fd->wait_q, status );
2060 break;
2061 default:
2062 assert(0);
2066 void fd_reselect_async( struct fd *fd, struct async_queue *queue )
2068 fd->fd_ops->reselect_async( fd, queue );
2071 void no_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
2073 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2076 void default_fd_queue_async( struct fd *fd, const async_data_t *data, int type, int count )
2078 struct async *async;
2080 if ((async = fd_queue_async( fd, data, type )))
2082 release_object( async );
2083 set_error( STATUS_PENDING );
2087 /* default reselect_async() fd routine */
2088 void default_fd_reselect_async( struct fd *fd, struct async_queue *queue )
2090 if (queue != fd->wait_q)
2092 int poll_events = fd->fd_ops->get_poll_events( fd );
2093 int events = check_fd_events( fd, poll_events );
2094 if (events) fd->fd_ops->poll_event( fd, events );
2095 else set_fd_events( fd, poll_events );
2099 /* default cancel_async() fd routine */
2100 int default_fd_cancel_async( struct fd *fd, struct process *process, struct thread *thread, client_ptr_t iosb )
2102 int n = 0;
2104 n += async_wake_up_by( fd->read_q, process, thread, iosb, STATUS_CANCELLED );
2105 n += async_wake_up_by( fd->write_q, process, thread, iosb, STATUS_CANCELLED );
2106 n += async_wake_up_by( fd->wait_q, process, thread, iosb, STATUS_CANCELLED );
2107 return n;
2110 static inline int is_valid_mounted_device( struct stat *st )
2112 #if defined(linux) || defined(__sun__)
2113 return S_ISBLK( st->st_mode );
2114 #else
2115 /* disks are char devices on *BSD */
2116 return S_ISCHR( st->st_mode );
2117 #endif
2120 /* close all Unix file descriptors on a device to allow unmounting it */
2121 static void unmount_device( struct fd *device_fd )
2123 unsigned int i;
2124 struct stat st;
2125 struct device *device;
2126 struct inode *inode;
2127 struct fd *fd;
2128 int unix_fd = get_unix_fd( device_fd );
2130 if (unix_fd == -1) return;
2132 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2134 set_error( STATUS_INVALID_PARAMETER );
2135 return;
2138 if (!(device = get_device( st.st_rdev, -1 ))) return;
2140 for (i = 0; i < INODE_HASH_SIZE; i++)
2142 LIST_FOR_EACH_ENTRY( inode, &device->inode_hash[i], struct inode, entry )
2144 LIST_FOR_EACH_ENTRY( fd, &inode->open, struct fd, inode_entry )
2146 unmount_fd( fd );
2148 inode_close_pending( inode, 0 );
2151 /* remove it from the hash table */
2152 list_remove( &device->entry );
2153 list_init( &device->entry );
2154 release_object( device );
2157 /* default read() routine */
2158 obj_handle_t no_fd_read( struct fd *fd, const async_data_t *async, int blocking, file_pos_t pos )
2160 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2161 return 0;
2164 /* default write() routine */
2165 obj_handle_t no_fd_write( struct fd *fd, const async_data_t *async, int blocking,
2166 file_pos_t pos, data_size_t *written )
2168 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2169 return 0;
2172 /* default flush() routine */
2173 obj_handle_t no_fd_flush( struct fd *fd, const async_data_t *async, int blocking )
2175 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2176 return 0;
2179 /* default ioctl() routine */
2180 obj_handle_t no_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async, int blocking )
2182 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2183 return 0;
2186 /* default ioctl() routine */
2187 obj_handle_t default_fd_ioctl( struct fd *fd, ioctl_code_t code, const async_data_t *async, int blocking )
2189 switch(code)
2191 case FSCTL_DISMOUNT_VOLUME:
2192 unmount_device( fd );
2193 return 0;
2194 default:
2195 set_error( STATUS_NOT_SUPPORTED );
2196 return 0;
2200 /* same as get_handle_obj but retrieve the struct fd associated to the object */
2201 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
2202 unsigned int access )
2204 struct fd *fd = NULL;
2205 struct object *obj;
2207 if ((obj = get_handle_obj( process, handle, access, NULL )))
2209 fd = get_obj_fd( obj );
2210 release_object( obj );
2212 return fd;
2215 /* set disposition for the fd */
2216 static void set_fd_disposition( struct fd *fd, int unlink )
2218 struct stat st;
2220 if (!fd->inode)
2222 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2223 return;
2226 if (fd->unix_fd == -1)
2228 set_error( fd->no_fd_status );
2229 return;
2232 if (fstat( fd->unix_fd, &st ) == -1)
2234 file_set_error();
2235 return;
2238 /* can't unlink special files */
2239 if (unlink && !S_ISDIR(st.st_mode) && !S_ISREG(st.st_mode))
2241 set_error( STATUS_INVALID_PARAMETER );
2242 return;
2245 /* can't unlink files we don't have permission to access */
2246 if (unlink && !(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
2248 set_error( STATUS_CANNOT_DELETE );
2249 return;
2252 fd->closed->unlink = unlink || (fd->options & FILE_DELETE_ON_CLOSE);
2255 /* set new name for the fd */
2256 static void set_fd_name( struct fd *fd, struct fd *root, const char *nameptr,
2257 data_size_t len, int create_link )
2259 struct inode *inode;
2260 struct stat st;
2261 char *name;
2263 if (!fd->inode || !fd->unix_name)
2265 set_error( STATUS_OBJECT_TYPE_MISMATCH );
2266 return;
2268 if (!len || ((nameptr[0] == '/') ^ !root))
2270 set_error( STATUS_OBJECT_PATH_SYNTAX_BAD );
2271 return;
2273 if (!(name = mem_alloc( len + 1 ))) return;
2274 memcpy( name, nameptr, len );
2275 name[len] = 0;
2277 if (root)
2279 char *combined_name = dup_fd_name( root, name );
2280 if (!combined_name)
2282 set_error( STATUS_NO_MEMORY );
2283 goto failed;
2285 free( name );
2286 name = combined_name;
2289 /* when creating a hard link, source cannot be a dir */
2290 if (create_link && fd->unix_fd != -1 &&
2291 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode ))
2293 set_error( STATUS_FILE_IS_A_DIRECTORY );
2294 goto failed;
2297 if (!stat( name, &st ))
2299 /* can't replace directories or special files */
2300 if (!S_ISREG( st.st_mode ))
2302 set_error( STATUS_ACCESS_DENIED );
2303 goto failed;
2306 /* can't replace an opened file */
2307 if ((inode = get_inode( st.st_dev, st.st_ino, -1 )))
2309 int is_empty = list_empty( &inode->open );
2310 release_object( inode );
2311 if (!is_empty)
2313 set_error( STATUS_ACCESS_DENIED );
2314 goto failed;
2318 /* link() expects that the target doesn't exist */
2319 /* rename() cannot replace files with directories */
2320 if (create_link || (fd->unix_fd != -1 &&
2321 !fstat( fd->unix_fd, &st ) && S_ISDIR( st.st_mode )))
2323 if (unlink( name ))
2325 file_set_error();
2326 goto failed;
2331 if (create_link)
2333 if (link( fd->unix_name, name ))
2334 file_set_error();
2335 free( name );
2336 return;
2339 if (rename( fd->unix_name, name ))
2341 file_set_error();
2342 goto failed;
2345 free( fd->unix_name );
2346 fd->unix_name = name;
2347 fd->closed->unix_name = name;
2348 return;
2350 failed:
2351 free( name );
2354 struct completion *fd_get_completion( struct fd *fd, apc_param_t *p_key )
2356 *p_key = fd->comp_key;
2357 return fd->completion ? (struct completion *)grab_object( fd->completion ) : NULL;
2360 void fd_copy_completion( struct fd *src, struct fd *dst )
2362 assert( !dst->completion );
2363 dst->completion = fd_get_completion( src, &dst->comp_key );
2366 /* flush a file buffers */
2367 DECL_HANDLER(flush)
2369 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, 0 );
2371 if (fd)
2373 reply->event = fd->fd_ops->flush( fd, &req->async, req->blocking );
2374 release_object( fd );
2378 /* open a file object */
2379 DECL_HANDLER(open_file_object)
2381 struct unicode_str name;
2382 struct directory *root = NULL;
2383 struct object *obj, *result;
2385 get_req_unicode_str( &name );
2386 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
2388 if (get_error() != STATUS_OBJECT_TYPE_MISMATCH) return;
2389 if (!(obj = (struct object *)get_file_obj( current->process, req->rootdir, 0 ))) return;
2390 if (name.len)
2392 release_object( obj );
2393 set_error( STATUS_OBJECT_PATH_NOT_FOUND );
2394 return;
2396 clear_error();
2398 else
2400 obj = open_object_dir( root, &name, req->attributes, NULL );
2401 if (root) release_object( root );
2402 if (!obj) return;
2405 if ((result = obj->ops->open_file( obj, req->access, req->sharing, req->options )))
2407 reply->handle = alloc_handle( current->process, result, req->access, req->attributes );
2408 release_object( result );
2410 release_object( obj );
2413 /* get the Unix name from a file handle */
2414 DECL_HANDLER(get_handle_unix_name)
2416 struct fd *fd;
2418 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2420 if (fd->unix_name)
2422 data_size_t name_len = strlen( fd->unix_name );
2423 reply->name_len = name_len;
2424 if (name_len <= get_reply_max_size()) set_reply_data( fd->unix_name, name_len );
2425 else set_error( STATUS_BUFFER_OVERFLOW );
2427 else set_error( STATUS_OBJECT_TYPE_MISMATCH );
2428 release_object( fd );
2432 /* get a Unix fd to access a file */
2433 DECL_HANDLER(get_handle_fd)
2435 struct fd *fd;
2437 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2439 int unix_fd = get_unix_fd( fd );
2440 if (unix_fd != -1)
2442 reply->type = fd->fd_ops->get_fd_type( fd );
2443 reply->cacheable = fd->cacheable;
2444 reply->options = fd->options;
2445 reply->access = get_handle_access( current->process, req->handle );
2446 send_client_fd( current->process, unix_fd, req->handle );
2448 release_object( fd );
2452 /* perform a read on a file object */
2453 DECL_HANDLER(read)
2455 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_READ_DATA );
2457 if (fd)
2459 reply->wait = fd->fd_ops->read( fd, &req->async, req->blocking, req->pos );
2460 reply->options = fd->options;
2461 release_object( fd );
2465 /* perform a write on a file object */
2466 DECL_HANDLER(write)
2468 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, FILE_WRITE_DATA );
2470 if (fd)
2472 reply->wait = fd->fd_ops->write( fd, &req->async, req->blocking, req->pos, &reply->size );
2473 reply->options = fd->options;
2474 release_object( fd );
2478 /* perform an ioctl on a file */
2479 DECL_HANDLER(ioctl)
2481 unsigned int access = (req->code >> 14) & (FILE_READ_DATA|FILE_WRITE_DATA);
2482 struct fd *fd = get_handle_fd_obj( current->process, req->async.handle, access );
2484 if (fd)
2486 reply->wait = fd->fd_ops->ioctl( fd, req->code, &req->async, req->blocking );
2487 reply->options = fd->options;
2488 release_object( fd );
2492 /* create / reschedule an async I/O */
2493 DECL_HANDLER(register_async)
2495 unsigned int access;
2496 struct fd *fd;
2498 switch(req->type)
2500 case ASYNC_TYPE_READ:
2501 access = FILE_READ_DATA;
2502 break;
2503 case ASYNC_TYPE_WRITE:
2504 access = FILE_WRITE_DATA;
2505 break;
2506 default:
2507 set_error( STATUS_INVALID_PARAMETER );
2508 return;
2511 if ((fd = get_handle_fd_obj( current->process, req->async.handle, access )))
2513 if (get_unix_fd( fd ) != -1) fd->fd_ops->queue_async( fd, &req->async, req->type, req->count );
2514 release_object( fd );
2518 /* cancels all async I/O */
2519 DECL_HANDLER(cancel_async)
2521 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2522 struct thread *thread = req->only_thread ? current : NULL;
2524 if (fd)
2526 int count = fd->fd_ops->cancel_async( fd, current->process, thread, req->iosb );
2527 if (!count && req->iosb) set_error( STATUS_NOT_FOUND );
2528 release_object( fd );
2532 /* attach completion object to a fd */
2533 DECL_HANDLER(set_completion_info)
2535 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2537 if (fd)
2539 if (!(fd->options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) && !fd->completion)
2541 fd->completion = get_completion_obj( current->process, req->chandle, IO_COMPLETION_MODIFY_STATE );
2542 fd->comp_key = req->ckey;
2544 else set_error( STATUS_INVALID_PARAMETER );
2545 release_object( fd );
2549 /* push new completion msg into a completion queue attached to the fd */
2550 DECL_HANDLER(add_fd_completion)
2552 struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
2553 if (fd)
2555 if (fd->completion)
2556 add_completion( fd->completion, fd->comp_key, req->cvalue, req->status, req->information );
2557 release_object( fd );
2561 /* set fd disposition information */
2562 DECL_HANDLER(set_fd_disp_info)
2564 struct fd *fd = get_handle_fd_obj( current->process, req->handle, DELETE );
2565 if (fd)
2567 set_fd_disposition( fd, req->unlink );
2568 release_object( fd );
2572 /* set fd name information */
2573 DECL_HANDLER(set_fd_name_info)
2575 struct fd *fd, *root_fd = NULL;
2577 if (req->rootdir)
2579 struct dir *root;
2581 if (!(root = get_dir_obj( current->process, req->rootdir, 0 ))) return;
2582 root_fd = get_obj_fd( (struct object *)root );
2583 release_object( root );
2584 if (!root_fd) return;
2587 if ((fd = get_handle_fd_obj( current->process, req->handle, 0 )))
2589 set_fd_name( fd, root_fd, get_req_data(), get_req_data_size(), req->link );
2590 release_object( fd );
2592 if (root_fd) release_object( root_fd );