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