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