Check file sharing permissions based on the file inode instead of the
[wine] / server / fd.c
1 /*
2  * Server-side file descriptor management
3  *
4  * Copyright (C) 2000, 2003 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21
22 #include "config.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <limits.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #ifdef HAVE_SYS_POLL_H
33 #include <sys/poll.h>
34 #endif
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #include <unistd.h>
39
40 #include "object.h"
41 #include "file.h"
42 #include "handle.h"
43 #include "process.h"
44 #include "request.h"
45
46 /* Because of the stupid Posix locking semantics, we need to keep
47  * track of all file descriptors referencing a given file, and not
48  * close a single one until all the locks are gone (sigh).
49  */
50
51 /* file descriptor object */
52
53 /* closed_fd is used to keep track of the unix fd belonging to a closed fd object */
54 struct closed_fd
55 {
56     struct closed_fd *next;   /* next fd in close list */
57     int               fd;     /* the unix file descriptor */
58 };
59
60 struct fd
61 {
62     struct object        obj;         /* object header */
63     const struct fd_ops *fd_ops;      /* file descriptor operations */
64     struct inode        *inode;       /* inode that this fd belongs to */
65     struct list          inode_entry; /* entry in inode fd list */
66     struct closed_fd    *closed;      /* structure to store the unix fd at destroy time */
67     struct object       *user;        /* object using this file descriptor */
68     struct list          locks;       /* list of locks on this fd */
69     unsigned int         access;      /* file access (GENERIC_READ/WRITE) */
70     unsigned int         sharing;     /* file sharing mode */
71     int                  unix_fd;     /* unix file descriptor */
72     int                  fs_locks;    /* can we use filesystem locks for this fd? */
73     int                  poll_index;  /* index of fd in poll array */
74 };
75
76 static void fd_dump( struct object *obj, int verbose );
77 static void fd_destroy( struct object *obj );
78
79 static const struct object_ops fd_ops =
80 {
81     sizeof(struct fd),        /* size */
82     fd_dump,                  /* dump */
83     no_add_queue,             /* add_queue */
84     NULL,                     /* remove_queue */
85     NULL,                     /* signaled */
86     NULL,                     /* satisfied */
87     no_get_fd,                /* get_fd */
88     fd_destroy                /* destroy */
89 };
90
91 /* inode object */
92
93 struct inode
94 {
95     struct object       obj;        /* object header */
96     struct list         entry;      /* inode hash list entry */
97     unsigned int        hash;       /* hashing code */
98     dev_t               dev;        /* device number */
99     ino_t               ino;        /* inode number */
100     struct list         open;       /* list of open file descriptors */
101     struct list         locks;      /* list of file locks */
102     struct closed_fd   *closed;     /* list of file descriptors to close at destroy time */
103 };
104
105 static void inode_dump( struct object *obj, int verbose );
106 static void inode_destroy( struct object *obj );
107
108 static const struct object_ops inode_ops =
109 {
110     sizeof(struct inode),     /* size */
111     inode_dump,               /* dump */
112     no_add_queue,             /* add_queue */
113     NULL,                     /* remove_queue */
114     NULL,                     /* signaled */
115     NULL,                     /* satisfied */
116     no_get_fd,                /* get_fd */
117     inode_destroy             /* destroy */
118 };
119
120 /* file lock object */
121
122 struct file_lock
123 {
124     struct object       obj;         /* object header */
125     struct fd          *fd;          /* fd owning this lock */
126     struct list         fd_entry;    /* entry in list of locks on a given fd */
127     struct list         inode_entry; /* entry in inode list of locks */
128     int                 shared;      /* shared lock? */
129     file_pos_t          start;       /* locked region is interval [start;end) */
130     file_pos_t          end;
131     struct process     *process;     /* process owning this lock */
132     struct list         proc_entry;  /* entry in list of locks owned by the process */
133 };
134
135 static void file_lock_dump( struct object *obj, int verbose );
136 static int file_lock_signaled( struct object *obj, struct thread *thread );
137
138 static const struct object_ops file_lock_ops =
139 {
140     sizeof(struct file_lock),   /* size */
141     file_lock_dump,             /* dump */
142     add_queue,                  /* add_queue */
143     remove_queue,               /* remove_queue */
144     file_lock_signaled,         /* signaled */
145     no_satisfied,               /* satisfied */
146     no_get_fd,                  /* get_fd */
147     no_destroy                  /* destroy */
148 };
149
150
151 #define OFF_T_MAX       (~((file_pos_t)1 << (8*sizeof(off_t)-1)))
152 #define FILE_POS_T_MAX  (~(file_pos_t)0)
153
154 static file_pos_t max_unix_offset = OFF_T_MAX;
155
156 #define DUMP_LONG_LONG(val) do { \
157     if (sizeof(val) > sizeof(unsigned long) && (val) > ~0UL) \
158         fprintf( stderr, "%lx%08lx", (unsigned long)((val) >> 32), (unsigned long)(val) ); \
159     else \
160         fprintf( stderr, "%lx", (unsigned long)(val) ); \
161   } while (0)
162
163
164
165 /****************************************************************/
166 /* timeouts support */
167
168 struct timeout_user
169 {
170     struct timeout_user  *next;       /* next in sorted timeout list */
171     struct timeout_user  *prev;       /* prev in sorted timeout list */
172     struct timeval        when;       /* timeout expiry (absolute time) */
173     timeout_callback      callback;   /* callback function */
174     void                 *private;    /* callback private data */
175 };
176
177 static struct timeout_user *timeout_head;   /* sorted timeouts list head */
178 static struct timeout_user *timeout_tail;   /* sorted timeouts list tail */
179
180 /* add a timeout user */
181 struct timeout_user *add_timeout_user( struct timeval *when, timeout_callback func, void *private )
182 {
183     struct timeout_user *user;
184     struct timeout_user *pos;
185
186     if (!(user = mem_alloc( sizeof(*user) ))) return NULL;
187     user->when     = *when;
188     user->callback = func;
189     user->private  = private;
190
191     /* Now insert it in the linked list */
192
193     for (pos = timeout_head; pos; pos = pos->next)
194         if (!time_before( &pos->when, when )) break;
195
196     if (pos)  /* insert it before 'pos' */
197     {
198         if ((user->prev = pos->prev)) user->prev->next = user;
199         else timeout_head = user;
200         user->next = pos;
201         pos->prev = user;
202     }
203     else  /* insert it at the tail */
204     {
205         user->next = NULL;
206         if (timeout_tail) timeout_tail->next = user;
207         else timeout_head = user;
208         user->prev = timeout_tail;
209         timeout_tail = user;
210     }
211     return user;
212 }
213
214 /* remove a timeout user */
215 void remove_timeout_user( struct timeout_user *user )
216 {
217     if (user->next) user->next->prev = user->prev;
218     else timeout_tail = user->prev;
219     if (user->prev) user->prev->next = user->next;
220     else timeout_head = user->next;
221     free( user );
222 }
223
224 /* add a timeout in milliseconds to an absolute time */
225 void add_timeout( struct timeval *when, int timeout )
226 {
227     if (timeout)
228     {
229         long sec = timeout / 1000;
230         if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
231         {
232             when->tv_usec -= 1000000;
233             when->tv_sec++;
234         }
235         when->tv_sec += sec;
236     }
237 }
238
239 /* handle the next expired timeout */
240 inline static void handle_timeout(void)
241 {
242     struct timeout_user *user = timeout_head;
243     timeout_head = user->next;
244     if (user->next) user->next->prev = user->prev;
245     else timeout_tail = user->prev;
246     user->callback( user->private );
247     free( user );
248 }
249
250
251 /****************************************************************/
252 /* poll support */
253
254 static struct fd **poll_users;              /* users array */
255 static struct pollfd *pollfd;               /* poll fd array */
256 static int nb_users;                        /* count of array entries actually in use */
257 static int active_users;                    /* current number of active users */
258 static int allocated_users;                 /* count of allocated entries in the array */
259 static struct fd **freelist;                /* list of free entries in the array */
260
261 /* add a user in the poll array and return its index, or -1 on failure */
262 static int add_poll_user( struct fd *fd )
263 {
264     int ret;
265     if (freelist)
266     {
267         ret = freelist - poll_users;
268         freelist = (struct fd **)poll_users[ret];
269     }
270     else
271     {
272         if (nb_users == allocated_users)
273         {
274             struct fd **newusers;
275             struct pollfd *newpoll;
276             int new_count = allocated_users ? (allocated_users + allocated_users / 2) : 16;
277             if (!(newusers = realloc( poll_users, new_count * sizeof(*poll_users) ))) return -1;
278             if (!(newpoll = realloc( pollfd, new_count * sizeof(*pollfd) )))
279             {
280                 if (allocated_users)
281                     poll_users = newusers;
282                 else
283                     free( newusers );
284                 return -1;
285             }
286             poll_users = newusers;
287             pollfd = newpoll;
288             allocated_users = new_count;
289         }
290         ret = nb_users++;
291     }
292     pollfd[ret].fd = -1;
293     pollfd[ret].events = 0;
294     pollfd[ret].revents = 0;
295     poll_users[ret] = fd;
296     active_users++;
297     return ret;
298 }
299
300 /* remove a user from the poll list */
301 static void remove_poll_user( struct fd *fd, int user )
302 {
303     assert( user >= 0 );
304     assert( poll_users[user] == fd );
305     pollfd[user].fd = -1;
306     pollfd[user].events = 0;
307     pollfd[user].revents = 0;
308     poll_users[user] = (struct fd *)freelist;
309     freelist = &poll_users[user];
310     active_users--;
311 }
312
313
314 /* server main poll() loop */
315 void main_loop(void)
316 {
317     int ret;
318
319     while (active_users)
320     {
321         long diff = -1;
322         if (timeout_head)
323         {
324             struct timeval now;
325             gettimeofday( &now, NULL );
326             while (timeout_head)
327             {
328                 if (!time_before( &now, &timeout_head->when )) handle_timeout();
329                 else
330                 {
331                     diff = (timeout_head->when.tv_sec - now.tv_sec) * 1000
332                             + (timeout_head->when.tv_usec - now.tv_usec) / 1000;
333                     break;
334                 }
335             }
336             if (!active_users) break;  /* last user removed by a timeout */
337         }
338         ret = poll( pollfd, nb_users, diff );
339         if (ret > 0)
340         {
341             int i;
342             for (i = 0; i < nb_users; i++)
343             {
344                 if (pollfd[i].revents)
345                 {
346                     fd_poll_event( poll_users[i], pollfd[i].revents );
347                     if (!--ret) break;
348                 }
349             }
350         }
351     }
352 }
353
354
355 /****************************************************************/
356 /* inode functions */
357
358 #define HASH_SIZE 37
359
360 static struct list inode_hash[HASH_SIZE];
361
362 /* close all pending file descriptors in the closed list */
363 static void inode_close_pending( struct inode *inode )
364 {
365     while (inode->closed)
366     {
367         struct closed_fd *fd = inode->closed;
368         inode->closed = fd->next;
369         close( fd->fd );
370         free( fd );
371     }
372 }
373
374
375 static void inode_dump( struct object *obj, int verbose )
376 {
377     struct inode *inode = (struct inode *)obj;
378     fprintf( stderr, "Inode dev=" );
379     DUMP_LONG_LONG( inode->dev );
380     fprintf( stderr, " ino=" );
381     DUMP_LONG_LONG( inode->ino );
382     fprintf( stderr, "\n" );
383 }
384
385 static void inode_destroy( struct object *obj )
386 {
387     struct inode *inode = (struct inode *)obj;
388
389     assert( list_empty(&inode->open) );
390     assert( list_empty(&inode->locks) );
391
392     list_remove( &inode->entry );
393     inode_close_pending( inode );
394 }
395
396 /* retrieve the inode object for a given fd, creating it if needed */
397 static struct inode *get_inode( dev_t dev, ino_t ino )
398 {
399     struct list *ptr;
400     struct inode *inode;
401     unsigned int hash = (dev ^ ino) % HASH_SIZE;
402
403     if (inode_hash[hash].next)
404     {
405         LIST_FOR_EACH( ptr, &inode_hash[hash] )
406         {
407             inode = LIST_ENTRY( ptr, struct inode, entry );
408             if (inode->dev == dev && inode->ino == ino)
409                 return (struct inode *)grab_object( inode );
410         }
411     }
412     else list_init( &inode_hash[hash] );
413
414     /* not found, create it */
415     if ((inode = alloc_object( &inode_ops )))
416     {
417         inode->hash   = hash;
418         inode->dev    = dev;
419         inode->ino    = ino;
420         inode->closed = NULL;
421         list_init( &inode->open );
422         list_init( &inode->locks );
423         list_add_head( &inode_hash[hash], &inode->entry );
424     }
425     return inode;
426 }
427
428 /* add fd to the indoe list of file descriptors to close */
429 static void inode_add_closed_fd( struct inode *inode, struct closed_fd *fd )
430 {
431     if (!list_empty( &inode->locks ))
432     {
433         fd->next = inode->closed;
434         inode->closed = fd;
435     }
436     else  /* no locks on this inode, we can close the fd right away */
437     {
438         close( fd->fd );
439         free( fd );
440     }
441 }
442
443
444 /****************************************************************/
445 /* file lock functions */
446
447 static void file_lock_dump( struct object *obj, int verbose )
448 {
449     struct file_lock *lock = (struct file_lock *)obj;
450     fprintf( stderr, "Lock %s fd=%p proc=%p start=",
451              lock->shared ? "shared" : "excl", lock->fd, lock->process );
452     DUMP_LONG_LONG( lock->start );
453     fprintf( stderr, " end=" );
454     DUMP_LONG_LONG( lock->end );
455     fprintf( stderr, "\n" );
456 }
457
458 static int file_lock_signaled( struct object *obj, struct thread *thread )
459 {
460     struct file_lock *lock = (struct file_lock *)obj;
461     /* lock is signaled if it has lost its owner */
462     return !lock->process;
463 }
464
465 /* set (or remove) a Unix lock if possible for the given range */
466 static int set_unix_lock( struct fd *fd, file_pos_t start, file_pos_t end, int type )
467 {
468     struct flock fl;
469
470     if (!fd->fs_locks) return 1;  /* no fs locks possible for this fd */
471     for (;;)
472     {
473         if (start == end) return 1;  /* can't set zero-byte lock */
474         if (start > max_unix_offset) return 1;  /* ignore it */
475         fl.l_type   = type;
476         fl.l_whence = SEEK_SET;
477         fl.l_start  = start;
478         if (!end || end > max_unix_offset) fl.l_len = 0;
479         else fl.l_len = end - start;
480         if (fcntl( fd->unix_fd, F_SETLK, &fl ) != -1) return 1;
481
482         switch(errno)
483         {
484         case EACCES:
485             /* check whether locks work at all on this file system */
486             if (fcntl( fd->unix_fd, F_GETLK, &fl ) != -1)
487             {
488                 set_error( STATUS_FILE_LOCK_CONFLICT );
489                 return 0;
490             }
491             /* fall through */
492         case EIO:
493         case ENOLCK:
494             /* no locking on this fs, just ignore it */
495             fd->fs_locks = 0;
496             return 1;
497         case EAGAIN:
498             set_error( STATUS_FILE_LOCK_CONFLICT );
499             return 0;
500         case EBADF:
501             /* this can happen if we try to set a write lock on a read-only file */
502             /* we just ignore that error */
503             if (fl.l_type == F_WRLCK) return 1;
504             set_error( STATUS_ACCESS_DENIED );
505             return 0;
506 #ifdef EOVERFLOW
507         case EOVERFLOW:
508 #endif
509         case EINVAL:
510             /* this can happen if off_t is 64-bit but the kernel only supports 32-bit */
511             /* in that case we shrink the limit and retry */
512             if (max_unix_offset > INT_MAX)
513             {
514                 max_unix_offset = INT_MAX;
515                 break;  /* retry */
516             }
517             /* fall through */
518         default:
519             file_set_error();
520             return 0;
521         }
522     }
523 }
524
525 /* check if interval [start;end) overlaps the lock */
526 inline static int lock_overlaps( struct file_lock *lock, file_pos_t start, file_pos_t end )
527 {
528     if (lock->end && start >= lock->end) return 0;
529     if (end && lock->start >= end) return 0;
530     return 1;
531 }
532
533 /* remove Unix locks for all bytes in the specified area that are no longer locked */
534 static void remove_unix_locks( struct fd *fd, file_pos_t start, file_pos_t end )
535 {
536     struct hole
537     {
538         struct hole *next;
539         struct hole *prev;
540         file_pos_t   start;
541         file_pos_t   end;
542     } *first, *cur, *next, *buffer;
543
544     struct list *ptr;
545     int count = 0;
546
547     if (!fd->inode) return;
548     if (!fd->fs_locks) return;
549     if (start == end || start > max_unix_offset) return;
550     if (!end || end > max_unix_offset) end = max_unix_offset + 1;
551
552     /* count the number of locks overlapping the specified area */
553
554     LIST_FOR_EACH( ptr, &fd->inode->locks )
555     {
556         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
557         if (lock->start == lock->end) continue;
558         if (lock_overlaps( lock, start, end )) count++;
559     }
560
561     if (!count)  /* no locks at all, we can unlock everything */
562     {
563         set_unix_lock( fd, start, end, F_UNLCK );
564         return;
565     }
566
567     /* allocate space for the list of holes */
568     /* max. number of holes is number of locks + 1 */
569
570     if (!(buffer = malloc( sizeof(*buffer) * (count+1) ))) return;
571     first = buffer;
572     first->next  = NULL;
573     first->prev  = NULL;
574     first->start = start;
575     first->end   = end;
576     next = first + 1;
577
578     /* build a sorted list of unlocked holes in the specified area */
579
580     LIST_FOR_EACH( ptr, &fd->inode->locks )
581     {
582         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
583         if (lock->start == lock->end) continue;
584         if (!lock_overlaps( lock, start, end )) continue;
585
586         /* go through all the holes touched by this lock */
587         for (cur = first; cur; cur = cur->next)
588         {
589             if (cur->end <= lock->start) continue; /* hole is before start of lock */
590             if (lock->end && cur->start >= lock->end) break;  /* hole is after end of lock */
591
592             /* now we know that lock is overlapping hole */
593
594             if (cur->start >= lock->start)  /* lock starts before hole, shrink from start */
595             {
596                 cur->start = lock->end;
597                 if (cur->start && cur->start < cur->end) break;  /* done with this lock */
598                 /* now hole is empty, remove it */
599                 if (cur->next) cur->next->prev = cur->prev;
600                 if (cur->prev) cur->prev->next = cur->next;
601                 else if (!(first = cur->next)) goto done;  /* no more holes at all */
602             }
603             else if (!lock->end || cur->end <= lock->end)  /* lock larger than hole, shrink from end */
604             {
605                 cur->end = lock->start;
606                 assert( cur->start < cur->end );
607             }
608             else  /* lock is in the middle of hole, split hole in two */
609             {
610                 next->prev = cur;
611                 next->next = cur->next;
612                 cur->next = next;
613                 next->start = lock->end;
614                 next->end = cur->end;
615                 cur->end = lock->start;
616                 assert( next->start < next->end );
617                 assert( cur->end < next->start );
618                 next++;
619                 break;  /* done with this lock */
620             }
621         }
622     }
623
624     /* clear Unix locks for all the holes */
625
626     for (cur = first; cur; cur = cur->next)
627         set_unix_lock( fd, cur->start, cur->end, F_UNLCK );
628
629  done:
630     free( buffer );
631 }
632
633 /* create a new lock on a fd */
634 static struct file_lock *add_lock( struct fd *fd, int shared, file_pos_t start, file_pos_t end )
635 {
636     struct file_lock *lock;
637
638     if (!fd->inode)  /* not a regular file */
639     {
640         set_error( STATUS_INVALID_HANDLE );
641         return NULL;
642     }
643
644     if (!(lock = alloc_object( &file_lock_ops ))) return NULL;
645     lock->shared  = shared;
646     lock->start   = start;
647     lock->end     = end;
648     lock->fd      = fd;
649     lock->process = current->process;
650
651     /* now try to set a Unix lock */
652     if (!set_unix_lock( lock->fd, lock->start, lock->end, lock->shared ? F_RDLCK : F_WRLCK ))
653     {
654         release_object( lock );
655         return NULL;
656     }
657     list_add_head( &fd->locks, &lock->fd_entry );
658     list_add_head( &fd->inode->locks, &lock->inode_entry );
659     list_add_head( &lock->process->locks, &lock->proc_entry );
660     return lock;
661 }
662
663 /* remove an existing lock */
664 static void remove_lock( struct file_lock *lock, int remove_unix )
665 {
666     struct inode *inode = lock->fd->inode;
667
668     list_remove( &lock->fd_entry );
669     list_remove( &lock->inode_entry );
670     list_remove( &lock->proc_entry );
671     if (remove_unix) remove_unix_locks( lock->fd, lock->start, lock->end );
672     if (list_empty( &inode->locks )) inode_close_pending( inode );
673     lock->process = NULL;
674     wake_up( &lock->obj, 0 );
675     release_object( lock );
676 }
677
678 /* remove all locks owned by a given process */
679 void remove_process_locks( struct process *process )
680 {
681     struct list *ptr;
682
683     while ((ptr = list_head( &process->locks )))
684     {
685         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, proc_entry );
686         remove_lock( lock, 1 );  /* this removes it from the list */
687     }
688 }
689
690 /* remove all locks on a given fd */
691 static void remove_fd_locks( struct fd *fd )
692 {
693     file_pos_t start = FILE_POS_T_MAX, end = 0;
694     struct list *ptr;
695
696     while ((ptr = list_head( &fd->locks )))
697     {
698         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
699         if (lock->start < start) start = lock->start;
700         if (!lock->end || lock->end > end) end = lock->end - 1;
701         remove_lock( lock, 0 );
702     }
703     if (start < end) remove_unix_locks( fd, start, end + 1 );
704 }
705
706 /* add a lock on an fd */
707 /* returns handle to wait on */
708 obj_handle_t lock_fd( struct fd *fd, file_pos_t start, file_pos_t count, int shared, int wait )
709 {
710     struct list *ptr;
711     file_pos_t end = start + count;
712
713     /* don't allow wrapping locks */
714     if (end && end < start)
715     {
716         set_error( STATUS_INVALID_PARAMETER );
717         return 0;
718     }
719
720     /* check if another lock on that file overlaps the area */
721     LIST_FOR_EACH( ptr, &fd->inode->locks )
722     {
723         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, inode_entry );
724         if (!lock_overlaps( lock, start, end )) continue;
725         if (lock->shared && shared) continue;
726         /* found one */
727         if (!wait)
728         {
729             set_error( STATUS_FILE_LOCK_CONFLICT );
730             return 0;
731         }
732         set_error( STATUS_PENDING );
733         return alloc_handle( current->process, lock, SYNCHRONIZE, 0 );
734     }
735
736     /* not found, add it */
737     if (add_lock( fd, shared, start, end )) return 0;
738     if (get_error() == STATUS_FILE_LOCK_CONFLICT)
739     {
740         /* Unix lock conflict -> tell client to wait and retry */
741         if (wait) set_error( STATUS_PENDING );
742     }
743     return 0;
744 }
745
746 /* remove a lock on an fd */
747 void unlock_fd( struct fd *fd, file_pos_t start, file_pos_t count )
748 {
749     struct list *ptr;
750     file_pos_t end = start + count;
751
752     /* find an existing lock with the exact same parameters */
753     LIST_FOR_EACH( ptr, &fd->locks )
754     {
755         struct file_lock *lock = LIST_ENTRY( ptr, struct file_lock, fd_entry );
756         if ((lock->start == start) && (lock->end == end))
757         {
758             remove_lock( lock, 1 );
759             return;
760         }
761     }
762     set_error( STATUS_FILE_LOCK_CONFLICT );
763 }
764
765
766 /****************************************************************/
767 /* file descriptor functions */
768
769 static void fd_dump( struct object *obj, int verbose )
770 {
771     struct fd *fd = (struct fd *)obj;
772     fprintf( stderr, "Fd unix_fd=%d user=%p\n", fd->unix_fd, fd->user );
773 }
774
775 static void fd_destroy( struct object *obj )
776 {
777     struct fd *fd = (struct fd *)obj;
778
779     remove_fd_locks( fd );
780     list_remove( &fd->inode_entry );
781     if (fd->poll_index != -1) remove_poll_user( fd, fd->poll_index );
782     if (fd->inode)
783     {
784         inode_add_closed_fd( fd->inode, fd->closed );
785         release_object( fd->inode );
786     }
787     else  /* no inode, close it right away */
788     {
789         if (fd->unix_fd != -1) close( fd->unix_fd );
790     }
791 }
792
793 /* set the events that select waits for on this fd */
794 void set_fd_events( struct fd *fd, int events )
795 {
796     int user = fd->poll_index;
797     assert( poll_users[user] == fd );
798     if (events == -1)  /* stop waiting on this fd completely */
799     {
800         pollfd[user].fd = -1;
801         pollfd[user].events = POLLERR;
802         pollfd[user].revents = 0;
803     }
804     else if (pollfd[user].fd != -1 || !pollfd[user].events)
805     {
806         pollfd[user].fd = fd->unix_fd;
807         pollfd[user].events = events;
808     }
809 }
810
811 /* allocate an fd object, without setting the unix fd yet */
812 struct fd *alloc_fd( const struct fd_ops *fd_user_ops, struct object *user )
813 {
814     struct fd *fd = alloc_object( &fd_ops );
815
816     if (!fd) return NULL;
817
818     fd->fd_ops     = fd_user_ops;
819     fd->user       = user;
820     fd->inode      = NULL;
821     fd->closed     = NULL;
822     fd->access     = 0;
823     fd->sharing    = 0;
824     fd->unix_fd    = -1;
825     fd->fs_locks   = 1;
826     fd->poll_index = -1;
827     list_init( &fd->inode_entry );
828     list_init( &fd->locks );
829
830     if ((fd->poll_index = add_poll_user( fd )) == -1)
831     {
832         release_object( fd );
833         return NULL;
834     }
835     return fd;
836 }
837
838 /* check if the desired access is possible without violating */
839 /* the sharing mode of other opens of the same file */
840 static int check_sharing( struct fd *fd, unsigned int access, unsigned int sharing )
841 {
842     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
843     unsigned int existing_access = 0;
844     struct list *ptr;
845
846     /* if access mode is 0, sharing mode is ignored */
847     if (!access) sharing = FILE_SHARE_READ|FILE_SHARE_WRITE;
848     fd->access = access;
849     fd->sharing = sharing;
850
851     LIST_FOR_EACH( ptr, &fd->inode->open )
852     {
853         struct fd *fd_ptr = LIST_ENTRY( ptr, struct fd, inode_entry );
854         if (fd_ptr != fd)
855         {
856             existing_sharing &= fd_ptr->sharing;
857             existing_access  |= fd_ptr->access;
858         }
859     }
860
861     if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) return 0;
862     if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) return 0;
863     if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) return 0;
864     if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) return 0;
865     return 1;
866 }
867
868 /* open() wrapper using a struct fd */
869 /* the fd must have been created with alloc_fd */
870 /* on error the fd object is released */
871 struct fd *open_fd( struct fd *fd, const char *name, int flags, mode_t *mode,
872                     unsigned int access, unsigned int sharing )
873 {
874     struct stat st;
875     struct closed_fd *closed_fd;
876
877     assert( fd->unix_fd == -1 );
878
879     if (!(closed_fd = mem_alloc( sizeof(*closed_fd) )))
880     {
881         release_object( fd );
882         return NULL;
883     }
884     if ((fd->unix_fd = open( name, flags, *mode )) == -1)
885     {
886         file_set_error();
887         release_object( fd );
888         free( closed_fd );
889         return NULL;
890     }
891     closed_fd->fd = fd->unix_fd;
892     fstat( fd->unix_fd, &st );
893     *mode = st.st_mode;
894
895     if (S_ISREG(st.st_mode))  /* only bother with an inode for normal files */
896     {
897         struct inode *inode = get_inode( st.st_dev, st.st_ino );
898
899         if (!inode)
900         {
901             /* we can close the fd because there are no others open on the same file,
902              * otherwise we wouldn't have failed to allocate a new inode
903              */
904             release_object( fd );
905             free( closed_fd );
906             return NULL;
907         }
908         fd->inode = inode;
909         fd->closed = closed_fd;
910         list_add_head( &inode->open, &fd->inode_entry );
911         if (!check_sharing( fd, access, sharing ))
912         {
913             release_object( fd );
914             set_error( STATUS_SHARING_VIOLATION );
915             return NULL;
916         }
917     }
918     else
919     {
920         free( closed_fd );
921     }
922     return fd;
923 }
924
925 /* create an fd for an anonymous file */
926 /* if the function fails the unix fd is closed */
927 struct fd *create_anonymous_fd( const struct fd_ops *fd_user_ops, int unix_fd, struct object *user )
928 {
929     struct fd *fd = alloc_fd( fd_user_ops, user );
930
931     if (fd)
932     {
933         fd->unix_fd = unix_fd;
934         return fd;
935     }
936     close( unix_fd );
937     return NULL;
938 }
939
940 /* retrieve the object that is using an fd */
941 void *get_fd_user( struct fd *fd )
942 {
943     return fd->user;
944 }
945
946 /* retrieve the unix fd for an object */
947 int get_unix_fd( struct fd *fd )
948 {
949     return fd->unix_fd;
950 }
951
952 /* check if two file descriptors point to the same file */
953 int is_same_file_fd( struct fd *fd1, struct fd *fd2 )
954 {
955     return fd1->inode == fd2->inode;
956 }
957
958 /* callback for event happening in the main poll() loop */
959 void fd_poll_event( struct fd *fd, int event )
960 {
961     return fd->fd_ops->poll_event( fd, event );
962 }
963
964 /* check if events are pending and if yes return which one(s) */
965 int check_fd_events( struct fd *fd, int events )
966 {
967     struct pollfd pfd;
968
969     pfd.fd     = fd->unix_fd;
970     pfd.events = events;
971     if (poll( &pfd, 1, 0 ) <= 0) return 0;
972     return pfd.revents;
973 }
974
975 /* default add_queue() routine for objects that poll() on an fd */
976 int default_fd_add_queue( struct object *obj, struct wait_queue_entry *entry )
977 {
978     struct fd *fd = get_obj_fd( obj );
979
980     if (!fd) return 0;
981     if (!obj->head)  /* first on the queue */
982         set_fd_events( fd, fd->fd_ops->get_poll_events( fd ) );
983     add_queue( obj, entry );
984     release_object( fd );
985     return 1;
986 }
987
988 /* default remove_queue() routine for objects that poll() on an fd */
989 void default_fd_remove_queue( struct object *obj, struct wait_queue_entry *entry )
990 {
991     struct fd *fd = get_obj_fd( obj );
992
993     grab_object( obj );
994     remove_queue( obj, entry );
995     if (!obj->head)  /* last on the queue is gone */
996         set_fd_events( fd, 0 );
997     release_object( obj );
998     release_object( fd );
999 }
1000
1001 /* default signaled() routine for objects that poll() on an fd */
1002 int default_fd_signaled( struct object *obj, struct thread *thread )
1003 {
1004     struct fd *fd = get_obj_fd( obj );
1005     int events = fd->fd_ops->get_poll_events( fd );
1006     int ret = check_fd_events( fd, events ) != 0;
1007
1008     if (ret)
1009         set_fd_events( fd, 0 ); /* stop waiting on select() if we are signaled */
1010     else if (obj->head)
1011         set_fd_events( fd, events ); /* restart waiting on poll() if we are no longer signaled */
1012
1013     release_object( fd );
1014     return ret;
1015 }
1016
1017 /* default handler for poll() events */
1018 void default_poll_event( struct fd *fd, int event )
1019 {
1020     /* an error occurred, stop polling this fd to avoid busy-looping */
1021     if (event & (POLLERR | POLLHUP)) set_fd_events( fd, -1 );
1022     wake_up( fd->user, 0 );
1023 }
1024
1025 /* default flush() routine */
1026 int no_flush( struct fd *fd, struct event **event )
1027 {
1028     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1029     return 0;
1030 }
1031
1032 /* default get_file_info() routine */
1033 int no_get_file_info( struct fd *fd, struct get_file_info_reply *info, int *flags )
1034 {
1035     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1036     *flags = 0;
1037     return FD_TYPE_INVALID;
1038 }
1039
1040 /* default queue_async() routine */
1041 void no_queue_async( struct fd *fd, void* ptr, unsigned int status, int type, int count )
1042 {
1043     set_error( STATUS_OBJECT_TYPE_MISMATCH );
1044 }
1045
1046 /* same as get_handle_obj but retrieve the struct fd associated to the object */
1047 static struct fd *get_handle_fd_obj( struct process *process, obj_handle_t handle,
1048                                      unsigned int access )
1049 {
1050     struct fd *fd = NULL;
1051     struct object *obj;
1052
1053     if ((obj = get_handle_obj( process, handle, access, NULL )))
1054     {
1055         fd = get_obj_fd( obj );
1056         release_object( obj );
1057     }
1058     return fd;
1059 }
1060
1061 /* flush a file buffers */
1062 DECL_HANDLER(flush_file)
1063 {
1064     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1065     struct event * event = NULL;
1066
1067     if (fd)
1068     {
1069         fd->fd_ops->flush( fd, &event );
1070         if( event )
1071         {
1072             reply->event = alloc_handle( current->process, event, SYNCHRONIZE, 0 );
1073         }
1074         release_object( fd );
1075     }
1076 }
1077
1078 /* get a Unix fd to access a file */
1079 DECL_HANDLER(get_handle_fd)
1080 {
1081     struct fd *fd;
1082
1083     reply->fd = -1;
1084     reply->type = FD_TYPE_INVALID;
1085
1086     if ((fd = get_handle_fd_obj( current->process, req->handle, req->access )))
1087     {
1088         int unix_fd = get_handle_unix_fd( current->process, req->handle, req->access );
1089         if (unix_fd != -1) reply->fd = unix_fd;
1090         else if (!get_error())
1091         {
1092             assert( fd->unix_fd != -1 );
1093             send_client_fd( current->process, fd->unix_fd, req->handle );
1094         }
1095         reply->type = fd->fd_ops->get_file_info( fd, NULL, &reply->flags );
1096         release_object( fd );
1097     }
1098 }
1099
1100 /* get a file information */
1101 DECL_HANDLER(get_file_info)
1102 {
1103     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1104
1105     if (fd)
1106     {
1107         int flags;
1108         fd->fd_ops->get_file_info( fd, reply, &flags );
1109         release_object( fd );
1110     }
1111 }
1112
1113 /* create / reschedule an async I/O */
1114 DECL_HANDLER(register_async)
1115 {
1116     struct fd *fd = get_handle_fd_obj( current->process, req->handle, 0 );
1117
1118 /*
1119  * The queue_async method must do the following:
1120  *
1121  * 1. Get the async_queue for the request of given type.
1122  * 2. Call find_async() to look for the specific client request in the queue (=> NULL if not found).
1123  * 3. If status is STATUS_PENDING:
1124  *      a) If no async request found in step 2 (new request): call create_async() to initialize one.
1125  *      b) Set request's status to STATUS_PENDING.
1126  *      c) If the "queue" field of the async request is NULL: call async_insert() to put it into the queue.
1127  *    Otherwise:
1128  *      If the async request was found in step 2, destroy it by calling destroy_async().
1129  * 4. Carry out any operations necessary to adjust the object's poll events
1130  *    Usually: set_elect_events (obj, obj->ops->get_poll_events()).
1131  *
1132  * See also the implementations in file.c, serial.c, and sock.c.
1133 */
1134
1135     if (fd)
1136     {
1137         fd->fd_ops->queue_async( fd, req->overlapped, req->status, req->type, req->count );
1138         release_object( fd );
1139     }
1140 }