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