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