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