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