wintrust: Map cert trust error status to a windows error.
[wine] / dlls / ntdll / file.c
1 /*
2  * Copyright 1999, 2000 Juergen Schmied
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #ifdef HAVE_SYS_ERRNO_H
31 #include <sys/errno.h>
32 #endif
33 #ifdef HAVE_LINUX_MAJOR_H
34 # include <linux/major.h>
35 #endif
36 #ifdef HAVE_SYS_STATVFS_H
37 # include <sys/statvfs.h>
38 #endif
39 #ifdef HAVE_SYS_PARAM_H
40 # include <sys/param.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 # include <sys/time.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48 #ifdef HAVE_SYS_FILIO_H
49 # include <sys/filio.h>
50 #endif
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #endif
54 #ifdef HAVE_SYS_POLL_H
55 #include <sys/poll.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
59 #endif
60 #ifdef HAVE_UTIME_H
61 # include <utime.h>
62 #endif
63 #ifdef HAVE_SYS_VFS_H
64 # include <sys/vfs.h>
65 #endif
66 #ifdef HAVE_SYS_MOUNT_H
67 # include <sys/mount.h>
68 #endif
69 #ifdef HAVE_SYS_STATFS_H
70 # include <sys/statfs.h>
71 #endif
72
73 #define NONAMELESSUNION
74 #define NONAMELESSSTRUCT
75 #include "ntstatus.h"
76 #define WIN32_NO_STATUS
77 #include "wine/unicode.h"
78 #include "wine/debug.h"
79 #include "wine/server.h"
80 #include "ntdll_misc.h"
81
82 #include "winternl.h"
83 #include "winioctl.h"
84 #include "ddk/ntddser.h"
85
86 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
87
88 mode_t FILE_umask = 0;
89
90 #define SECSPERDAY         86400
91 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
92
93 /**************************************************************************
94  *                 NtOpenFile                           [NTDLL.@]
95  *                 ZwOpenFile                           [NTDLL.@]
96  *
97  * Open a file.
98  *
99  * PARAMS
100  *  handle    [O] Variable that receives the file handle on return
101  *  access    [I] Access desired by the caller to the file
102  *  attr      [I] Structure describing the file to be opened
103  *  io        [O] Receives details about the result of the operation
104  *  sharing   [I] Type of shared access the caller requires
105  *  options   [I] Options for the file open
106  *
107  * RETURNS
108  *  Success: 0. FileHandle and IoStatusBlock are updated.
109  *  Failure: An NTSTATUS error code describing the error.
110  */
111 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
112                             POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
113                             ULONG sharing, ULONG options )
114 {
115     return NtCreateFile( handle, access, attr, io, NULL, 0,
116                          sharing, FILE_OPEN, options, NULL, 0 );
117 }
118
119 /**************************************************************************
120  *              NtCreateFile                            [NTDLL.@]
121  *              ZwCreateFile                            [NTDLL.@]
122  *
123  * Either create a new file or directory, or open an existing file, device,
124  * directory or volume.
125  *
126  * PARAMS
127  *      handle       [O] Points to a variable which receives the file handle on return
128  *      access       [I] Desired access to the file
129  *      attr         [I] Structure describing the file
130  *      io           [O] Receives information about the operation on return
131  *      alloc_size   [I] Initial size of the file in bytes
132  *      attributes   [I] Attributes to create the file with
133  *      sharing      [I] Type of shared access the caller would like to the file
134  *      disposition  [I] Specifies what to do, depending on whether the file already exists
135  *      options      [I] Options for creating a new file
136  *      ea_buffer    [I] Pointer to an extended attributes buffer
137  *      ea_length    [I] Length of ea_buffer
138  *
139  * RETURNS
140  *  Success: 0. handle and io are updated.
141  *  Failure: An NTSTATUS error code describing the error.
142  */
143 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
144                               PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
145                               ULONG attributes, ULONG sharing, ULONG disposition,
146                               ULONG options, PVOID ea_buffer, ULONG ea_length )
147 {
148     ANSI_STRING unix_name;
149     int created = FALSE;
150
151     TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p\n"
152           "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
153           handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
154           attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
155           attributes, sharing, disposition, options, ea_buffer, ea_length );
156
157     if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
158
159     if (alloc_size) FIXME( "alloc_size not supported\n" );
160
161     if (attr->RootDirectory)
162     {
163         FIXME( "RootDirectory %p not supported\n", attr->RootDirectory );
164         return STATUS_OBJECT_NAME_NOT_FOUND;
165     }
166
167     io->u.Status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, disposition,
168                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) );
169
170     if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
171     {
172         SERVER_START_REQ( open_file_object )
173         {
174             req->access     = access;
175             req->attributes = attr->Attributes;
176             req->rootdir    = attr->RootDirectory;
177             req->sharing    = sharing;
178             req->options    = options;
179             wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
180             io->u.Status = wine_server_call( req );
181             *handle = reply->handle;
182         }
183         SERVER_END_REQ;
184         if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
185         return io->u.Status;
186     }
187
188     if (io->u.Status == STATUS_NO_SUCH_FILE &&
189         disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
190     {
191         created = TRUE;
192         io->u.Status = STATUS_SUCCESS;
193     }
194
195     if (io->u.Status == STATUS_SUCCESS)
196     {
197         struct security_descriptor *sd = NULL;
198         struct object_attributes objattr;
199
200         objattr.rootdir = 0;
201         objattr.sd_len = 0;
202         objattr.name_len = 0;
203         if (attr)
204         {
205             io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
206             if (io->u.Status != STATUS_SUCCESS)
207             {
208                 RtlFreeAnsiString( &unix_name );
209                 return io->u.Status;
210             }
211         }
212
213         SERVER_START_REQ( create_file )
214         {
215             req->access     = access;
216             req->attributes = attr->Attributes;
217             req->sharing    = sharing;
218             req->create     = disposition;
219             req->options    = options;
220             req->attrs      = attributes;
221             wine_server_add_data( req, &objattr, sizeof(objattr) );
222             if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
223             wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
224             io->u.Status = wine_server_call( req );
225             *handle = reply->handle;
226         }
227         SERVER_END_REQ;
228         NTDLL_free_struct_sd( sd );
229         RtlFreeAnsiString( &unix_name );
230     }
231     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
232
233     if (io->u.Status == STATUS_SUCCESS)
234     {
235         if (created) io->Information = FILE_CREATED;
236         else switch(disposition)
237         {
238         case FILE_SUPERSEDE:
239             io->Information = FILE_SUPERSEDED;
240             break;
241         case FILE_CREATE:
242             io->Information = FILE_CREATED;
243             break;
244         case FILE_OPEN:
245         case FILE_OPEN_IF:
246             io->Information = FILE_OPENED;
247             break;
248         case FILE_OVERWRITE:
249         case FILE_OVERWRITE_IF:
250             io->Information = FILE_OVERWRITTEN;
251             break;
252         }
253     }
254
255     return io->u.Status;
256 }
257
258 /***********************************************************************
259  *                  Asynchronous file I/O                              *
260  */
261
262 struct async_fileio
263 {
264     HANDLE              handle;
265     PIO_APC_ROUTINE     apc;
266     void               *apc_arg;
267 };
268
269 typedef struct
270 {
271     struct async_fileio io;
272     char*               buffer;
273     unsigned int        already;
274     unsigned int        count;
275     BOOL                avail_mode;
276 } async_fileio_read;
277
278 typedef struct
279 {
280     struct async_fileio io;
281     const char         *buffer;
282     unsigned int        already;
283     unsigned int        count;
284 } async_fileio_write;
285
286
287 /* callback for file I/O user APC */
288 static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
289 {
290     struct async_fileio *async = arg;
291     if (async->apc) async->apc( async->apc_arg, io, reserved );
292     RtlFreeHeap( GetProcessHeap(), 0, async );
293 }
294
295 /***********************************************************************
296  *           FILE_GetNtStatus(void)
297  *
298  * Retrieve the Nt Status code from errno.
299  * Try to be consistent with FILE_SetDosError().
300  */
301 NTSTATUS FILE_GetNtStatus(void)
302 {
303     int err = errno;
304
305     TRACE( "errno = %d\n", errno );
306     switch (err)
307     {
308     case EAGAIN:    return STATUS_SHARING_VIOLATION;
309     case EBADF:     return STATUS_INVALID_HANDLE;
310     case EBUSY:     return STATUS_DEVICE_BUSY;
311     case ENOSPC:    return STATUS_DISK_FULL;
312     case EPERM:
313     case EROFS:
314     case EACCES:    return STATUS_ACCESS_DENIED;
315     case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
316     case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
317     case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
318     case EMFILE:
319     case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
320     case EINVAL:    return STATUS_INVALID_PARAMETER;
321     case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
322     case EPIPE:     return STATUS_PIPE_DISCONNECTED;
323     case EIO:       return STATUS_DEVICE_NOT_READY;
324 #ifdef ENOMEDIUM
325     case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
326 #endif
327     case ENXIO:     return STATUS_NO_SUCH_DEVICE;
328     case ENOTTY:
329     case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
330     case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
331     case EFAULT:    return STATUS_ACCESS_VIOLATION;
332     case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
333     case ENOEXEC:   /* ?? */
334     case EEXIST:    /* ?? */
335     default:
336         FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
337         return STATUS_UNSUCCESSFUL;
338     }
339 }
340
341 /***********************************************************************
342  *             FILE_AsyncReadService      (INTERNAL)
343  */
344 static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, ULONG_PTR *total)
345 {
346     async_fileio_read *fileio = user;
347     int fd, needs_close, result;
348
349     switch (status)
350     {
351     case STATUS_ALERTED: /* got some new data */
352         /* check to see if the data is ready (non-blocking) */
353         if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
354                                           &needs_close, NULL, NULL )))
355             break;
356
357         result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
358         if (needs_close) close( fd );
359
360         if (result < 0)
361         {
362             if (errno == EAGAIN || errno == EINTR)
363                 status = STATUS_PENDING;
364             else /* check to see if the transfer is complete */
365                 status = FILE_GetNtStatus();
366         }
367         else if (result == 0)
368         {
369             status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
370         }
371         else
372         {
373             fileio->already += result;
374             if (fileio->already >= fileio->count || fileio->avail_mode)
375                 status = STATUS_SUCCESS;
376             else
377             {
378                 /* if we only have to read the available data, and none is available,
379                  * simply cancel the request. If data was available, it has been read
380                  * while in by previous call (NtDelayExecution)
381                  */
382                 status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
383             }
384         }
385         break;
386
387     case STATUS_TIMEOUT:
388     case STATUS_IO_TIMEOUT:
389         if (fileio->already) status = STATUS_SUCCESS;
390         break;
391     }
392     if (status != STATUS_PENDING)
393     {
394         iosb->u.Status = status;
395         iosb->Information = *total = fileio->already;
396     }
397     return status;
398 }
399
400 struct io_timeouts
401 {
402     int interval;   /* max interval between two bytes */
403     int total;      /* total timeout for the whole operation */
404     int end_time;   /* absolute time of end of operation */
405 };
406
407 /* retrieve the I/O timeouts to use for a given handle */
408 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
409                                  struct io_timeouts *timeouts )
410 {
411     NTSTATUS status = STATUS_SUCCESS;
412
413     timeouts->interval = timeouts->total = -1;
414
415     switch(type)
416     {
417     case FD_TYPE_SERIAL:
418         {
419             /* GetCommTimeouts */
420             SERIAL_TIMEOUTS st;
421             IO_STATUS_BLOCK io;
422
423             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
424                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
425             if (status) break;
426
427             if (is_read)
428             {
429                 if (st.ReadIntervalTimeout)
430                     timeouts->interval = st.ReadIntervalTimeout;
431
432                 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
433                 {
434                     timeouts->total = st.ReadTotalTimeoutConstant;
435                     if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
436                         timeouts->total += count * st.ReadTotalTimeoutMultiplier;
437                 }
438                 else if (st.ReadIntervalTimeout == MAXDWORD)
439                     timeouts->interval = timeouts->total = 0;
440             }
441             else  /* write */
442             {
443                 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
444                 {
445                     timeouts->total = st.WriteTotalTimeoutConstant;
446                     if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
447                         timeouts->total += count * st.WriteTotalTimeoutMultiplier;
448                 }
449             }
450         }
451         break;
452     case FD_TYPE_MAILSLOT:
453         if (is_read)
454         {
455             timeouts->interval = 0;  /* return as soon as we got something */
456             SERVER_START_REQ( set_mailslot_info )
457             {
458                 req->handle = handle;
459                 req->flags = 0;
460                 if (!(status = wine_server_call( req )) &&
461                     reply->read_timeout != TIMEOUT_INFINITE)
462                     timeouts->total = reply->read_timeout / -10000;
463             }
464             SERVER_END_REQ;
465         }
466         break;
467     case FD_TYPE_SOCKET:
468     case FD_TYPE_PIPE:
469     case FD_TYPE_CHAR:
470         if (is_read) timeouts->interval = 0;  /* return as soon as we got something */
471         break;
472     default:
473         break;
474     }
475     if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
476     return STATUS_SUCCESS;
477 }
478
479
480 /* retrieve the timeout for the next wait, in milliseconds */
481 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
482 {
483     int ret = -1;
484
485     if (timeouts->total != -1)
486     {
487         ret = timeouts->end_time - NtGetTickCount();
488         if (ret < 0) ret = 0;
489     }
490     if (already && timeouts->interval != -1)
491     {
492         if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
493     }
494     return ret;
495 }
496
497
498 /* retrieve the avail_mode flag for async reads */
499 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
500 {
501     NTSTATUS status = STATUS_SUCCESS;
502
503     switch(type)
504     {
505     case FD_TYPE_SERIAL:
506         {
507             /* GetCommTimeouts */
508             SERIAL_TIMEOUTS st;
509             IO_STATUS_BLOCK io;
510
511             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
512                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
513             if (status) break;
514             *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
515                            !st.ReadTotalTimeoutConstant &&
516                            st.ReadIntervalTimeout == MAXDWORD);
517         }
518         break;
519     case FD_TYPE_MAILSLOT:
520     case FD_TYPE_SOCKET:
521     case FD_TYPE_PIPE:
522     case FD_TYPE_CHAR:
523         *avail_mode = TRUE;
524         break;
525     default:
526         *avail_mode = FALSE;
527         break;
528     }
529     return status;
530 }
531
532
533 /******************************************************************************
534  *  NtReadFile                                  [NTDLL.@]
535  *  ZwReadFile                                  [NTDLL.@]
536  *
537  * Read from an open file handle.
538  *
539  * PARAMS
540  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
541  *  Event         [I] Event to signal upon completion (or NULL)
542  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
543  *  ApcContext    [I] Context for ApcRoutine (or NULL)
544  *  IoStatusBlock [O] Receives information about the operation on return
545  *  Buffer        [O] Destination for the data read
546  *  Length        [I] Size of Buffer
547  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
548  *  Key           [O] Function unknown (may be NULL)
549  *
550  * RETURNS
551  *  Success: 0. IoStatusBlock is updated, and the Information member contains
552  *           The number of bytes read.
553  *  Failure: An NTSTATUS error code describing the error.
554  */
555 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
556                            PIO_APC_ROUTINE apc, void* apc_user,
557                            PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
558                            PLARGE_INTEGER offset, PULONG key)
559 {
560     int result, unix_handle, needs_close, timeout_init_done = 0;
561     unsigned int options;
562     struct io_timeouts timeouts;
563     NTSTATUS status;
564     ULONG total = 0;
565     enum server_fd_type type;
566     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
567
568     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
569           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
570
571     if (!io_status) return STATUS_ACCESS_VIOLATION;
572
573     status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
574                                  &needs_close, &type, &options );
575     if (status) return status;
576
577     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
578     {
579         /* async I/O doesn't make sense on regular files */
580         while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
581         {
582             if (errno != EINTR)
583             {
584                 status = FILE_GetNtStatus();
585                 goto done;
586             }
587         }
588         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
589             /* update file pointer position */
590             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
591
592         total = result;
593         status = total ? STATUS_SUCCESS : STATUS_END_OF_FILE;
594         goto done;
595     }
596
597     for (;;)
598     {
599         if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
600         {
601             total += result;
602             if (!result || total == length)
603             {
604                 if (total)
605                 {
606                     status = STATUS_SUCCESS;
607                     goto done;
608                 }
609                 switch (type)
610                 {
611                 case FD_TYPE_FILE:
612                 case FD_TYPE_CHAR:
613                     status = STATUS_END_OF_FILE;
614                     goto done;
615                 case FD_TYPE_SERIAL:
616                     break;
617                 default:
618                     status = STATUS_PIPE_BROKEN;
619                     goto done;
620                 }
621             }
622         }
623         else
624         {
625             if (errno == EINTR) continue;
626             if (errno != EAGAIN)
627             {
628                 status = FILE_GetNtStatus();
629                 goto done;
630             }
631         }
632
633         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
634         {
635             async_fileio_read *fileio;
636             BOOL avail_mode;
637
638             if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
639                 goto err;
640             if (total && avail_mode)
641             {
642                 status = STATUS_SUCCESS;
643                 goto done;
644             }
645
646             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
647             {
648                 status = STATUS_NO_MEMORY;
649                 goto err;
650             }
651             fileio->io.handle  = hFile;
652             fileio->io.apc     = apc;
653             fileio->io.apc_arg = apc_user;
654             fileio->already = total;
655             fileio->count = length;
656             fileio->buffer = buffer;
657             fileio->avail_mode = avail_mode;
658
659             SERVER_START_REQ( register_async )
660             {
661                 req->handle = hFile;
662                 req->type   = ASYNC_TYPE_READ;
663                 req->count  = length;
664                 req->async.callback = FILE_AsyncReadService;
665                 req->async.iosb     = io_status;
666                 req->async.arg      = fileio;
667                 req->async.apc      = fileio_apc;
668                 req->async.event    = hEvent;
669                 req->async.cvalue   = cvalue;
670                 status = wine_server_call( req );
671             }
672             SERVER_END_REQ;
673
674             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
675             goto err;
676         }
677         else  /* synchronous read, wait for the fd to become ready */
678         {
679             struct pollfd pfd;
680             int ret, timeout;
681
682             if (!timeout_init_done)
683             {
684                 timeout_init_done = 1;
685                 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
686                     goto err;
687                 if (hEvent) NtResetEvent( hEvent, NULL );
688             }
689             timeout = get_next_io_timeout( &timeouts, total );
690
691             pfd.fd = unix_handle;
692             pfd.events = POLLIN;
693
694             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
695             {
696                 if (total)  /* return with what we got so far */
697                     status = STATUS_SUCCESS;
698                 else
699                     status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
700                 goto done;
701             }
702             if (ret == -1 && errno != EINTR)
703             {
704                 status = FILE_GetNtStatus();
705                 goto done;
706             }
707             /* will now restart the read */
708         }
709     }
710
711 done:
712     if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );
713
714 err:
715     if (needs_close) close( unix_handle );
716     if (status == STATUS_SUCCESS)
717     {
718         io_status->u.Status = status;
719         io_status->Information = total;
720         TRACE("= SUCCESS (%u)\n", total);
721         if (hEvent) NtSetEvent( hEvent, NULL );
722         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
723                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
724     }
725     else
726     {
727         TRACE("= 0x%08x\n", status);
728         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
729     }
730     return status;
731 }
732
733
734 /******************************************************************************
735  *  NtReadFileScatter   [NTDLL.@]
736  *  ZwReadFileScatter   [NTDLL.@]
737  */
738 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
739                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
740                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
741 {
742     size_t page_size = getpagesize();
743     int result, unix_handle, needs_close;
744     unsigned int options;
745     NTSTATUS status;
746     ULONG pos = 0, total = 0;
747     enum server_fd_type type;
748     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
749
750     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
751            file, event, apc, apc_user, io_status, segments, length, offset, key);
752
753     if (length % page_size) return STATUS_INVALID_PARAMETER;
754     if (!io_status) return STATUS_ACCESS_VIOLATION;
755
756     status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
757                                  &needs_close, &type, &options );
758     if (status) return status;
759
760     if ((type != FD_TYPE_FILE) ||
761         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
762         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
763     {
764         status = STATUS_INVALID_PARAMETER;
765         goto error;
766     }
767
768     while (length)
769     {
770         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
771             result = pread( unix_handle, (char *)segments->Buffer + pos,
772                             page_size - pos, offset->QuadPart + total );
773         else
774             result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
775
776         if (result == -1)
777         {
778             if (errno == EINTR) continue;
779             status = FILE_GetNtStatus();
780             break;
781         }
782         if (!result)
783         {
784             status = STATUS_END_OF_FILE;
785             break;
786         }
787         total += result;
788         length -= result;
789         if ((pos += result) == page_size)
790         {
791             pos = 0;
792             segments++;
793         }
794     }
795
796     if (cvalue) NTDLL_AddCompletion( file, cvalue, status, total );
797
798  error:
799     if (needs_close) close( unix_handle );
800     if (status == STATUS_SUCCESS)
801     {
802         io_status->u.Status = status;
803         io_status->Information = total;
804         TRACE("= SUCCESS (%u)\n", total);
805         if (event) NtSetEvent( event, NULL );
806         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
807                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
808     }
809     else
810     {
811         TRACE("= 0x%08x\n", status);
812         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
813     }
814     return status;
815 }
816
817
818 /***********************************************************************
819  *             FILE_AsyncWriteService      (INTERNAL)
820  */
821 static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, ULONG_PTR *total)
822 {
823     async_fileio_write *fileio = user;
824     int result, fd, needs_close;
825     enum server_fd_type type;
826
827     switch (status)
828     {
829     case STATUS_ALERTED:
830         /* write some data (non-blocking) */
831         if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
832                                           &needs_close, &type, NULL )))
833             break;
834
835         if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
836             result = send( fd, fileio->buffer, 0, 0 );
837         else
838             result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
839
840         if (needs_close) close( fd );
841
842         if (result < 0)
843         {
844             if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
845             else status = FILE_GetNtStatus();
846         }
847         else
848         {
849             fileio->already += result;
850             status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
851         }
852         break;
853
854     case STATUS_TIMEOUT:
855     case STATUS_IO_TIMEOUT:
856         if (fileio->already) status = STATUS_SUCCESS;
857         break;
858     }
859     if (status != STATUS_PENDING)
860     {
861         iosb->u.Status = status;
862         iosb->Information = *total = fileio->already;
863     }
864     return status;
865 }
866
867 /******************************************************************************
868  *  NtWriteFile                                 [NTDLL.@]
869  *  ZwWriteFile                                 [NTDLL.@]
870  *
871  * Write to an open file handle.
872  *
873  * PARAMS
874  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
875  *  Event         [I] Event to signal upon completion (or NULL)
876  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
877  *  ApcContext    [I] Context for ApcRoutine (or NULL)
878  *  IoStatusBlock [O] Receives information about the operation on return
879  *  Buffer        [I] Source for the data to write
880  *  Length        [I] Size of Buffer
881  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
882  *  Key           [O] Function unknown (may be NULL)
883  *
884  * RETURNS
885  *  Success: 0. IoStatusBlock is updated, and the Information member contains
886  *           The number of bytes written.
887  *  Failure: An NTSTATUS error code describing the error.
888  */
889 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
890                             PIO_APC_ROUTINE apc, void* apc_user,
891                             PIO_STATUS_BLOCK io_status, 
892                             const void* buffer, ULONG length,
893                             PLARGE_INTEGER offset, PULONG key)
894 {
895     int result, unix_handle, needs_close, timeout_init_done = 0;
896     unsigned int options;
897     struct io_timeouts timeouts;
898     NTSTATUS status;
899     ULONG total = 0;
900     enum server_fd_type type;
901     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
902
903     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
904           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
905
906     if (!io_status) return STATUS_ACCESS_VIOLATION;
907
908     status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
909                                  &needs_close, &type, &options );
910     if (status) return status;
911
912     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
913     {
914         /* async I/O doesn't make sense on regular files */
915         while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
916         {
917             if (errno != EINTR)
918             {
919                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
920                 else status = FILE_GetNtStatus();
921                 goto done;
922             }
923         }
924
925         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
926             /* update file pointer position */
927             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
928
929         total = result;
930         status = STATUS_SUCCESS;
931         goto done;
932     }
933
934     for (;;)
935     {
936         /* zero-length writes on sockets may not work with plain write(2) */
937         if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
938             result = send( unix_handle, buffer, 0, 0 );
939         else
940             result = write( unix_handle, (const char *)buffer + total, length - total );
941
942         if (result >= 0)
943         {
944             total += result;
945             if (total == length)
946             {
947                 status = STATUS_SUCCESS;
948                 goto done;
949             }
950         }
951         else
952         {
953             if (errno == EINTR) continue;
954             if (errno != EAGAIN)
955             {
956                 if (errno == EFAULT)
957                 {
958                     status = STATUS_INVALID_USER_BUFFER;
959                     goto err;
960                 }
961                 status = FILE_GetNtStatus();
962                 goto done;
963             }
964         }
965
966         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
967         {
968             async_fileio_write *fileio;
969
970             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
971             {
972                 status = STATUS_NO_MEMORY;
973                 goto err;
974             }
975             fileio->io.handle  = hFile;
976             fileio->io.apc     = apc;
977             fileio->io.apc_arg = apc_user;
978             fileio->already = total;
979             fileio->count = length;
980             fileio->buffer = buffer;
981
982             SERVER_START_REQ( register_async )
983             {
984                 req->handle = hFile;
985                 req->type   = ASYNC_TYPE_WRITE;
986                 req->count  = length;
987                 req->async.callback = FILE_AsyncWriteService;
988                 req->async.iosb     = io_status;
989                 req->async.arg      = fileio;
990                 req->async.apc      = fileio_apc;
991                 req->async.event    = hEvent;
992                 req->async.cvalue   = cvalue;
993                 status = wine_server_call( req );
994             }
995             SERVER_END_REQ;
996
997             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
998             goto err;
999         }
1000         else  /* synchronous write, wait for the fd to become ready */
1001         {
1002             struct pollfd pfd;
1003             int ret, timeout;
1004
1005             if (!timeout_init_done)
1006             {
1007                 timeout_init_done = 1;
1008                 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1009                     goto err;
1010                 if (hEvent) NtResetEvent( hEvent, NULL );
1011             }
1012             timeout = get_next_io_timeout( &timeouts, total );
1013
1014             pfd.fd = unix_handle;
1015             pfd.events = POLLOUT;
1016
1017             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1018             {
1019                 /* return with what we got so far */
1020                 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1021                 goto done;
1022             }
1023             if (ret == -1 && errno != EINTR)
1024             {
1025                 status = FILE_GetNtStatus();
1026                 goto done;
1027             }
1028             /* will now restart the write */
1029         }
1030     }
1031
1032 done:
1033     if (cvalue) NTDLL_AddCompletion( hFile, cvalue, status, total );
1034
1035 err:
1036     if (needs_close) close( unix_handle );
1037     if (status == STATUS_SUCCESS)
1038     {
1039         io_status->u.Status = status;
1040         io_status->Information = total;
1041         TRACE("= SUCCESS (%u)\n", total);
1042         if (hEvent) NtSetEvent( hEvent, NULL );
1043         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1044                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1045     }
1046     else
1047     {
1048         TRACE("= 0x%08x\n", status);
1049         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1050     }
1051     return status;
1052 }
1053
1054
1055 /******************************************************************************
1056  *  NtWriteFileGather   [NTDLL.@]
1057  *  ZwWriteFileGather   [NTDLL.@]
1058  */
1059 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1060                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1061                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
1062 {
1063     size_t page_size = getpagesize();
1064     int result, unix_handle, needs_close;
1065     unsigned int options;
1066     NTSTATUS status;
1067     ULONG pos = 0, total = 0;
1068     enum server_fd_type type;
1069     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1070
1071     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1072            file, event, apc, apc_user, io_status, segments, length, offset, key);
1073
1074     if (length % page_size) return STATUS_INVALID_PARAMETER;
1075     if (!io_status) return STATUS_ACCESS_VIOLATION;
1076
1077     status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1078                                  &needs_close, &type, &options );
1079     if (status) return status;
1080
1081     if ((type != FD_TYPE_FILE) ||
1082         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1083         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1084     {
1085         status = STATUS_INVALID_PARAMETER;
1086         goto error;
1087     }
1088
1089     while (length)
1090     {
1091         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
1092             result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1093                              page_size - pos, offset->QuadPart + total );
1094         else
1095             result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1096
1097         if (result == -1)
1098         {
1099             if (errno == EINTR) continue;
1100             if (errno == EFAULT)
1101             {
1102                 status = STATUS_INVALID_USER_BUFFER;
1103                 goto error;
1104             }
1105             status = FILE_GetNtStatus();
1106             break;
1107         }
1108         if (!result)
1109         {
1110             status = STATUS_DISK_FULL;
1111             break;
1112         }
1113         total += result;
1114         length -= result;
1115         if ((pos += result) == page_size)
1116         {
1117             pos = 0;
1118             segments++;
1119         }
1120     }
1121
1122     if (cvalue) NTDLL_AddCompletion( file, cvalue, status, total );
1123
1124  error:
1125     if (needs_close) close( unix_handle );
1126     if (status == STATUS_SUCCESS)
1127     {
1128         io_status->u.Status = status;
1129         io_status->Information = total;
1130         TRACE("= SUCCESS (%u)\n", total);
1131         if (event) NtSetEvent( event, NULL );
1132         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1133                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1134     }
1135     else
1136     {
1137         TRACE("= 0x%08x\n", status);
1138         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1139     }
1140     return status;
1141 }
1142
1143
1144 struct async_ioctl
1145 {
1146     HANDLE          handle;   /* handle to the device */
1147     void           *buffer;   /* buffer for output */
1148     ULONG           size;     /* size of buffer */
1149     PIO_APC_ROUTINE apc;      /* user apc params */
1150     void           *apc_arg;
1151 };
1152
1153 /* callback for ioctl async I/O completion */
1154 static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status )
1155 {
1156     struct async_ioctl *async = arg;
1157
1158     if (status == STATUS_ALERTED)
1159     {
1160         SERVER_START_REQ( get_ioctl_result )
1161         {
1162             req->handle   = async->handle;
1163             req->user_arg = async;
1164             wine_server_set_reply( req, async->buffer, async->size );
1165             if (!(status = wine_server_call( req )))
1166                 io->Information = wine_server_reply_size( reply );
1167         }
1168         SERVER_END_REQ;
1169     }
1170     if (status != STATUS_PENDING) io->u.Status = status;
1171     return status;
1172 }
1173
1174 /* callback for ioctl user APC */
1175 static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
1176 {
1177     struct async_ioctl *async = arg;
1178     if (async->apc) async->apc( async->apc_arg, io, reserved );
1179     RtlFreeHeap( GetProcessHeap(), 0, async );
1180 }
1181
1182 /* do a ioctl call through the server */
1183 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1184                                    PIO_APC_ROUTINE apc, PVOID apc_context,
1185                                    IO_STATUS_BLOCK *io, ULONG code,
1186                                    const void *in_buffer, ULONG in_size,
1187                                    PVOID out_buffer, ULONG out_size )
1188 {
1189     struct async_ioctl *async;
1190     NTSTATUS status;
1191     HANDLE wait_handle;
1192     ULONG options;
1193     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1194
1195     if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
1196         return STATUS_NO_MEMORY;
1197     async->handle  = handle;
1198     async->buffer  = out_buffer;
1199     async->size    = out_size;
1200     async->apc     = apc;
1201     async->apc_arg = apc_context;
1202
1203     SERVER_START_REQ( ioctl )
1204     {
1205         req->handle         = handle;
1206         req->code           = code;
1207         req->async.callback = ioctl_completion;
1208         req->async.iosb     = io;
1209         req->async.arg      = async;
1210         req->async.apc      = (apc || event) ? ioctl_apc : NULL;
1211         req->async.event    = event;
1212         req->async.cvalue   = cvalue;
1213         wine_server_add_data( req, in_buffer, in_size );
1214         wine_server_set_reply( req, out_buffer, out_size );
1215         if (!(status = wine_server_call( req )))
1216             io->Information = wine_server_reply_size( reply );
1217         wait_handle = reply->wait;
1218         options     = reply->options;
1219     }
1220     SERVER_END_REQ;
1221
1222     if (status == STATUS_NOT_SUPPORTED)
1223         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1224               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1225
1226     if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1227
1228     if (wait_handle)
1229     {
1230         NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1231         status = io->u.Status;
1232         NtClose( wait_handle );
1233         RtlFreeHeap( GetProcessHeap(), 0, async );
1234     }
1235
1236     return status;
1237 }
1238
1239
1240 /**************************************************************************
1241  *              NtDeviceIoControlFile                   [NTDLL.@]
1242  *              ZwDeviceIoControlFile                   [NTDLL.@]
1243  *
1244  * Perform an I/O control operation on an open file handle.
1245  *
1246  * PARAMS
1247  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1248  *  event          [I] Event to signal upon completion (or NULL)
1249  *  apc            [I] Callback to call upon completion (or NULL)
1250  *  apc_context    [I] Context for ApcRoutine (or NULL)
1251  *  io             [O] Receives information about the operation on return
1252  *  code           [I] Control code for the operation to perform
1253  *  in_buffer      [I] Source for any input data required (or NULL)
1254  *  in_size        [I] Size of InputBuffer
1255  *  out_buffer     [O] Source for any output data returned (or NULL)
1256  *  out_size       [I] Size of OutputBuffer
1257  *
1258  * RETURNS
1259  *  Success: 0. IoStatusBlock is updated.
1260  *  Failure: An NTSTATUS error code describing the error.
1261  */
1262 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1263                                       PIO_APC_ROUTINE apc, PVOID apc_context,
1264                                       PIO_STATUS_BLOCK io, ULONG code,
1265                                       PVOID in_buffer, ULONG in_size,
1266                                       PVOID out_buffer, ULONG out_size)
1267 {
1268     ULONG device = (code >> 16);
1269     NTSTATUS status = STATUS_NOT_SUPPORTED;
1270
1271     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1272           handle, event, apc, apc_context, io, code,
1273           in_buffer, in_size, out_buffer, out_size);
1274
1275     switch(device)
1276     {
1277     case FILE_DEVICE_DISK:
1278     case FILE_DEVICE_CD_ROM:
1279     case FILE_DEVICE_DVD:
1280     case FILE_DEVICE_CONTROLLER:
1281     case FILE_DEVICE_MASS_STORAGE:
1282         status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1283                                        in_buffer, in_size, out_buffer, out_size);
1284         break;
1285     case FILE_DEVICE_SERIAL_PORT:
1286         status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1287                                       in_buffer, in_size, out_buffer, out_size);
1288         break;
1289     case FILE_DEVICE_TAPE:
1290         status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1291                                       in_buffer, in_size, out_buffer, out_size);
1292         break;
1293     }
1294
1295     if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1296         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1297                                     in_buffer, in_size, out_buffer, out_size );
1298
1299     if (status != STATUS_PENDING) io->u.Status = status;
1300     return status;
1301 }
1302
1303
1304 /**************************************************************************
1305  *              NtFsControlFile                 [NTDLL.@]
1306  *              ZwFsControlFile                 [NTDLL.@]
1307  *
1308  * Perform a file system control operation on an open file handle.
1309  *
1310  * PARAMS
1311  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1312  *  event          [I] Event to signal upon completion (or NULL)
1313  *  apc            [I] Callback to call upon completion (or NULL)
1314  *  apc_context    [I] Context for ApcRoutine (or NULL)
1315  *  io             [O] Receives information about the operation on return
1316  *  code           [I] Control code for the operation to perform
1317  *  in_buffer      [I] Source for any input data required (or NULL)
1318  *  in_size        [I] Size of InputBuffer
1319  *  out_buffer     [O] Source for any output data returned (or NULL)
1320  *  out_size       [I] Size of OutputBuffer
1321  *
1322  * RETURNS
1323  *  Success: 0. IoStatusBlock is updated.
1324  *  Failure: An NTSTATUS error code describing the error.
1325  */
1326 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1327                                 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1328                                 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1329 {
1330     NTSTATUS status;
1331
1332     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1333           handle, event, apc, apc_context, io, code,
1334           in_buffer, in_size, out_buffer, out_size);
1335
1336     if (!io) return STATUS_INVALID_PARAMETER;
1337
1338     switch(code)
1339     {
1340     case FSCTL_DISMOUNT_VOLUME:
1341         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1342                                     in_buffer, in_size, out_buffer, out_size );
1343         if (!status) status = DIR_unmount_device( handle );
1344         break;
1345
1346     case FSCTL_PIPE_PEEK:
1347         {
1348             FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1349             int avail = 0, fd, needs_close;
1350
1351             if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1352             {
1353                 status = STATUS_INFO_LENGTH_MISMATCH;
1354                 break;
1355             }
1356
1357             if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1358                 break;
1359
1360 #ifdef FIONREAD
1361             if (ioctl( fd, FIONREAD, &avail ) != 0)
1362             {
1363                 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1364                 if (needs_close) close( fd );
1365                 status = FILE_GetNtStatus();
1366                 break;
1367             }
1368 #endif
1369             if (!avail)  /* check for closed pipe */
1370             {
1371                 struct pollfd pollfd;
1372                 int ret;
1373
1374                 pollfd.fd = fd;
1375                 pollfd.events = POLLIN;
1376                 pollfd.revents = 0;
1377                 ret = poll( &pollfd, 1, 0 );
1378                 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1379                 {
1380                     if (needs_close) close( fd );
1381                     status = STATUS_PIPE_BROKEN;
1382                     break;
1383                 }
1384             }
1385             buffer->NamedPipeState    = 0;  /* FIXME */
1386             buffer->ReadDataAvailable = avail;
1387             buffer->NumberOfMessages  = 0;  /* FIXME */
1388             buffer->MessageLength     = 0;  /* FIXME */
1389             io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1390             status = STATUS_SUCCESS;
1391             if (avail)
1392             {
1393                 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1394                 if (data_size)
1395                 {
1396                     int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1397                     if (res >= 0) io->Information += res;
1398                 }
1399             }
1400             if (needs_close) close( fd );
1401         }
1402         break;
1403
1404     case FSCTL_PIPE_DISCONNECT:
1405         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1406                                     in_buffer, in_size, out_buffer, out_size );
1407         if (!status)
1408         {
1409             int fd = server_remove_fd_from_cache( handle );
1410             if (fd != -1) close( fd );
1411         }
1412         break;
1413
1414     case FSCTL_PIPE_IMPERSONATE:
1415         FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1416         status = RtlImpersonateSelf( SecurityImpersonation );
1417         break;
1418
1419     case FSCTL_LOCK_VOLUME:
1420     case FSCTL_UNLOCK_VOLUME:
1421         FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1422               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1423         status = STATUS_SUCCESS;
1424         break;
1425
1426     case FSCTL_PIPE_LISTEN:
1427     case FSCTL_PIPE_WAIT:
1428     default:
1429         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1430                                     in_buffer, in_size, out_buffer, out_size );
1431         break;
1432     }
1433
1434     if (status != STATUS_PENDING) io->u.Status = status;
1435     return status;
1436 }
1437
1438 /******************************************************************************
1439  *  NtSetVolumeInformationFile          [NTDLL.@]
1440  *  ZwSetVolumeInformationFile          [NTDLL.@]
1441  *
1442  * Set volume information for an open file handle.
1443  *
1444  * PARAMS
1445  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1446  *  IoStatusBlock      [O] Receives information about the operation on return
1447  *  FsInformation      [I] Source for volume information
1448  *  Length             [I] Size of FsInformation
1449  *  FsInformationClass [I] Type of volume information to set
1450  *
1451  * RETURNS
1452  *  Success: 0. IoStatusBlock is updated.
1453  *  Failure: An NTSTATUS error code describing the error.
1454  */
1455 NTSTATUS WINAPI NtSetVolumeInformationFile(
1456         IN HANDLE FileHandle,
1457         PIO_STATUS_BLOCK IoStatusBlock,
1458         PVOID FsInformation,
1459         ULONG Length,
1460         FS_INFORMATION_CLASS FsInformationClass)
1461 {
1462         FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1463         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1464         return 0;
1465 }
1466
1467 /******************************************************************************
1468  *  NtQueryInformationFile              [NTDLL.@]
1469  *  ZwQueryInformationFile              [NTDLL.@]
1470  *
1471  * Get information about an open file handle.
1472  *
1473  * PARAMS
1474  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1475  *  io       [O] Receives information about the operation on return
1476  *  ptr      [O] Destination for file information
1477  *  len      [I] Size of FileInformation
1478  *  class    [I] Type of file information to get
1479  *
1480  * RETURNS
1481  *  Success: 0. IoStatusBlock and FileInformation are updated.
1482  *  Failure: An NTSTATUS error code describing the error.
1483  */
1484 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
1485                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
1486 {
1487     static const size_t info_sizes[] =
1488     {
1489         0,
1490         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
1491         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
1492         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
1493         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
1494         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
1495         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
1496         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
1497         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
1498         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
1499         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
1500         0,                                             /* FileLinkInformation */
1501         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
1502         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
1503         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
1504         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
1505         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
1506         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
1507         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
1508         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
1509         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
1510         0,                                             /* FileAlternateNameInformation */
1511         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
1512         0,                                             /* FilePipeInformation */
1513         sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1514         0,                                             /* FilePipeRemoteInformation */
1515         sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1516         0,                                             /* FileMailslotSetInformation */
1517         0,                                             /* FileCompressionInformation */
1518         0,                                             /* FileObjectIdInformation */
1519         0,                                             /* FileCompletionInformation */
1520         0,                                             /* FileMoveClusterInformation */
1521         0,                                             /* FileQuotaInformation */
1522         0,                                             /* FileReparsePointInformation */
1523         0,                                             /* FileNetworkOpenInformation */
1524         0,                                             /* FileAttributeTagInformation */
1525         0                                              /* FileTrackingInformation */
1526     };
1527
1528     struct stat st;
1529     int fd, needs_close = FALSE;
1530
1531     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1532
1533     io->Information = 0;
1534
1535     if (class <= 0 || class >= FileMaximumInformation)
1536         return io->u.Status = STATUS_INVALID_INFO_CLASS;
1537     if (!info_sizes[class])
1538     {
1539         FIXME("Unsupported class (%d)\n", class);
1540         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1541     }
1542     if (len < info_sizes[class])
1543         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1544
1545     if (class != FilePipeLocalInformation)
1546     {
1547         if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1548             return io->u.Status;
1549     }
1550
1551     switch (class)
1552     {
1553     case FileBasicInformation:
1554         {
1555             FILE_BASIC_INFORMATION *info = ptr;
1556
1557             if (fstat( fd, &st ) == -1)
1558                 io->u.Status = FILE_GetNtStatus();
1559             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1560                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1561             else
1562             {
1563                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1564                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1565                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1566                     info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1567                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
1568                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
1569                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
1570                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1571 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1572                 info->CreationTime.QuadPart += st.st_mtim.tv_nsec / 100;
1573                 info->LastWriteTime.QuadPart += st.st_mtim.tv_nsec / 100;
1574 #endif
1575 #ifdef HAVE_STRUCT_STAT_ST_CTIM
1576                 info->ChangeTime.QuadPart += st.st_ctim.tv_nsec / 100;
1577 #endif
1578 #ifdef HAVE_STRUCT_STAT_ST_ATIM
1579                 info->LastAccessTime.QuadPart += st.st_atim.tv_nsec / 100;
1580 #endif
1581             }
1582         }
1583         break;
1584     case FileStandardInformation:
1585         {
1586             FILE_STANDARD_INFORMATION *info = ptr;
1587
1588             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1589             else
1590             {
1591                 if ((info->Directory = S_ISDIR(st.st_mode)))
1592                 {
1593                     info->AllocationSize.QuadPart = 0;
1594                     info->EndOfFile.QuadPart      = 0;
1595                     info->NumberOfLinks           = 1;
1596                     info->DeletePending           = FALSE;
1597                 }
1598                 else
1599                 {
1600                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1601                     info->EndOfFile.QuadPart      = st.st_size;
1602                     info->NumberOfLinks           = st.st_nlink;
1603                     info->DeletePending           = FALSE; /* FIXME */
1604                 }
1605             }
1606         }
1607         break;
1608     case FilePositionInformation:
1609         {
1610             FILE_POSITION_INFORMATION *info = ptr;
1611             off_t res = lseek( fd, 0, SEEK_CUR );
1612             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
1613             else info->CurrentByteOffset.QuadPart = res;
1614         }
1615         break;
1616     case FileInternalInformation:
1617         {
1618             FILE_INTERNAL_INFORMATION *info = ptr;
1619
1620             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1621             else info->IndexNumber.QuadPart = st.st_ino;
1622         }
1623         break;
1624     case FileEaInformation:
1625         {
1626             FILE_EA_INFORMATION *info = ptr;
1627             info->EaSize = 0;
1628         }
1629         break;
1630     case FileEndOfFileInformation:
1631         {
1632             FILE_END_OF_FILE_INFORMATION *info = ptr;
1633
1634             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1635             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
1636         }
1637         break;
1638     case FileAllInformation:
1639         {
1640             FILE_ALL_INFORMATION *info = ptr;
1641
1642             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1643             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1644                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1645             else
1646             {
1647                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
1648                 {
1649                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1650                     info->StandardInformation.AllocationSize.QuadPart = 0;
1651                     info->StandardInformation.EndOfFile.QuadPart      = 0;
1652                     info->StandardInformation.NumberOfLinks           = 1;
1653                     info->StandardInformation.DeletePending           = FALSE;
1654                 }
1655                 else
1656                 {
1657                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1658                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1659                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1660                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1661                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1662                 }
1663                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1664                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1665                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1666                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1667                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1668                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1669 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1670                 info->BasicInformation.CreationTime.QuadPart += st.st_mtim.tv_nsec / 100;
1671                 info->BasicInformation.LastWriteTime.QuadPart += st.st_mtim.tv_nsec / 100;
1672 #endif
1673 #ifdef HAVE_STRUCT_STAT_ST_CTIM
1674                 info->BasicInformation.ChangeTime.QuadPart += st.st_ctim.tv_nsec / 100;
1675 #endif
1676 #ifdef HAVE_STRUCT_STAT_ST_ATIM
1677                 info->BasicInformation.LastAccessTime.QuadPart += st.st_atim.tv_nsec / 100;
1678 #endif
1679                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1680                 info->EaInformation.EaSize = 0;
1681                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1682                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1683                 info->ModeInformation.Mode = 0;  /* FIXME */
1684                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1685                 info->NameInformation.FileNameLength = 0;
1686                 io->Information = sizeof(*info) - sizeof(WCHAR);
1687             }
1688         }
1689         break;
1690     case FileMailslotQueryInformation:
1691         {
1692             FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
1693
1694             SERVER_START_REQ( set_mailslot_info )
1695             {
1696                 req->handle = hFile;
1697                 req->flags = 0;
1698                 io->u.Status = wine_server_call( req );
1699                 if( io->u.Status == STATUS_SUCCESS )
1700                 {
1701                     info->MaximumMessageSize = reply->max_msgsize;
1702                     info->MailslotQuota = 0;
1703                     info->NextMessageSize = 0;
1704                     info->MessagesAvailable = 0;
1705                     info->ReadTimeout.QuadPart = reply->read_timeout;
1706                 }
1707             }
1708             SERVER_END_REQ;
1709             if (!io->u.Status)
1710             {
1711                 char *tmpbuf;
1712                 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1713                 if (size > 0x10000) size = 0x10000;
1714                 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1715                 {
1716                     int fd, needs_close;
1717                     if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1718                     {
1719                         int res = recv( fd, tmpbuf, size, MSG_PEEK );
1720                         info->MessagesAvailable = (res > 0);
1721                         info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
1722                         if (needs_close) close( fd );
1723                     }
1724                     RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
1725                 }
1726             }
1727         }
1728         break;
1729     case FilePipeLocalInformation:
1730         {
1731             FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
1732
1733             SERVER_START_REQ( get_named_pipe_info )
1734             {
1735                 req->handle = hFile;
1736                 if (!(io->u.Status = wine_server_call( req )))
1737                 {
1738                     pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
1739                         FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
1740                     pli->NamedPipeConfiguration = 0; /* FIXME */
1741                     pli->MaximumInstances = reply->maxinstances;
1742                     pli->CurrentInstances = reply->instances;
1743                     pli->InboundQuota = reply->insize;
1744                     pli->ReadDataAvailable = 0; /* FIXME */
1745                     pli->OutboundQuota = reply->outsize;
1746                     pli->WriteQuotaAvailable = 0; /* FIXME */
1747                     pli->NamedPipeState = 0; /* FIXME */
1748                     pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
1749                         FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
1750                 }
1751             }
1752             SERVER_END_REQ;
1753         }
1754         break;
1755     default:
1756         FIXME("Unsupported class (%d)\n", class);
1757         io->u.Status = STATUS_NOT_IMPLEMENTED;
1758         break;
1759     }
1760     if (needs_close) close( fd );
1761     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1762     return io->u.Status;
1763 }
1764
1765 /******************************************************************************
1766  *  NtSetInformationFile                [NTDLL.@]
1767  *  ZwSetInformationFile                [NTDLL.@]
1768  *
1769  * Set information about an open file handle.
1770  *
1771  * PARAMS
1772  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1773  *  io      [O] Receives information about the operation on return
1774  *  ptr     [I] Source for file information
1775  *  len     [I] Size of FileInformation
1776  *  class   [I] Type of file information to set
1777  *
1778  * RETURNS
1779  *  Success: 0. io is updated.
1780  *  Failure: An NTSTATUS error code describing the error.
1781  */
1782 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1783                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1784 {
1785     int fd, needs_close;
1786
1787     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1788
1789     io->u.Status = STATUS_SUCCESS;
1790     switch (class)
1791     {
1792     case FileBasicInformation:
1793         if (len >= sizeof(FILE_BASIC_INFORMATION))
1794         {
1795             struct stat st;
1796             const FILE_BASIC_INFORMATION *info = ptr;
1797
1798             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1799                 return io->u.Status;
1800
1801             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1802             {
1803                 ULONGLONG sec, nsec;
1804                 struct timeval tv[2];
1805
1806                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1807                 {
1808
1809                     tv[0].tv_sec = tv[0].tv_usec = 0;
1810                     tv[1].tv_sec = tv[1].tv_usec = 0;
1811                     if (!fstat( fd, &st ))
1812                     {
1813                         tv[0].tv_sec = st.st_atime;
1814                         tv[1].tv_sec = st.st_mtime;
1815                     }
1816                 }
1817                 if (info->LastAccessTime.QuadPart)
1818                 {
1819                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1820                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1821                     tv[0].tv_usec = (UINT)nsec / 10;
1822                 }
1823                 if (info->LastWriteTime.QuadPart)
1824                 {
1825                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1826                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1827                     tv[1].tv_usec = (UINT)nsec / 10;
1828                 }
1829                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1830             }
1831
1832             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1833             {
1834                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1835                 else
1836                 {
1837                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1838                     {
1839                         if (S_ISDIR( st.st_mode))
1840                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1841                         else
1842                             st.st_mode &= ~0222; /* clear write permission bits */
1843                     }
1844                     else
1845                     {
1846                         /* add write permission only where we already have read permission */
1847                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1848                     }
1849                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1850                 }
1851             }
1852
1853             if (needs_close) close( fd );
1854         }
1855         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1856         break;
1857
1858     case FilePositionInformation:
1859         if (len >= sizeof(FILE_POSITION_INFORMATION))
1860         {
1861             const FILE_POSITION_INFORMATION *info = ptr;
1862
1863             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1864                 return io->u.Status;
1865
1866             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1867                 io->u.Status = FILE_GetNtStatus();
1868
1869             if (needs_close) close( fd );
1870         }
1871         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1872         break;
1873
1874     case FileEndOfFileInformation:
1875         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1876         {
1877             struct stat st;
1878             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1879
1880             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1881                 return io->u.Status;
1882
1883             /* first try normal truncate */
1884             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1885
1886             /* now check for the need to extend the file */
1887             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1888             {
1889                 static const char zero;
1890
1891                 /* extend the file one byte beyond the requested size and then truncate it */
1892                 /* this should work around ftruncate implementations that can't extend files */
1893                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1894                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1895             }
1896             io->u.Status = FILE_GetNtStatus();
1897
1898             if (needs_close) close( fd );
1899         }
1900         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1901         break;
1902
1903     case FileMailslotSetInformation:
1904         {
1905             FILE_MAILSLOT_SET_INFORMATION *info = ptr;
1906
1907             SERVER_START_REQ( set_mailslot_info )
1908             {
1909                 req->handle = handle;
1910                 req->flags = MAILSLOT_SET_READ_TIMEOUT;
1911                 req->read_timeout = info->ReadTimeout.QuadPart;
1912                 io->u.Status = wine_server_call( req );
1913             }
1914             SERVER_END_REQ;
1915         }
1916         break;
1917
1918     case FileCompletionInformation:
1919         if (len >= sizeof(FILE_COMPLETION_INFORMATION))
1920         {
1921             FILE_COMPLETION_INFORMATION *info = (FILE_COMPLETION_INFORMATION *)ptr;
1922
1923             SERVER_START_REQ( set_completion_info )
1924             {
1925                 req->handle   = handle;
1926                 req->chandle  = info->CompletionPort;
1927                 req->ckey     = info->CompletionKey;
1928                 io->u.Status  = wine_server_call( req );
1929             }
1930             SERVER_END_REQ;
1931         } else
1932             io->u.Status = STATUS_INVALID_PARAMETER_3;
1933         break;
1934
1935     default:
1936         FIXME("Unsupported class (%d)\n", class);
1937         io->u.Status = STATUS_NOT_IMPLEMENTED;
1938         break;
1939     }
1940     io->Information = 0;
1941     return io->u.Status;
1942 }
1943
1944
1945 /******************************************************************************
1946  *              NtQueryFullAttributesFile   (NTDLL.@)
1947  */
1948 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1949                                            FILE_NETWORK_OPEN_INFORMATION *info )
1950 {
1951     ANSI_STRING unix_name;
1952     NTSTATUS status;
1953
1954     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1955                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1956     {
1957         struct stat st;
1958
1959         if (stat( unix_name.Buffer, &st ) == -1)
1960             status = FILE_GetNtStatus();
1961         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1962             status = STATUS_INVALID_INFO_CLASS;
1963         else
1964         {
1965             if (S_ISDIR(st.st_mode))
1966             {
1967                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1968                 info->AllocationSize.QuadPart = 0;
1969                 info->EndOfFile.QuadPart      = 0;
1970             }
1971             else
1972             {
1973                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1974                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1975                 info->EndOfFile.QuadPart      = st.st_size;
1976             }
1977             if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1978                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1979             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1980             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1981             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1982             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1983             if (DIR_is_hidden_file( attr->ObjectName ))
1984                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1985         }
1986         RtlFreeAnsiString( &unix_name );
1987     }
1988     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1989     return status;
1990 }
1991
1992
1993 /******************************************************************************
1994  *              NtQueryAttributesFile   (NTDLL.@)
1995  *              ZwQueryAttributesFile   (NTDLL.@)
1996  */
1997 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1998 {
1999     FILE_NETWORK_OPEN_INFORMATION full_info;
2000     NTSTATUS status;
2001
2002     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
2003     {
2004         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
2005         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
2006         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
2007         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
2008         info->FileAttributes          = full_info.FileAttributes;
2009     }
2010     return status;
2011 }
2012
2013
2014 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
2015 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
2016 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
2017                                             unsigned int flags )
2018 {
2019     if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
2020     {
2021         info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2022         /* Don't assume read-only, let the mount options set it below */
2023         info->Characteristics |= FILE_REMOVABLE_MEDIA;
2024     }
2025     else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
2026              !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
2027     {
2028         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2029         info->Characteristics |= FILE_REMOTE_DEVICE;
2030     }
2031     else if (!strcmp("procfs", fstypename))
2032         info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2033     else
2034         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2035
2036     if (flags & MNT_RDONLY)
2037         info->Characteristics |= FILE_READ_ONLY_DEVICE;
2038
2039     if (!(flags & MNT_LOCAL))
2040     {
2041         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2042         info->Characteristics |= FILE_REMOTE_DEVICE;
2043     }
2044 }
2045 #endif
2046
2047 static inline int is_device_placeholder( int fd )
2048 {
2049     static const char wine_placeholder[] = "Wine device placeholder";
2050     char buffer[sizeof(wine_placeholder)-1];
2051
2052     if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
2053         return 0;
2054     return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
2055 }
2056
2057 /******************************************************************************
2058  *              get_device_info
2059  *
2060  * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
2061  */
2062 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2063 {
2064     struct stat st;
2065
2066     info->Characteristics = 0;
2067     if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
2068     if (S_ISCHR( st.st_mode ))
2069     {
2070         info->DeviceType = FILE_DEVICE_UNKNOWN;
2071 #ifdef linux
2072         switch(major(st.st_rdev))
2073         {
2074         case MEM_MAJOR:
2075             info->DeviceType = FILE_DEVICE_NULL;
2076             break;
2077         case TTY_MAJOR:
2078             info->DeviceType = FILE_DEVICE_SERIAL_PORT;
2079             break;
2080         case LP_MAJOR:
2081             info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
2082             break;
2083         case SCSI_TAPE_MAJOR:
2084             info->DeviceType = FILE_DEVICE_TAPE;
2085             break;
2086         }
2087 #endif
2088     }
2089     else if (S_ISBLK( st.st_mode ))
2090     {
2091         info->DeviceType = FILE_DEVICE_DISK;
2092     }
2093     else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
2094     {
2095         info->DeviceType = FILE_DEVICE_NAMED_PIPE;
2096     }
2097     else if (is_device_placeholder( fd ))
2098     {
2099         info->DeviceType = FILE_DEVICE_DISK;
2100     }
2101     else  /* regular file or directory */
2102     {
2103 #if defined(linux) && defined(HAVE_FSTATFS)
2104         struct statfs stfs;
2105
2106         /* check for floppy disk */
2107         if (major(st.st_dev) == FLOPPY_MAJOR)
2108             info->Characteristics |= FILE_REMOVABLE_MEDIA;
2109
2110         if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
2111         switch (stfs.f_type)
2112         {
2113         case 0x9660:      /* iso9660 */
2114         case 0x9fa1:      /* supermount */
2115         case 0x15013346:  /* udf */
2116             info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2117             info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2118             break;
2119         case 0x6969:  /* nfs */
2120         case 0x517B:  /* smbfs */
2121         case 0x564c:  /* ncpfs */
2122             info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2123             info->Characteristics |= FILE_REMOTE_DEVICE;
2124             break;
2125         case 0x01021994:  /* tmpfs */
2126         case 0x28cd3d45:  /* cramfs */
2127         case 0x1373:      /* devfs */
2128         case 0x9fa0:      /* procfs */
2129             info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2130             break;
2131         default:
2132             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2133             break;
2134         }
2135 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
2136         struct statfs stfs;
2137
2138         if (fstatfs( fd, &stfs ) < 0)
2139             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2140         else
2141             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2142 #elif defined(__NetBSD__)
2143         struct statvfs stfs;
2144
2145         if (fstatvfs( fd, &stfs) < 0)
2146             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2147         else
2148             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2149 #elif defined(sun)
2150         /* Use dkio to work out device types */
2151         {
2152 # include <sys/dkio.h>
2153 # include <sys/vtoc.h>
2154             struct dk_cinfo dkinf;
2155             int retval = ioctl(fd, DKIOCINFO, &dkinf);
2156             if(retval==-1){
2157                 WARN("Unable to get disk device type information - assuming a disk like device\n");
2158                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2159             }
2160             switch (dkinf.dki_ctype)
2161             {
2162             case DKC_CDROM:
2163                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2164                 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2165                 break;
2166             case DKC_NCRFLOPPY:
2167             case DKC_SMSFLOPPY:
2168             case DKC_INTEL82072:
2169             case DKC_INTEL82077:
2170                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2171                 info->Characteristics |= FILE_REMOVABLE_MEDIA;
2172                 break;
2173             case DKC_MD:
2174                 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2175                 break;
2176             default:
2177                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2178             }
2179         }
2180 #else
2181         static int warned;
2182         if (!warned++) FIXME( "device info not properly supported on this platform\n" );
2183         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2184 #endif
2185         info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
2186     }
2187     return STATUS_SUCCESS;
2188 }
2189
2190
2191 /******************************************************************************
2192  *  NtQueryVolumeInformationFile                [NTDLL.@]
2193  *  ZwQueryVolumeInformationFile                [NTDLL.@]
2194  *
2195  * Get volume information for an open file handle.
2196  *
2197  * PARAMS
2198  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2199  *  io          [O] Receives information about the operation on return
2200  *  buffer      [O] Destination for volume information
2201  *  length      [I] Size of FsInformation
2202  *  info_class  [I] Type of volume information to set
2203  *
2204  * RETURNS
2205  *  Success: 0. io and buffer are updated.
2206  *  Failure: An NTSTATUS error code describing the error.
2207  */
2208 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
2209                                               PVOID buffer, ULONG length,
2210                                               FS_INFORMATION_CLASS info_class )
2211 {
2212     int fd, needs_close;
2213     struct stat st;
2214
2215     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2216         return io->u.Status;
2217
2218     io->u.Status = STATUS_NOT_IMPLEMENTED;
2219     io->Information = 0;
2220
2221     switch( info_class )
2222     {
2223     case FileFsVolumeInformation:
2224         FIXME( "%p: volume info not supported\n", handle );
2225         break;
2226     case FileFsLabelInformation:
2227         FIXME( "%p: label info not supported\n", handle );
2228         break;
2229     case FileFsSizeInformation:
2230         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
2231             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2232         else
2233         {
2234             FILE_FS_SIZE_INFORMATION *info = buffer;
2235
2236             if (fstat( fd, &st ) < 0)
2237             {
2238                 io->u.Status = FILE_GetNtStatus();
2239                 break;
2240             }
2241             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2242             {
2243                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
2244             }
2245             else
2246             {
2247                 ULONGLONG bsize;
2248                 /* Linux's fstatvfs is buggy */
2249 #if !defined(linux) || !defined(HAVE_FSTATFS)
2250                 struct statvfs stfs;
2251
2252                 if (fstatvfs( fd, &stfs ) < 0)
2253                 {
2254                     io->u.Status = FILE_GetNtStatus();
2255                     break;
2256                 }
2257                 bsize = stfs.f_frsize;
2258 #else
2259                 struct statfs stfs;
2260                 if (fstatfs( fd, &stfs ) < 0)
2261                 {
2262                     io->u.Status = FILE_GetNtStatus();
2263                     break;
2264                 }
2265                 bsize = stfs.f_bsize;
2266 #endif
2267                 info->BytesPerSector = 512;
2268                 info->SectorsPerAllocationUnit = 8;
2269                 info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (512 * 8);
2270                 info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (512 * 8);
2271                 io->Information = sizeof(*info);
2272                 io->u.Status = STATUS_SUCCESS;
2273             }
2274         }
2275         break;
2276     case FileFsDeviceInformation:
2277         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
2278             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2279         else
2280         {
2281             FILE_FS_DEVICE_INFORMATION *info = buffer;
2282
2283             if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2284                 io->Information = sizeof(*info);
2285         }
2286         break;
2287     case FileFsAttributeInformation:
2288         FIXME( "%p: attribute info not supported\n", handle );
2289         break;
2290     case FileFsControlInformation:
2291         FIXME( "%p: control info not supported\n", handle );
2292         break;
2293     case FileFsFullSizeInformation:
2294         FIXME( "%p: full size info not supported\n", handle );
2295         break;
2296     case FileFsObjectIdInformation:
2297         FIXME( "%p: object id info not supported\n", handle );
2298         break;
2299     case FileFsMaximumInformation:
2300         FIXME( "%p: maximum info not supported\n", handle );
2301         break;
2302     default:
2303         io->u.Status = STATUS_INVALID_PARAMETER;
2304         break;
2305     }
2306     if (needs_close) close( fd );
2307     return io->u.Status;
2308 }
2309
2310
2311 /******************************************************************
2312  *              NtQueryEaFile  (NTDLL.@)
2313  *
2314  * Read extended attributes from NTFS files.
2315  *
2316  * PARAMS
2317  *  hFile         [I] File handle, must be opened with FILE_READ_EA access
2318  *  iosb          [O] Receives information about the operation on return
2319  *  buffer        [O] Output buffer
2320  *  length        [I] Length of output buffer
2321  *  single_entry  [I] Only read and return one entry
2322  *  ea_list       [I] Optional list with names of EAs to return
2323  *  ea_list_len   [I] Length of ea_list in bytes
2324  *  ea_index      [I] Optional pointer to 1-based index of attribute to return
2325  *  restart       [I] restart EA scan
2326  *
2327  * RETURNS
2328  *  Success: 0. Atrributes read into buffer
2329  *  Failure: An NTSTATUS error code describing the error.
2330  */
2331 NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
2332                                BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
2333                                PULONG ea_index, BOOLEAN restart )
2334 {
2335     FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
2336             hFile, iosb, buffer, length, single_entry, ea_list,
2337             ea_list_len, ea_index, restart);
2338     return STATUS_ACCESS_DENIED;
2339 }
2340
2341
2342 /******************************************************************
2343  *              NtSetEaFile  (NTDLL.@)
2344  *
2345  * Update extended attributes for NTFS files.
2346  *
2347  * PARAMS
2348  *  hFile         [I] File handle, must be opened with FILE_READ_EA access
2349  *  iosb          [O] Receives information about the operation on return
2350  *  buffer        [I] Buffer with EA information
2351  *  length        [I] Length of buffer
2352  *
2353  * RETURNS
2354  *  Success: 0. Attributes are updated
2355  *  Failure: An NTSTATUS error code describing the error.
2356  */
2357 NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
2358 {
2359     FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
2360     return STATUS_ACCESS_DENIED;
2361 }
2362
2363
2364 /******************************************************************
2365  *              NtFlushBuffersFile  (NTDLL.@)
2366  *
2367  * Flush any buffered data on an open file handle.
2368  *
2369  * PARAMS
2370  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2371  *  IoStatusBlock      [O] Receives information about the operation on return
2372  *
2373  * RETURNS
2374  *  Success: 0. IoStatusBlock is updated.
2375  *  Failure: An NTSTATUS error code describing the error.
2376  */
2377 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
2378 {
2379     NTSTATUS ret;
2380     HANDLE hEvent = NULL;
2381
2382     SERVER_START_REQ( flush_file )
2383     {
2384         req->handle = hFile;
2385         ret = wine_server_call( req );
2386         hEvent = reply->event;
2387     }
2388     SERVER_END_REQ;
2389     if (!ret && hEvent)
2390     {
2391         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
2392         NtClose( hEvent );
2393     }
2394     return ret;
2395 }
2396
2397 /******************************************************************
2398  *              NtLockFile       (NTDLL.@)
2399  *
2400  *
2401  */
2402 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
2403                             PIO_APC_ROUTINE apc, void* apc_user,
2404                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2405                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
2406                             BOOLEAN exclusive )
2407 {
2408     NTSTATUS    ret;
2409     HANDLE      handle;
2410     BOOLEAN     async;
2411
2412     if (apc || io_status || key)
2413     {
2414         FIXME("Unimplemented yet parameter\n");
2415         return STATUS_NOT_IMPLEMENTED;
2416     }
2417
2418     if (apc_user) FIXME("I/O completion on lock not implemented yet\n");
2419
2420     for (;;)
2421     {
2422         SERVER_START_REQ( lock_file )
2423         {
2424             req->handle      = hFile;
2425             req->offset      = offset->QuadPart;
2426             req->count       = count->QuadPart;
2427             req->shared      = !exclusive;
2428             req->wait        = !dont_wait;
2429             ret = wine_server_call( req );
2430             handle = reply->handle;
2431             async  = reply->overlapped;
2432         }
2433         SERVER_END_REQ;
2434         if (ret != STATUS_PENDING)
2435         {
2436             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
2437             return ret;
2438         }
2439
2440         if (async)
2441         {
2442             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
2443             if (handle) NtClose( handle );
2444             return STATUS_PENDING;
2445         }
2446         if (handle)
2447         {
2448             NtWaitForSingleObject( handle, FALSE, NULL );
2449             NtClose( handle );
2450         }
2451         else
2452         {
2453             LARGE_INTEGER time;
2454     
2455             /* Unix lock conflict, sleep a bit and retry */
2456             time.QuadPart = 100 * (ULONGLONG)10000;
2457             time.QuadPart = -time.QuadPart;
2458             NtDelayExecution( FALSE, &time );
2459         }
2460     }
2461 }
2462
2463
2464 /******************************************************************
2465  *              NtUnlockFile    (NTDLL.@)
2466  *
2467  *
2468  */
2469 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
2470                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
2471                               PULONG key )
2472 {
2473     NTSTATUS status;
2474
2475     TRACE( "%p %x%08x %x%08x\n",
2476            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2477
2478     if (io_status || key)
2479     {
2480         FIXME("Unimplemented yet parameter\n");
2481         return STATUS_NOT_IMPLEMENTED;
2482     }
2483
2484     SERVER_START_REQ( unlock_file )
2485     {
2486         req->handle = hFile;
2487         req->offset = offset->QuadPart;
2488         req->count  = count->QuadPart;
2489         status = wine_server_call( req );
2490     }
2491     SERVER_END_REQ;
2492     return status;
2493 }
2494
2495 /******************************************************************
2496  *              NtCreateNamedPipeFile    (NTDLL.@)
2497  *
2498  *
2499  */
2500 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2501                                        POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2502                                        ULONG sharing, ULONG dispo, ULONG options,
2503                                        ULONG pipe_type, ULONG read_mode, 
2504                                        ULONG completion_mode, ULONG max_inst,
2505                                        ULONG inbound_quota, ULONG outbound_quota,
2506                                        PLARGE_INTEGER timeout)
2507 {
2508     NTSTATUS    status;
2509
2510     TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2511           handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2512           options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
2513           outbound_quota, timeout);
2514
2515     /* assume we only get relative timeout */
2516     if (timeout->QuadPart > 0)
2517         FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
2518
2519     SERVER_START_REQ( create_named_pipe )
2520     {
2521         req->access  = access;
2522         req->attributes = attr->Attributes;
2523         req->rootdir = attr->RootDirectory;
2524         req->options = options;
2525         req->flags = 
2526             (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
2527             (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
2528             (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
2529         req->maxinstances = max_inst;
2530         req->outsize = outbound_quota;
2531         req->insize  = inbound_quota;
2532         req->timeout = timeout->QuadPart;
2533         wine_server_add_data( req, attr->ObjectName->Buffer,
2534                               attr->ObjectName->Length );
2535         status = wine_server_call( req );
2536         if (!status) *handle = reply->handle;
2537     }
2538     SERVER_END_REQ;
2539     return status;
2540 }
2541
2542 /******************************************************************
2543  *              NtDeleteFile    (NTDLL.@)
2544  *
2545  *
2546  */
2547 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
2548 {
2549     NTSTATUS status;
2550     HANDLE hFile;
2551     IO_STATUS_BLOCK io;
2552
2553     TRACE("%p\n", ObjectAttributes);
2554     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
2555                            ObjectAttributes, &io, NULL, 0,
2556                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
2557                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
2558     if (status == STATUS_SUCCESS) status = NtClose(hFile);
2559     return status;
2560 }
2561
2562 /******************************************************************
2563  *              NtCancelIoFile    (NTDLL.@)
2564  *
2565  *
2566  */
2567 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2568 {
2569     LARGE_INTEGER timeout;
2570
2571     TRACE("%p %p\n", hFile, io_status );
2572
2573     SERVER_START_REQ( cancel_async )
2574     {
2575         req->handle = hFile;
2576         wine_server_call( req );
2577     }
2578     SERVER_END_REQ;
2579     /* Let some APC be run, so that we can run the remaining APCs on hFile
2580      * either the cancelation of the pending one, but also the execution
2581      * of the queued APC, but not yet run. This is needed to ensure proper
2582      * clean-up of allocated data.
2583      */
2584     timeout.u.LowPart = timeout.u.HighPart = 0;
2585     return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2586 }
2587
2588 /******************************************************************************
2589  *  NtCreateMailslotFile        [NTDLL.@]
2590  *  ZwCreateMailslotFile        [NTDLL.@]
2591  *
2592  * PARAMS
2593  *  pHandle          [O] pointer to receive the handle created
2594  *  DesiredAccess    [I] access mode (read, write, etc)
2595  *  ObjectAttributes [I] fully qualified NT path of the mailslot
2596  *  IoStatusBlock    [O] receives completion status and other info
2597  *  CreateOptions    [I]
2598  *  MailslotQuota    [I]
2599  *  MaxMessageSize   [I]
2600  *  TimeOut          [I]
2601  *
2602  * RETURNS
2603  *  An NT status code
2604  */
2605 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
2606      POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
2607      ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
2608      PLARGE_INTEGER TimeOut)
2609 {
2610     LARGE_INTEGER timeout;
2611     NTSTATUS ret;
2612
2613     TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2614               pHandle, DesiredAccess, attr, IoStatusBlock,
2615               CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
2616
2617     if (!pHandle) return STATUS_ACCESS_VIOLATION;
2618     if (!attr) return STATUS_INVALID_PARAMETER;
2619     if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2620
2621     /*
2622      *  For a NULL TimeOut pointer set the default timeout value
2623      */
2624     if  (!TimeOut)
2625         timeout.QuadPart = -1;
2626     else
2627         timeout.QuadPart = TimeOut->QuadPart;
2628
2629     SERVER_START_REQ( create_mailslot )
2630     {
2631         req->access = DesiredAccess;
2632         req->attributes = attr->Attributes;
2633         req->rootdir = attr->RootDirectory;
2634         req->max_msgsize = MaxMessageSize;
2635         req->read_timeout = timeout.QuadPart;
2636         wine_server_add_data( req, attr->ObjectName->Buffer,
2637                               attr->ObjectName->Length );
2638         ret = wine_server_call( req );
2639         if( ret == STATUS_SUCCESS )
2640             *pHandle = reply->handle;
2641     }
2642     SERVER_END_REQ;
2643  
2644     return ret;
2645 }