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