Moved all references to file descriptors out of the generic object
[wine] / server / file.c
1 /*
2  * Server-side file management
3  *
4  * Copyright (C) 1998 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 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <fcntl.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <errno.h>
30 #ifdef HAVE_SYS_ERRNO_H
31 #include <sys/errno.h>
32 #endif
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #include <time.h>
37 #include <unistd.h>
38 #ifdef HAVE_UTIME_H
39 #include <utime.h>
40 #endif
41
42 #include "winerror.h"
43 #include "winbase.h"
44
45 #include "file.h"
46 #include "handle.h"
47 #include "thread.h"
48 #include "request.h"
49 #include "async.h"
50
51 struct file
52 {
53     struct object       obj;        /* object header */
54     struct fd          *fd;         /* file descriptor for this file */
55     struct file        *next;       /* next file in hashing list */
56     char               *name;       /* file name */
57     unsigned int        access;     /* file access (GENERIC_READ/WRITE) */
58     unsigned int        flags;      /* flags (FILE_FLAG_*) */
59     unsigned int        sharing;    /* file sharing mode */
60     int                 drive_type; /* type of drive the file is on */
61     struct async_queue  read_q;
62     struct async_queue  write_q;
63 };
64
65 #define NAME_HASH_SIZE 37
66
67 static struct file *file_hash[NAME_HASH_SIZE];
68
69 static void file_dump( struct object *obj, int verbose );
70 static struct fd *file_get_fd( struct object *obj );
71 static void file_destroy( struct object *obj );
72
73 static int file_get_poll_events( struct fd *fd );
74 static void file_poll_event( struct fd *fd, int event );
75 static int file_flush( struct fd *fd );
76 static int file_get_info( struct fd *fd, struct get_file_info_reply *reply, int *flags );
77 static void file_queue_async( struct fd *fd, void *ptr, unsigned int status, int type, int count );
78
79 static const struct object_ops file_ops =
80 {
81     sizeof(struct file),          /* size */
82     file_dump,                    /* dump */
83     default_fd_add_queue,         /* add_queue */
84     default_fd_remove_queue,      /* remove_queue */
85     default_fd_signaled,          /* signaled */
86     no_satisfied,                 /* satisfied */
87     file_get_fd,                  /* get_fd */
88     file_destroy                  /* destroy */
89 };
90
91 static const struct fd_ops file_fd_ops =
92 {
93     file_get_poll_events,         /* get_poll_events */
94     file_poll_event,              /* poll_event */
95     file_flush,                   /* flush */
96     file_get_info,                /* get_file_info */
97     file_queue_async              /* queue_async */
98 };
99
100 static int get_name_hash( const char *name )
101 {
102     int hash = 0;
103     while (*name) hash ^= (unsigned char)*name++;
104     return hash % NAME_HASH_SIZE;
105 }
106
107 /* check if the desired access is possible without violating */
108 /* the sharing mode of other opens of the same file */
109 static int check_sharing( const char *name, int hash, unsigned int access,
110                           unsigned int sharing )
111 {
112     struct file *file;
113     unsigned int existing_sharing = FILE_SHARE_READ | FILE_SHARE_WRITE;
114     unsigned int existing_access = 0;
115
116     for (file = file_hash[hash]; file; file = file->next)
117     {
118         if (strcmp( file->name, name )) continue;
119         existing_sharing &= file->sharing;
120         existing_access |= file->access;
121     }
122     if ((access & GENERIC_READ) && !(existing_sharing & FILE_SHARE_READ)) goto error;
123     if ((access & GENERIC_WRITE) && !(existing_sharing & FILE_SHARE_WRITE)) goto error;
124     if ((existing_access & GENERIC_READ) && !(sharing & FILE_SHARE_READ)) goto error;
125     if ((existing_access & GENERIC_WRITE) && !(sharing & FILE_SHARE_WRITE)) goto error;
126     return 1;
127  error:
128     set_error( STATUS_SHARING_VIOLATION );
129     return 0;
130 }
131
132 /* create a file from a file descriptor */
133 /* if the function fails the fd is closed */
134 static struct file *create_file_for_fd( int fd, unsigned int access, unsigned int sharing,
135                                         unsigned int attrs, int drive_type )
136 {
137     struct file *file;
138
139     if ((file = alloc_object( &file_ops )))
140     {
141         file->name       = NULL;
142         file->next       = NULL;
143         file->access     = access;
144         file->flags      = attrs;
145         file->sharing    = sharing;
146         file->drive_type = drive_type;
147         if (file->flags & FILE_FLAG_OVERLAPPED)
148         {
149             init_async_queue (&file->read_q);
150             init_async_queue (&file->write_q);
151         }
152         if (!(file->fd = alloc_fd( &file_fd_ops, fd, &file->obj )))
153         {
154             release_object( file );
155             return NULL;
156         }
157     }
158     return file;
159 }
160
161
162 static struct file *create_file( const char *nameptr, size_t len, unsigned int access,
163                                  unsigned int sharing, int create, unsigned int attrs,
164                                  int drive_type )
165 {
166     struct file *file;
167     int hash, flags;
168     struct stat st;
169     char *name;
170     int fd = -1;
171     mode_t mode;
172
173     if (!(name = mem_alloc( len + 1 ))) return NULL;
174     memcpy( name, nameptr, len );
175     name[len] = 0;
176
177     /* check sharing mode */
178     hash = get_name_hash( name );
179     if (!check_sharing( name, hash, access, sharing )) goto error;
180
181     switch(create)
182     {
183     case CREATE_NEW:        flags = O_CREAT | O_EXCL; break;
184     case CREATE_ALWAYS:     flags = O_CREAT | O_TRUNC; break;
185     case OPEN_ALWAYS:       flags = O_CREAT; break;
186     case TRUNCATE_EXISTING: flags = O_TRUNC; break;
187     case OPEN_EXISTING:     flags = 0; break;
188     default:                set_error( STATUS_INVALID_PARAMETER ); goto error;
189     }
190     switch(access & (GENERIC_READ | GENERIC_WRITE))
191     {
192     case 0: break;
193     case GENERIC_READ:  flags |= O_RDONLY; break;
194     case GENERIC_WRITE: flags |= O_WRONLY; break;
195     case GENERIC_READ|GENERIC_WRITE: flags |= O_RDWR; break;
196     }
197     mode = (attrs & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
198
199     if (len >= 4 &&
200         (!strcasecmp( name + len - 4, ".exe" ) || !strcasecmp( name + len - 4, ".com" )))
201         mode |= 0111;
202
203     /* FIXME: should set error to STATUS_OBJECT_NAME_COLLISION if file existed before */
204     if ((fd = open( name, flags | O_NONBLOCK | O_LARGEFILE, mode )) == -1 )
205         goto file_error;
206     /* refuse to open a directory */
207     if (fstat( fd, &st ) == -1) goto file_error;
208     if (S_ISDIR(st.st_mode))
209     {
210         set_error( STATUS_ACCESS_DENIED );
211         goto error;
212     }
213
214     if (!(file = create_file_for_fd( fd, access, sharing, attrs, drive_type )))
215     {
216         free( name );
217         return NULL;
218     }
219     file->name = name;
220     file->next = file_hash[hash];
221     file_hash[hash] = file;
222     return file;
223
224  file_error:
225     file_set_error();
226  error:
227     if (fd != -1) close( fd );
228     free( name );
229     return NULL;
230 }
231
232 /* check if two file objects point to the same file */
233 int is_same_file( struct file *file1, struct file *file2 )
234 {
235     return !strcmp( file1->name, file2->name );
236 }
237
238 /* get the type of drive the file is on */
239 int get_file_drive_type( struct file *file )
240 {
241     return file->drive_type;
242 }
243
244 /* Create an anonymous Unix file */
245 int create_anonymous_file(void)
246 {
247     char tmpfn[21];
248     int fd;
249
250     sprintf(tmpfn,"/tmp/anonmap.XXXXXX");
251     fd = mkstemp(tmpfn);
252     if (fd == -1)
253     {
254         file_set_error();
255         return -1;
256     }
257     unlink( tmpfn );
258     return fd;
259 }
260
261 /* Create a temp file for anonymous mappings */
262 struct file *create_temp_file( int access )
263 {
264     int fd;
265
266     if ((fd = create_anonymous_file()) == -1) return NULL;
267     return create_file_for_fd( fd, access, 0, 0, DRIVE_FIXED );
268 }
269
270 static void file_dump( struct object *obj, int verbose )
271 {
272     struct file *file = (struct file *)obj;
273     assert( obj->ops == &file_ops );
274     fprintf( stderr, "File fd=%p flags=%08x name='%s'\n", file->fd, file->flags, file->name );
275 }
276
277 static int file_get_poll_events( struct fd *fd )
278 {
279     struct file *file = get_fd_user( fd );
280     int events = 0;
281     assert( file->obj.ops == &file_ops );
282     if (file->access & GENERIC_READ) events |= POLLIN;
283     if (file->access & GENERIC_WRITE) events |= POLLOUT;
284     return events;
285 }
286
287 static void file_poll_event( struct fd *fd, int event )
288 {
289     struct file *file = get_fd_user( fd );
290     assert( file->obj.ops == &file_ops );
291     if ( file->flags & FILE_FLAG_OVERLAPPED )
292     {
293         if( IS_READY(file->read_q) && (POLLIN & event) )
294         {
295             async_notify(file->read_q.head, STATUS_ALERTED);
296             return;
297         }
298         if( IS_READY(file->write_q) && (POLLOUT & event) )
299         {
300             async_notify(file->write_q.head, STATUS_ALERTED);
301             return;
302         }
303     }
304     default_poll_event( fd, event );
305 }
306
307
308 static int file_flush( struct fd *fd )
309 {
310     int ret = (fsync( get_unix_fd(fd) ) != -1);
311     if (!ret) file_set_error();
312     return ret;
313 }
314
315 static int file_get_info( struct fd *fd, struct get_file_info_reply *reply, int *flags )
316 {
317     struct stat st;
318     struct file *file = get_fd_user( fd );
319     int unix_fd = get_unix_fd( fd );
320
321     if (reply)
322     {
323         if (fstat( unix_fd, &st ) == -1)
324         {
325             file_set_error();
326             return FD_TYPE_INVALID;
327         }
328         if (S_ISCHR(st.st_mode) || S_ISFIFO(st.st_mode) ||
329             S_ISSOCK(st.st_mode) || isatty(unix_fd)) reply->type = FILE_TYPE_CHAR;
330         else reply->type = FILE_TYPE_DISK;
331         if (S_ISDIR(st.st_mode)) reply->attr = FILE_ATTRIBUTE_DIRECTORY;
332         else reply->attr = FILE_ATTRIBUTE_ARCHIVE;
333         if (!(st.st_mode & S_IWUSR)) reply->attr |= FILE_ATTRIBUTE_READONLY;
334         reply->access_time = st.st_atime;
335         reply->write_time  = st.st_mtime;
336         if (S_ISDIR(st.st_mode))
337         {
338             reply->size_high = 0;
339             reply->size_low  = 0;
340         }
341         else
342         {
343             reply->size_high = st.st_size >> 32;
344             reply->size_low  = st.st_size & 0xffffffff;
345         }
346         reply->links       = st.st_nlink;
347         reply->index_high  = st.st_dev;
348         reply->index_low   = st.st_ino;
349         reply->serial      = 0; /* FIXME */
350     }
351     *flags = 0;
352     if (file->flags & FILE_FLAG_OVERLAPPED) *flags |= FD_FLAG_OVERLAPPED;
353     return FD_TYPE_DEFAULT;
354 }
355
356 static void file_queue_async(struct fd *fd, void *ptr, unsigned int status, int type, int count)
357 {
358     struct file *file = get_fd_user( fd );
359     struct async *async;
360     struct async_queue *q;
361
362     assert( file->obj.ops == &file_ops );
363
364     if ( !(file->flags & FILE_FLAG_OVERLAPPED) )
365     {
366         set_error ( STATUS_INVALID_HANDLE );
367         return;
368     }
369
370     switch(type)
371     {
372     case ASYNC_TYPE_READ:
373         q = &file->read_q;
374         break;
375     case ASYNC_TYPE_WRITE:
376         q = &file->write_q;
377         break;
378     default:
379         set_error( STATUS_INVALID_PARAMETER );
380         return;
381     }
382
383     async = find_async ( q, current, ptr );
384
385     if ( status == STATUS_PENDING )
386     {
387         int events;
388
389         if ( !async )
390             async = create_async ( &file->obj, current, ptr );
391         if ( !async )
392             return;
393
394         async->status = STATUS_PENDING;
395         if ( !async->q )
396             async_insert( q, async );
397
398         /* Check if the new pending request can be served immediately */
399         events = check_fd_events( fd, file_get_poll_events( fd ) );
400         if (events) file_poll_event ( fd, events );
401     }
402     else if ( async ) destroy_async ( async );
403     else set_error ( STATUS_INVALID_PARAMETER );
404
405     set_fd_events( fd, file_get_poll_events( fd ));
406 }
407
408 static struct fd *file_get_fd( struct object *obj )
409 {
410     struct file *file = (struct file *)obj;
411     assert( obj->ops == &file_ops );
412     return (struct fd *)grab_object( file->fd );
413 }
414
415 static void file_destroy( struct object *obj )
416 {
417     struct file *file = (struct file *)obj;
418     assert( obj->ops == &file_ops );
419
420     if (file->name)
421     {
422         /* remove it from the hashing list */
423         struct file **pptr = &file_hash[get_name_hash( file->name )];
424         while (*pptr && *pptr != file) pptr = &(*pptr)->next;
425         assert( *pptr );
426         *pptr = (*pptr)->next;
427         if (file->flags & FILE_FLAG_DELETE_ON_CLOSE) unlink( file->name );
428         free( file->name );
429     }
430     if (file->flags & FILE_FLAG_OVERLAPPED)
431     {
432         destroy_async_queue (&file->read_q);
433         destroy_async_queue (&file->write_q);
434     }
435     if (file->fd) release_object( file->fd );
436 }
437
438 /* set the last error depending on errno */
439 void file_set_error(void)
440 {
441     switch (errno)
442     {
443     case EAGAIN:    set_error( STATUS_SHARING_VIOLATION ); break;
444     case EBADF:     set_error( STATUS_INVALID_HANDLE ); break;
445     case ENOSPC:    set_error( STATUS_DISK_FULL ); break;
446     case EACCES:
447     case ESRCH:
448     case EPERM:     set_error( STATUS_ACCESS_DENIED ); break;
449     case EROFS:     set_error( STATUS_MEDIA_WRITE_PROTECTED ); break;
450     case EBUSY:     set_error( STATUS_FILE_LOCK_CONFLICT ); break;
451     case ENOENT:    set_error( STATUS_NO_SUCH_FILE ); break;
452     case EISDIR:    set_error( 0xc0010000 | ERROR_CANNOT_MAKE /* FIXME */ ); break;
453     case ENFILE:
454     case EMFILE:    set_error( STATUS_NO_MORE_FILES ); break;
455     case EEXIST:    set_error( STATUS_OBJECT_NAME_COLLISION ); break;
456     case EINVAL:    set_error( STATUS_INVALID_PARAMETER ); break;
457     case ESPIPE:    set_error( 0xc0010000 | ERROR_SEEK /* FIXME */ ); break;
458     case ENOTEMPTY: set_error( STATUS_DIRECTORY_NOT_EMPTY ); break;
459     case EIO:       set_error( STATUS_ACCESS_VIOLATION ); break;
460     default:        perror("file_set_error"); set_error( ERROR_UNKNOWN /* FIXME */ ); break;
461     }
462 }
463
464 struct file *get_file_obj( struct process *process, obj_handle_t handle, unsigned int access )
465 {
466     return (struct file *)get_handle_obj( process, handle, access, &file_ops );
467 }
468
469 int get_file_unix_fd( struct file *file )
470 {
471     return get_unix_fd( file->fd );
472 }
473
474 static int set_file_pointer( obj_handle_t handle, unsigned int *low, int *high, int whence )
475 {
476     struct file *file;
477     off_t result,xto;
478
479     xto = *low+((off_t)*high<<32);
480     if (!(file = get_file_obj( current->process, handle, 0 )))
481         return 0;
482     if ((result = lseek( get_file_unix_fd(file), xto, whence))==-1)
483     {
484         /* Check for seek before start of file */
485
486         /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
487         if (((errno == EINVAL) || (errno == EPERM))
488             && (whence != SEEK_SET) && (*high < 0))
489             set_error( 0xc0010000 | ERROR_NEGATIVE_SEEK /* FIXME */ );
490         else
491             file_set_error();
492         release_object( file );
493         return 0;
494     }
495     *low  = result & 0xffffffff;
496     *high = result >> 32;
497     release_object( file );
498     return 1;
499 }
500
501 /* extend a file beyond the current end of file */
502 static int extend_file( struct file *file, off_t size )
503 {
504     static const char zero;
505     int unix_fd = get_file_unix_fd( file );
506
507     /* extend the file one byte beyond the requested size and then truncate it */
508     /* this should work around ftruncate implementations that can't extend files */
509     if ((lseek( unix_fd, size, SEEK_SET ) != -1) &&
510         (write( unix_fd, &zero, 1 ) != -1))
511     {
512         ftruncate( unix_fd, size );
513         return 1;
514     }
515     file_set_error();
516     return 0;
517 }
518
519 /* truncate file at current position */
520 static int truncate_file( struct file *file )
521 {
522     int ret = 0;
523     int unix_fd = get_file_unix_fd( file );
524     off_t pos = lseek( unix_fd, 0, SEEK_CUR );
525     off_t eof = lseek( unix_fd, 0, SEEK_END );
526
527     if (eof < pos) ret = extend_file( file, pos );
528     else
529     {
530         if (ftruncate( unix_fd, pos ) != -1) ret = 1;
531         else file_set_error();
532     }
533     lseek( unix_fd, pos, SEEK_SET );  /* restore file pos */
534     return ret;
535 }
536
537 /* try to grow the file to the specified size */
538 int grow_file( struct file *file, int size_high, int size_low )
539 {
540     int ret = 0;
541     struct stat st;
542     int unix_fd = get_file_unix_fd( file );
543     off_t old_pos, size = size_low + (((off_t)size_high)<<32);
544
545     if (fstat( unix_fd, &st ) == -1)
546     {
547         file_set_error();
548         return 0;
549     }
550     if (st.st_size >= size) return 1;  /* already large enough */
551     old_pos = lseek( unix_fd, 0, SEEK_CUR );  /* save old pos */
552     ret = extend_file( file, size );
553     lseek( unix_fd, old_pos, SEEK_SET );  /* restore file pos */
554     return ret;
555 }
556
557 static int set_file_time( obj_handle_t handle, time_t access_time, time_t write_time )
558 {
559     struct file *file;
560     struct utimbuf utimbuf;
561
562     if (!(file = get_file_obj( current->process, handle, GENERIC_WRITE )))
563         return 0;
564     if (!file->name)
565     {
566         set_error( STATUS_INVALID_HANDLE );
567         release_object( file );
568         return 0;
569     }
570     if (!access_time || !write_time)
571     {
572         struct stat st;
573         if (stat( file->name, &st ) == -1) goto error;
574         if (!access_time) access_time = st.st_atime;
575         if (!write_time) write_time = st.st_mtime;
576     }
577     utimbuf.actime  = access_time;
578     utimbuf.modtime = write_time;
579     if (utime( file->name, &utimbuf ) == -1) goto error;
580     release_object( file );
581     return 1;
582  error:
583     file_set_error();
584     release_object( file );
585     return 0;
586 }
587
588 static int file_lock( struct file *file, int offset_high, int offset_low,
589                       int count_high, int count_low )
590 {
591     /* FIXME: implement this */
592     return 1;
593 }
594
595 static int file_unlock( struct file *file, int offset_high, int offset_low,
596                         int count_high, int count_low )
597 {
598     /* FIXME: implement this */
599     return 1;
600 }
601
602 /* create a file */
603 DECL_HANDLER(create_file)
604 {
605     struct file *file;
606
607     reply->handle = 0;
608     if ((file = create_file( get_req_data(), get_req_data_size(), req->access,
609                              req->sharing, req->create, req->attrs, req->drive_type )))
610     {
611         reply->handle = alloc_handle( current->process, file, req->access, req->inherit );
612         release_object( file );
613     }
614 }
615
616 /* allocate a file handle for a Unix fd */
617 DECL_HANDLER(alloc_file_handle)
618 {
619     struct file *file;
620     int fd;
621
622     reply->handle = 0;
623     if ((fd = thread_get_inflight_fd( current, req->fd )) == -1)
624     {
625         set_error( STATUS_INVALID_HANDLE );
626         return;
627     }
628     if ((file = create_file_for_fd( fd, req->access, FILE_SHARE_READ | FILE_SHARE_WRITE,
629                                     0, DRIVE_UNKNOWN )))
630     {
631         reply->handle = alloc_handle( current->process, file, req->access, req->inherit );
632         release_object( file );
633     }
634 }
635
636 /* set a file current position */
637 DECL_HANDLER(set_file_pointer)
638 {
639     int high = req->high;
640     int low  = req->low;
641     set_file_pointer( req->handle, &low, &high, req->whence );
642     reply->new_low  = low;
643     reply->new_high = high;
644 }
645
646 /* truncate (or extend) a file */
647 DECL_HANDLER(truncate_file)
648 {
649     struct file *file;
650
651     if ((file = get_file_obj( current->process, req->handle, GENERIC_WRITE )))
652     {
653         truncate_file( file );
654         release_object( file );
655     }
656 }
657
658 /* set a file access and modification times */
659 DECL_HANDLER(set_file_time)
660 {
661     set_file_time( req->handle, req->access_time, req->write_time );
662 }
663
664 /* lock a region of a file */
665 DECL_HANDLER(lock_file)
666 {
667     struct file *file;
668
669     if ((file = get_file_obj( current->process, req->handle, 0 )))
670     {
671         file_lock( file, req->offset_high, req->offset_low,
672                    req->count_high, req->count_low );
673         release_object( file );
674     }
675 }
676
677 /* unlock a region of a file */
678 DECL_HANDLER(unlock_file)
679 {
680     struct file *file;
681
682     if ((file = get_file_obj( current->process, req->handle, 0 )))
683     {
684         file_unlock( file, req->offset_high, req->offset_low,
685                      req->count_high, req->count_low );
686         release_object( file );
687     }
688 }