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