server: Add an async_data_t structure to store parameters for async I/O requests.
[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->async.callback = apc;
322         req->async.iosb     = iosb;
323         req->async.arg      = 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->async.callback = pipe_completion_wait;
987                 req->async.iosb     = io;
988                 req->async.arg      = event ? event : internal_event;
989                 io->u.Status = wine_server_call(req);
990             }
991             SERVER_END_REQ;
992
993             if(io->u.Status == STATUS_SUCCESS)
994             {
995                 if(event) io->u.Status = STATUS_PENDING;
996                 else
997                 {
998                     do
999                         io->u.Status = NtWaitForSingleObject(internal_event, TRUE, NULL);
1000                     while(io->u.Status == STATUS_USER_APC);
1001                 }
1002             }
1003             if (internal_event) NtClose(internal_event);
1004         }
1005         break;
1006
1007     case FSCTL_PIPE_WAIT:
1008         {
1009             HANDLE internal_event = 0;
1010             FILE_PIPE_WAIT_FOR_BUFFER *buff = in_buffer;
1011
1012             if(!event)
1013             {
1014                 io->u.Status = NtCreateEvent(&internal_event, EVENT_ALL_ACCESS, NULL, FALSE, FALSE);
1015                 if (io->u.Status != STATUS_SUCCESS) return io->u.Status;
1016             }
1017             SERVER_START_REQ(wait_named_pipe)
1018             {
1019                 req->handle = handle;
1020                 req->timeout = buff->TimeoutSpecified ? buff->Timeout.QuadPart / -10000L
1021                                : NMPWAIT_USE_DEFAULT_WAIT;
1022                 req->async.callback = pipe_completion_wait;
1023                 req->async.iosb     = io;
1024                 req->async.arg      = event ? event : internal_event;
1025                 wine_server_add_data( req, buff->Name, buff->NameLength );
1026                 io->u.Status = wine_server_call( req );
1027             }
1028             SERVER_END_REQ;
1029
1030             if(io->u.Status == STATUS_SUCCESS)
1031             {
1032                 if(event)
1033                     io->u.Status = STATUS_PENDING;
1034                 else
1035                 {
1036                     do
1037                         io->u.Status = NtWaitForSingleObject(internal_event, TRUE, NULL);
1038                     while(io->u.Status == STATUS_USER_APC);
1039                 }
1040             }
1041             if (internal_event) NtClose(internal_event);
1042         }
1043         break;
1044
1045     case FSCTL_PIPE_PEEK:
1046         {
1047             FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1048             int avail = 0, fd, needs_close, flags;
1049
1050             if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1051             {
1052                 io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1053                 break;
1054             }
1055
1056             if ((io->u.Status = server_get_unix_fd( handle, FILE_READ_DATA, &fd,
1057                                                     &needs_close, NULL, &flags )))
1058                 break;
1059
1060             if (flags & FD_FLAG_RECV_SHUTDOWN)
1061             {
1062                 if (needs_close) close( fd );
1063                 io->u.Status = STATUS_PIPE_DISCONNECTED;
1064                 break;
1065             }
1066
1067 #ifdef FIONREAD
1068             if (ioctl( fd, FIONREAD, &avail ) != 0)
1069             {
1070                 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1071                 if (needs_close) close( fd );
1072                 io->u.Status = FILE_GetNtStatus();
1073                 break;
1074             }
1075 #endif
1076             if (!avail)  /* check for closed pipe */
1077             {
1078                 struct pollfd pollfd;
1079                 int ret;
1080
1081                 pollfd.fd = fd;
1082                 pollfd.events = POLLIN;
1083                 pollfd.revents = 0;
1084                 ret = poll( &pollfd, 1, 0 );
1085                 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1086                 {
1087                     if (needs_close) close( fd );
1088                     io->u.Status = STATUS_PIPE_BROKEN;
1089                     break;
1090                 }
1091             }
1092             buffer->NamedPipeState    = 0;  /* FIXME */
1093             buffer->ReadDataAvailable = avail;
1094             buffer->NumberOfMessages  = 0;  /* FIXME */
1095             buffer->MessageLength     = 0;  /* FIXME */
1096             io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1097             io->u.Status = STATUS_SUCCESS;
1098             if (avail)
1099             {
1100                 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1101                 if (data_size)
1102                 {
1103                     int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1104                     if (res >= 0) io->Information += res;
1105                 }
1106             }
1107             if (needs_close) close( fd );
1108         }
1109         break;
1110
1111     case FSCTL_PIPE_DISCONNECT:
1112         SERVER_START_REQ(disconnect_named_pipe)
1113         {
1114             req->handle = handle;
1115             io->u.Status = wine_server_call(req);
1116             if (!io->u.Status)
1117             {
1118                 int fd = server_remove_fd_from_cache( handle );
1119                 if (fd != -1) close( fd );
1120             }
1121         }
1122         SERVER_END_REQ;
1123         break;
1124
1125     case FSCTL_LOCK_VOLUME:
1126     case FSCTL_UNLOCK_VOLUME:
1127         FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1128               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1129         io->u.Status = STATUS_SUCCESS;
1130         break;
1131
1132     default:
1133         FIXME("Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1134               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1135         io->u.Status = STATUS_NOT_SUPPORTED;
1136         break;
1137     }
1138     return io->u.Status;
1139 }
1140
1141 /******************************************************************************
1142  *  NtSetVolumeInformationFile          [NTDLL.@]
1143  *  ZwSetVolumeInformationFile          [NTDLL.@]
1144  *
1145  * Set volume information for an open file handle.
1146  *
1147  * PARAMS
1148  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1149  *  IoStatusBlock      [O] Receives information about the operation on return
1150  *  FsInformation      [I] Source for volume information
1151  *  Length             [I] Size of FsInformation
1152  *  FsInformationClass [I] Type of volume information to set
1153  *
1154  * RETURNS
1155  *  Success: 0. IoStatusBlock is updated.
1156  *  Failure: An NTSTATUS error code describing the error.
1157  */
1158 NTSTATUS WINAPI NtSetVolumeInformationFile(
1159         IN HANDLE FileHandle,
1160         PIO_STATUS_BLOCK IoStatusBlock,
1161         PVOID FsInformation,
1162         ULONG Length,
1163         FS_INFORMATION_CLASS FsInformationClass)
1164 {
1165         FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1166         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1167         return 0;
1168 }
1169
1170 /******************************************************************************
1171  *  NtQueryInformationFile              [NTDLL.@]
1172  *  ZwQueryInformationFile              [NTDLL.@]
1173  *
1174  * Get information about an open file handle.
1175  *
1176  * PARAMS
1177  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1178  *  io       [O] Receives information about the operation on return
1179  *  ptr      [O] Destination for file information
1180  *  len      [I] Size of FileInformation
1181  *  class    [I] Type of file information to get
1182  *
1183  * RETURNS
1184  *  Success: 0. IoStatusBlock and FileInformation are updated.
1185  *  Failure: An NTSTATUS error code describing the error.
1186  */
1187 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
1188                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
1189 {
1190     static const size_t info_sizes[] =
1191     {
1192         0,
1193         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
1194         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
1195         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
1196         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
1197         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
1198         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
1199         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
1200         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
1201         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
1202         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
1203         0,                                             /* FileLinkInformation */
1204         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
1205         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
1206         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
1207         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
1208         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
1209         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
1210         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
1211         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
1212         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
1213         0,                                             /* FileAlternateNameInformation */
1214         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
1215         0,                                             /* FilePipeInformation */
1216         sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1217         0,                                             /* FilePipeRemoteInformation */
1218         sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1219         0,                                             /* FileMailslotSetInformation */
1220         0,                                             /* FileCompressionInformation */
1221         0,                                             /* FileObjectIdInformation */
1222         0,                                             /* FileCompletionInformation */
1223         0,                                             /* FileMoveClusterInformation */
1224         0,                                             /* FileQuotaInformation */
1225         0,                                             /* FileReparsePointInformation */
1226         0,                                             /* FileNetworkOpenInformation */
1227         0,                                             /* FileAttributeTagInformation */
1228         0                                              /* FileTrackingInformation */
1229     };
1230
1231     struct stat st;
1232     int fd, needs_close = FALSE;
1233
1234     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1235
1236     io->Information = 0;
1237
1238     if (class <= 0 || class >= FileMaximumInformation)
1239         return io->u.Status = STATUS_INVALID_INFO_CLASS;
1240     if (!info_sizes[class])
1241     {
1242         FIXME("Unsupported class (%d)\n", class);
1243         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1244     }
1245     if (len < info_sizes[class])
1246         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1247
1248     if (class != FilePipeLocalInformation)
1249     {
1250         if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1251             return io->u.Status;
1252     }
1253
1254     switch (class)
1255     {
1256     case FileBasicInformation:
1257         {
1258             FILE_BASIC_INFORMATION *info = ptr;
1259
1260             if (fstat( fd, &st ) == -1)
1261                 io->u.Status = FILE_GetNtStatus();
1262             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1263                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1264             else
1265             {
1266                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1267                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1268                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1269                     info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1270                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
1271                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
1272                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
1273                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
1274             }
1275         }
1276         break;
1277     case FileStandardInformation:
1278         {
1279             FILE_STANDARD_INFORMATION *info = ptr;
1280
1281             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1282             else
1283             {
1284                 if ((info->Directory = S_ISDIR(st.st_mode)))
1285                 {
1286                     info->AllocationSize.QuadPart = 0;
1287                     info->EndOfFile.QuadPart      = 0;
1288                     info->NumberOfLinks           = 1;
1289                     info->DeletePending           = FALSE;
1290                 }
1291                 else
1292                 {
1293                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1294                     info->EndOfFile.QuadPart      = st.st_size;
1295                     info->NumberOfLinks           = st.st_nlink;
1296                     info->DeletePending           = FALSE; /* FIXME */
1297                 }
1298             }
1299         }
1300         break;
1301     case FilePositionInformation:
1302         {
1303             FILE_POSITION_INFORMATION *info = ptr;
1304             off_t res = lseek( fd, 0, SEEK_CUR );
1305             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
1306             else info->CurrentByteOffset.QuadPart = res;
1307         }
1308         break;
1309     case FileInternalInformation:
1310         {
1311             FILE_INTERNAL_INFORMATION *info = ptr;
1312
1313             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1314             else info->IndexNumber.QuadPart = st.st_ino;
1315         }
1316         break;
1317     case FileEaInformation:
1318         {
1319             FILE_EA_INFORMATION *info = ptr;
1320             info->EaSize = 0;
1321         }
1322         break;
1323     case FileEndOfFileInformation:
1324         {
1325             FILE_END_OF_FILE_INFORMATION *info = ptr;
1326
1327             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1328             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
1329         }
1330         break;
1331     case FileAllInformation:
1332         {
1333             FILE_ALL_INFORMATION *info = ptr;
1334
1335             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1336             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1337                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1338             else
1339             {
1340                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
1341                 {
1342                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1343                     info->StandardInformation.AllocationSize.QuadPart = 0;
1344                     info->StandardInformation.EndOfFile.QuadPart      = 0;
1345                     info->StandardInformation.NumberOfLinks           = 1;
1346                     info->StandardInformation.DeletePending           = FALSE;
1347                 }
1348                 else
1349                 {
1350                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1351                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1352                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1353                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1354                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1355                 }
1356                 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1357                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1358                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1359                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1360                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1361                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1362                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1363                 info->EaInformation.EaSize = 0;
1364                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1365                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1366                 info->ModeInformation.Mode = 0;  /* FIXME */
1367                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1368                 info->NameInformation.FileNameLength = 0;
1369                 io->Information = sizeof(*info) - sizeof(WCHAR);
1370             }
1371         }
1372         break;
1373     case FileMailslotQueryInformation:
1374         {
1375             FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
1376
1377             SERVER_START_REQ( set_mailslot_info )
1378             {
1379                 req->handle = hFile;
1380                 req->flags = 0;
1381                 io->u.Status = wine_server_call( req );
1382                 if( io->u.Status == STATUS_SUCCESS )
1383                 {
1384                     info->MaximumMessageSize = reply->max_msgsize;
1385                     info->MailslotQuota = 0;
1386                     info->NextMessageSize = 0;
1387                     info->MessagesAvailable = 0;
1388                     info->ReadTimeout.QuadPart = reply->read_timeout * -10000;
1389                 }
1390             }
1391             SERVER_END_REQ;
1392             if (!io->u.Status)
1393             {
1394                 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
1395                 char *tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size );
1396                 if (tmpbuf)
1397                 {
1398                     int fd, needs_close;
1399                     if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
1400                     {
1401                         int res = recv( fd, tmpbuf, size, MSG_PEEK );
1402                         info->MessagesAvailable = (res > 0);
1403                         info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
1404                         if (needs_close) close( fd );
1405                     }
1406                     RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
1407                 }
1408             }
1409         }
1410         break;
1411     case FilePipeLocalInformation:
1412         {
1413             FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
1414
1415             SERVER_START_REQ( get_named_pipe_info )
1416             {
1417                 req->handle = hFile;
1418                 if (!(io->u.Status = wine_server_call( req )))
1419                 {
1420                     pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
1421                         FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
1422                     pli->NamedPipeConfiguration = 0; /* FIXME */
1423                     pli->MaximumInstances = reply->maxinstances;
1424                     pli->CurrentInstances = reply->instances;
1425                     pli->InboundQuota = reply->insize;
1426                     pli->ReadDataAvailable = 0; /* FIXME */
1427                     pli->OutboundQuota = reply->outsize;
1428                     pli->WriteQuotaAvailable = 0; /* FIXME */
1429                     pli->NamedPipeState = 0; /* FIXME */
1430                     pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
1431                         FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
1432                 }
1433             }
1434             SERVER_END_REQ;
1435         }
1436         break;
1437     default:
1438         FIXME("Unsupported class (%d)\n", class);
1439         io->u.Status = STATUS_NOT_IMPLEMENTED;
1440         break;
1441     }
1442     if (needs_close) close( fd );
1443     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1444     return io->u.Status;
1445 }
1446
1447 /******************************************************************************
1448  *  NtSetInformationFile                [NTDLL.@]
1449  *  ZwSetInformationFile                [NTDLL.@]
1450  *
1451  * Set information about an open file handle.
1452  *
1453  * PARAMS
1454  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1455  *  io      [O] Receives information about the operation on return
1456  *  ptr     [I] Source for file information
1457  *  len     [I] Size of FileInformation
1458  *  class   [I] Type of file information to set
1459  *
1460  * RETURNS
1461  *  Success: 0. io is updated.
1462  *  Failure: An NTSTATUS error code describing the error.
1463  */
1464 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1465                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1466 {
1467     int fd, needs_close;
1468
1469     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
1470
1471     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
1472         return io->u.Status;
1473
1474     io->u.Status = STATUS_SUCCESS;
1475     switch (class)
1476     {
1477     case FileBasicInformation:
1478         if (len >= sizeof(FILE_BASIC_INFORMATION))
1479         {
1480             struct stat st;
1481             const FILE_BASIC_INFORMATION *info = ptr;
1482
1483             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1484             {
1485                 ULONGLONG sec, nsec;
1486                 struct timeval tv[2];
1487
1488                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1489                 {
1490
1491                     tv[0].tv_sec = tv[0].tv_usec = 0;
1492                     tv[1].tv_sec = tv[1].tv_usec = 0;
1493                     if (!fstat( fd, &st ))
1494                     {
1495                         tv[0].tv_sec = st.st_atime;
1496                         tv[1].tv_sec = st.st_mtime;
1497                     }
1498                 }
1499                 if (info->LastAccessTime.QuadPart)
1500                 {
1501                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1502                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1503                     tv[0].tv_usec = (UINT)nsec / 10;
1504                 }
1505                 if (info->LastWriteTime.QuadPart)
1506                 {
1507                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1508                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1509                     tv[1].tv_usec = (UINT)nsec / 10;
1510                 }
1511                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1512             }
1513
1514             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1515             {
1516                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1517                 else
1518                 {
1519                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1520                     {
1521                         if (S_ISDIR( st.st_mode))
1522                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1523                         else
1524                             st.st_mode &= ~0222; /* clear write permission bits */
1525                     }
1526                     else
1527                     {
1528                         /* add write permission only where we already have read permission */
1529                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1530                     }
1531                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1532                 }
1533             }
1534         }
1535         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1536         break;
1537
1538     case FilePositionInformation:
1539         if (len >= sizeof(FILE_POSITION_INFORMATION))
1540         {
1541             const FILE_POSITION_INFORMATION *info = ptr;
1542
1543             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1544                 io->u.Status = FILE_GetNtStatus();
1545         }
1546         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1547         break;
1548
1549     case FileEndOfFileInformation:
1550         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1551         {
1552             struct stat st;
1553             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1554
1555             /* first try normal truncate */
1556             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1557
1558             /* now check for the need to extend the file */
1559             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1560             {
1561                 static const char zero;
1562
1563                 /* extend the file one byte beyond the requested size and then truncate it */
1564                 /* this should work around ftruncate implementations that can't extend files */
1565                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1566                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1567             }
1568             io->u.Status = FILE_GetNtStatus();
1569         }
1570         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1571         break;
1572
1573     case FileMailslotSetInformation:
1574         {
1575             FILE_MAILSLOT_SET_INFORMATION *info = ptr;
1576
1577             SERVER_START_REQ( set_mailslot_info )
1578             {
1579                 req->handle = handle;
1580                 req->flags = MAILSLOT_SET_READ_TIMEOUT;
1581                 req->read_timeout = info->ReadTimeout.QuadPart / -10000;
1582                 io->u.Status = wine_server_call( req );
1583             }
1584             SERVER_END_REQ;
1585         }
1586         break;
1587
1588     default:
1589         FIXME("Unsupported class (%d)\n", class);
1590         io->u.Status = STATUS_NOT_IMPLEMENTED;
1591         break;
1592     }
1593     if (needs_close) close( fd );
1594     io->Information = 0;
1595     return io->u.Status;
1596 }
1597
1598
1599 /******************************************************************************
1600  *              NtQueryFullAttributesFile   (NTDLL.@)
1601  */
1602 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1603                                            FILE_NETWORK_OPEN_INFORMATION *info )
1604 {
1605     ANSI_STRING unix_name;
1606     NTSTATUS status;
1607
1608     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1609                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1610     {
1611         struct stat st;
1612
1613         if (stat( unix_name.Buffer, &st ) == -1)
1614             status = FILE_GetNtStatus();
1615         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1616             status = STATUS_INVALID_INFO_CLASS;
1617         else
1618         {
1619             if (S_ISDIR(st.st_mode))
1620             {
1621                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1622                 info->AllocationSize.QuadPart = 0;
1623                 info->EndOfFile.QuadPart      = 0;
1624             }
1625             else
1626             {
1627                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1628                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1629                 info->EndOfFile.QuadPart      = st.st_size;
1630             }
1631             if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1632                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1633             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1634             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1635             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1636             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1637             if (DIR_is_hidden_file( attr->ObjectName ))
1638                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1639         }
1640         RtlFreeAnsiString( &unix_name );
1641     }
1642     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
1643     return status;
1644 }
1645
1646
1647 /******************************************************************************
1648  *              NtQueryAttributesFile   (NTDLL.@)
1649  *              ZwQueryAttributesFile   (NTDLL.@)
1650  */
1651 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1652 {
1653     FILE_NETWORK_OPEN_INFORMATION full_info;
1654     NTSTATUS status;
1655
1656     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
1657     {
1658         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
1659         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
1660         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
1661         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
1662         info->FileAttributes          = full_info.FileAttributes;
1663     }
1664     return status;
1665 }
1666
1667
1668 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__APPLE__)
1669 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
1670 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
1671                                             size_t fstypesize, unsigned int flags )
1672 {
1673     if (!strncmp("cd9660", fstypename, fstypesize) ||
1674         !strncmp("udf", fstypename, fstypesize))
1675     {
1676         info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1677         /* Don't assume read-only, let the mount options set it below */
1678         info->Characteristics |= FILE_REMOVABLE_MEDIA;
1679     }
1680     else if (!strncmp("nfs", fstypename, fstypesize) ||
1681              !strncmp("nwfs", fstypename, fstypesize) ||
1682              !strncmp("smbfs", fstypename, fstypesize) ||
1683              !strncmp("afpfs", fstypename, fstypesize))
1684     {
1685         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1686         info->Characteristics |= FILE_REMOTE_DEVICE;
1687     }
1688     else if (!strncmp("procfs", fstypename, fstypesize))
1689         info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1690     else
1691         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1692
1693     if (flags & MNT_RDONLY)
1694         info->Characteristics |= FILE_READ_ONLY_DEVICE;
1695
1696     if (!(flags & MNT_LOCAL))
1697     {
1698         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1699         info->Characteristics |= FILE_REMOTE_DEVICE;
1700     }
1701 }
1702 #endif
1703
1704 /******************************************************************************
1705  *              get_device_info
1706  *
1707  * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
1708  */
1709 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
1710 {
1711     struct stat st;
1712
1713     info->Characteristics = 0;
1714     if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
1715     if (S_ISCHR( st.st_mode ))
1716     {
1717         info->DeviceType = FILE_DEVICE_UNKNOWN;
1718 #ifdef linux
1719         switch(major(st.st_rdev))
1720         {
1721         case MEM_MAJOR:
1722             info->DeviceType = FILE_DEVICE_NULL;
1723             break;
1724         case TTY_MAJOR:
1725             info->DeviceType = FILE_DEVICE_SERIAL_PORT;
1726             break;
1727         case LP_MAJOR:
1728             info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
1729             break;
1730         case SCSI_TAPE_MAJOR:
1731             info->DeviceType = FILE_DEVICE_TAPE;
1732             break;
1733         }
1734 #endif
1735     }
1736     else if (S_ISBLK( st.st_mode ))
1737     {
1738         info->DeviceType = FILE_DEVICE_DISK;
1739     }
1740     else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
1741     {
1742         info->DeviceType = FILE_DEVICE_NAMED_PIPE;
1743     }
1744     else  /* regular file or directory */
1745     {
1746 #if defined(linux) && defined(HAVE_FSTATFS)
1747         struct statfs stfs;
1748
1749         /* check for floppy disk */
1750         if (major(st.st_dev) == FLOPPY_MAJOR)
1751             info->Characteristics |= FILE_REMOVABLE_MEDIA;
1752
1753         if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
1754         switch (stfs.f_type)
1755         {
1756         case 0x9660:      /* iso9660 */
1757         case 0x9fa1:      /* supermount */
1758         case 0x15013346:  /* udf */
1759             info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1760             info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1761             break;
1762         case 0x6969:  /* nfs */
1763         case 0x517B:  /* smbfs */
1764         case 0x564c:  /* ncpfs */
1765             info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1766             info->Characteristics |= FILE_REMOTE_DEVICE;
1767             break;
1768         case 0x01021994:  /* tmpfs */
1769         case 0x28cd3d45:  /* cramfs */
1770         case 0x1373:      /* devfs */
1771         case 0x9fa0:      /* procfs */
1772             info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1773             break;
1774         default:
1775             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1776             break;
1777         }
1778 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__APPLE__)
1779         struct statfs stfs;
1780
1781         if (fstatfs( fd, &stfs ) < 0)
1782             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1783         else
1784             get_device_info_fstatfs( info, stfs.f_fstypename,
1785                                      sizeof(stfs.f_fstypename), stfs.f_flags );
1786 #elif defined(__NetBSD__)
1787         struct statvfs stfs;
1788
1789         if (fstatvfs( fd, &stfs) < 0)
1790             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1791         else
1792             get_device_info_fstatfs( info, stfs.f_fstypename,
1793                                      sizeof(stfs.f_fstypename), stfs.f_flag );
1794 #elif defined(sun)
1795         /* Use dkio to work out device types */
1796         {
1797 # include <sys/dkio.h>
1798 # include <sys/vtoc.h>
1799             struct dk_cinfo dkinf;
1800             int retval = ioctl(fd, DKIOCINFO, &dkinf);
1801             if(retval==-1){
1802                 WARN("Unable to get disk device type information - assuming a disk like device\n");
1803                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1804             }
1805             switch (dkinf.dki_ctype)
1806             {
1807             case DKC_CDROM:
1808                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1809                 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1810                 break;
1811             case DKC_NCRFLOPPY:
1812             case DKC_SMSFLOPPY:
1813             case DKC_INTEL82072:
1814             case DKC_INTEL82077:
1815                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1816                 info->Characteristics |= FILE_REMOVABLE_MEDIA;
1817                 break;
1818             case DKC_MD:
1819                 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1820                 break;
1821             default:
1822                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1823             }
1824         }
1825 #else
1826         static int warned;
1827         if (!warned++) FIXME( "device info not properly supported on this platform\n" );
1828         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1829 #endif
1830         info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
1831     }
1832     return STATUS_SUCCESS;
1833 }
1834
1835
1836 /******************************************************************************
1837  *  NtQueryVolumeInformationFile                [NTDLL.@]
1838  *  ZwQueryVolumeInformationFile                [NTDLL.@]
1839  *
1840  * Get volume information for an open file handle.
1841  *
1842  * PARAMS
1843  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1844  *  io          [O] Receives information about the operation on return
1845  *  buffer      [O] Destination for volume information
1846  *  length      [I] Size of FsInformation
1847  *  info_class  [I] Type of volume information to set
1848  *
1849  * RETURNS
1850  *  Success: 0. io and buffer are updated.
1851  *  Failure: An NTSTATUS error code describing the error.
1852  */
1853 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
1854                                               PVOID buffer, ULONG length,
1855                                               FS_INFORMATION_CLASS info_class )
1856 {
1857     int fd, needs_close;
1858     struct stat st;
1859
1860     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1861         return io->u.Status;
1862
1863     io->u.Status = STATUS_NOT_IMPLEMENTED;
1864     io->Information = 0;
1865
1866     switch( info_class )
1867     {
1868     case FileFsVolumeInformation:
1869         FIXME( "%p: volume info not supported\n", handle );
1870         break;
1871     case FileFsLabelInformation:
1872         FIXME( "%p: label info not supported\n", handle );
1873         break;
1874     case FileFsSizeInformation:
1875         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
1876             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1877         else
1878         {
1879             FILE_FS_SIZE_INFORMATION *info = buffer;
1880
1881             if (fstat( fd, &st ) < 0)
1882             {
1883                 io->u.Status = FILE_GetNtStatus();
1884                 break;
1885             }
1886             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1887             {
1888                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
1889             }
1890             else
1891             {
1892                 /* Linux's fstatvfs is buggy */
1893 #if !defined(linux) || !defined(HAVE_FSTATFS)
1894                 struct statvfs stfs;
1895
1896                 if (fstatvfs( fd, &stfs ) < 0)
1897                 {
1898                     io->u.Status = FILE_GetNtStatus();
1899                     break;
1900                 }
1901                 info->BytesPerSector = stfs.f_frsize;
1902 #else
1903                 struct statfs stfs;
1904                 if (fstatfs( fd, &stfs ) < 0)
1905                 {
1906                     io->u.Status = FILE_GetNtStatus();
1907                     break;
1908                 }
1909                 info->BytesPerSector = stfs.f_bsize;
1910 #endif
1911                 info->TotalAllocationUnits.QuadPart = stfs.f_blocks;
1912                 info->AvailableAllocationUnits.QuadPart = stfs.f_bavail;
1913                 info->SectorsPerAllocationUnit = 1;
1914                 io->Information = sizeof(*info);
1915                 io->u.Status = STATUS_SUCCESS;
1916             }
1917         }
1918         break;
1919     case FileFsDeviceInformation:
1920         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
1921             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1922         else
1923         {
1924             FILE_FS_DEVICE_INFORMATION *info = buffer;
1925
1926             if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
1927                 io->Information = sizeof(*info);
1928         }
1929         break;
1930     case FileFsAttributeInformation:
1931         FIXME( "%p: attribute info not supported\n", handle );
1932         break;
1933     case FileFsControlInformation:
1934         FIXME( "%p: control info not supported\n", handle );
1935         break;
1936     case FileFsFullSizeInformation:
1937         FIXME( "%p: full size info not supported\n", handle );
1938         break;
1939     case FileFsObjectIdInformation:
1940         FIXME( "%p: object id info not supported\n", handle );
1941         break;
1942     case FileFsMaximumInformation:
1943         FIXME( "%p: maximum info not supported\n", handle );
1944         break;
1945     default:
1946         io->u.Status = STATUS_INVALID_PARAMETER;
1947         break;
1948     }
1949     if (needs_close) close( fd );
1950     return io->u.Status;
1951 }
1952
1953
1954 /******************************************************************
1955  *              NtFlushBuffersFile  (NTDLL.@)
1956  *
1957  * Flush any buffered data on an open file handle.
1958  *
1959  * PARAMS
1960  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1961  *  IoStatusBlock      [O] Receives information about the operation on return
1962  *
1963  * RETURNS
1964  *  Success: 0. IoStatusBlock is updated.
1965  *  Failure: An NTSTATUS error code describing the error.
1966  */
1967 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
1968 {
1969     NTSTATUS ret;
1970     HANDLE hEvent = NULL;
1971
1972     SERVER_START_REQ( flush_file )
1973     {
1974         req->handle = hFile;
1975         ret = wine_server_call( req );
1976         hEvent = reply->event;
1977     }
1978     SERVER_END_REQ;
1979     if (!ret && hEvent)
1980     {
1981         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
1982         NtClose( hEvent );
1983     }
1984     return ret;
1985 }
1986
1987 /******************************************************************
1988  *              NtLockFile       (NTDLL.@)
1989  *
1990  *
1991  */
1992 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
1993                             PIO_APC_ROUTINE apc, void* apc_user,
1994                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
1995                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
1996                             BOOLEAN exclusive )
1997 {
1998     NTSTATUS    ret;
1999     HANDLE      handle;
2000     BOOLEAN     async;
2001
2002     if (apc || io_status || key)
2003     {
2004         FIXME("Unimplemented yet parameter\n");
2005         return STATUS_NOT_IMPLEMENTED;
2006     }
2007
2008     for (;;)
2009     {
2010         SERVER_START_REQ( lock_file )
2011         {
2012             req->handle      = hFile;
2013             req->offset_low  = offset->u.LowPart;
2014             req->offset_high = offset->u.HighPart;
2015             req->count_low   = count->u.LowPart;
2016             req->count_high  = count->u.HighPart;
2017             req->shared      = !exclusive;
2018             req->wait        = !dont_wait;
2019             ret = wine_server_call( req );
2020             handle = reply->handle;
2021             async  = reply->overlapped;
2022         }
2023         SERVER_END_REQ;
2024         if (ret != STATUS_PENDING)
2025         {
2026             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
2027             return ret;
2028         }
2029
2030         if (async)
2031         {
2032             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
2033             if (handle) NtClose( handle );
2034             return STATUS_PENDING;
2035         }
2036         if (handle)
2037         {
2038             NtWaitForSingleObject( handle, FALSE, NULL );
2039             NtClose( handle );
2040         }
2041         else
2042         {
2043             LARGE_INTEGER time;
2044     
2045             /* Unix lock conflict, sleep a bit and retry */
2046             time.QuadPart = 100 * (ULONGLONG)10000;
2047             time.QuadPart = -time.QuadPart;
2048             NtDelayExecution( FALSE, &time );
2049         }
2050     }
2051 }
2052
2053
2054 /******************************************************************
2055  *              NtUnlockFile    (NTDLL.@)
2056  *
2057  *
2058  */
2059 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
2060                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
2061                               PULONG key )
2062 {
2063     NTSTATUS status;
2064
2065     TRACE( "%p %x%08x %x%08x\n",
2066            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2067
2068     if (io_status || key)
2069     {
2070         FIXME("Unimplemented yet parameter\n");
2071         return STATUS_NOT_IMPLEMENTED;
2072     }
2073
2074     SERVER_START_REQ( unlock_file )
2075     {
2076         req->handle      = hFile;
2077         req->offset_low  = offset->u.LowPart;
2078         req->offset_high = offset->u.HighPart;
2079         req->count_low   = count->u.LowPart;
2080         req->count_high  = count->u.HighPart;
2081         status = wine_server_call( req );
2082     }
2083     SERVER_END_REQ;
2084     return status;
2085 }
2086
2087 /******************************************************************
2088  *              NtCreateNamedPipeFile    (NTDLL.@)
2089  *
2090  *
2091  */
2092 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2093                                        POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2094                                        ULONG sharing, ULONG dispo, ULONG options,
2095                                        ULONG pipe_type, ULONG read_mode, 
2096                                        ULONG completion_mode, ULONG max_inst,
2097                                        ULONG inbound_quota, ULONG outbound_quota,
2098                                        PLARGE_INTEGER timeout)
2099 {
2100     NTSTATUS    status;
2101     static const WCHAR leadin[] = {'\\','?','?','\\','P','I','P','E','\\'};
2102
2103     TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2104           handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2105           options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
2106           outbound_quota, timeout);
2107
2108     if (attr->ObjectName->Length < sizeof(leadin) ||
2109         strncmpiW( attr->ObjectName->Buffer, 
2110                    leadin, sizeof(leadin)/sizeof(leadin[0]) ))
2111         return STATUS_OBJECT_NAME_INVALID;
2112     /* assume we only get relative timeout, and storable in a DWORD as ms */
2113     if (timeout->QuadPart > 0 || (timeout->QuadPart / -10000) >> 32)
2114         FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
2115
2116     SERVER_START_REQ( create_named_pipe )
2117     {
2118         req->access  = access;
2119         req->attributes = (attr) ? attr->Attributes : 0;
2120         req->rootdir = attr ? attr->RootDirectory : 0;
2121         req->options = options;
2122         req->flags = 
2123             (pipe_type) ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0 |
2124             (read_mode) ? NAMED_PIPE_MESSAGE_STREAM_READ  : 0 |
2125             (completion_mode) ? NAMED_PIPE_NONBLOCKING_MODE  : 0;
2126         req->maxinstances = max_inst;
2127         req->outsize = outbound_quota;
2128         req->insize  = inbound_quota;
2129         req->timeout = timeout->QuadPart / -10000;
2130         wine_server_add_data( req, attr->ObjectName->Buffer,
2131                               attr->ObjectName->Length );
2132         status = wine_server_call( req );
2133         if (!status) *handle = reply->handle;
2134     }
2135     SERVER_END_REQ;
2136     return status;
2137 }
2138
2139 /******************************************************************
2140  *              NtDeleteFile    (NTDLL.@)
2141  *
2142  *
2143  */
2144 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
2145 {
2146     NTSTATUS status;
2147     HANDLE hFile;
2148     IO_STATUS_BLOCK io;
2149
2150     TRACE("%p\n", ObjectAttributes);
2151     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
2152                            ObjectAttributes, &io, NULL, 0,
2153                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
2154                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
2155     if (status == STATUS_SUCCESS) status = NtClose(hFile);
2156     return status;
2157 }
2158
2159 /******************************************************************
2160  *              NtCancelIoFile    (NTDLL.@)
2161  *
2162  *
2163  */
2164 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2165 {
2166     LARGE_INTEGER timeout;
2167
2168     TRACE("%p %p\n", hFile, io_status );
2169
2170     SERVER_START_REQ( cancel_async )
2171     {
2172         req->handle = hFile;
2173         wine_server_call( req );
2174     }
2175     SERVER_END_REQ;
2176     /* Let some APC be run, so that we can run the remaining APCs on hFile
2177      * either the cancelation of the pending one, but also the execution
2178      * of the queued APC, but not yet run. This is needed to ensure proper
2179      * clean-up of allocated data.
2180      */
2181     timeout.u.LowPart = timeout.u.HighPart = 0;
2182     return io_status->u.Status = NtDelayExecution( TRUE, &timeout );
2183 }
2184
2185 /******************************************************************************
2186  *  NtCreateMailslotFile        [NTDLL.@]
2187  *  ZwCreateMailslotFile        [NTDLL.@]
2188  *
2189  * PARAMS
2190  *  pHandle          [O] pointer to receive the handle created
2191  *  DesiredAccess    [I] access mode (read, write, etc)
2192  *  ObjectAttributes [I] fully qualified NT path of the mailslot
2193  *  IoStatusBlock    [O] receives completion status and other info
2194  *  CreateOptions    [I]
2195  *  MailslotQuota    [I]
2196  *  MaxMessageSize   [I]
2197  *  TimeOut          [I]
2198  *
2199  * RETURNS
2200  *  An NT status code
2201  */
2202 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
2203      POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
2204      ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
2205      PLARGE_INTEGER TimeOut)
2206 {
2207     LARGE_INTEGER timeout;
2208     static const WCHAR leadin[] = {
2209         '\\','?','?','\\','M','A','I','L','S','L','O','T','\\'};
2210     NTSTATUS ret;
2211
2212     TRACE("%p %08x %p %p %08x %08x %08x %p\n",
2213               pHandle, DesiredAccess, attr, IoStatusBlock,
2214               CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
2215
2216     if (!pHandle) return STATUS_ACCESS_VIOLATION;
2217
2218     if (!attr) return STATUS_INVALID_PARAMETER;
2219
2220     if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2221
2222     if (attr->ObjectName->Length < sizeof(leadin) ||
2223         strncmpiW( attr->ObjectName->Buffer, 
2224                    leadin, sizeof(leadin)/sizeof(leadin[0]) ))
2225     {
2226         return STATUS_OBJECT_NAME_INVALID;
2227     }
2228
2229     /*
2230      *  For a NULL TimeOut pointer set the default timeout value
2231      */
2232     if  (!TimeOut)
2233         timeout.QuadPart = -1;
2234     else
2235         timeout.QuadPart = TimeOut->QuadPart;
2236
2237     SERVER_START_REQ( create_mailslot )
2238     {
2239         req->access = DesiredAccess;
2240         req->attributes = attr->Attributes;
2241         req->rootdir = attr->RootDirectory;
2242         req->max_msgsize = MaxMessageSize;
2243         req->read_timeout = (timeout.QuadPart <= 0) ? timeout.QuadPart / -10000 : -1;
2244         wine_server_add_data( req, attr->ObjectName->Buffer,
2245                               attr->ObjectName->Length );
2246         ret = wine_server_call( req );
2247         if( ret == STATUS_SUCCESS )
2248             *pHandle = reply->handle;
2249     }
2250     SERVER_END_REQ;
2251  
2252     return ret;
2253 }