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