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