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