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