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