Fixed the FIXME in RtlNtStatusToDosError, and implemented
[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 #define NONAMELESSUNION
61 #define NONAMELESSSTRUCT
62 #include "wine/unicode.h"
63 #include "wine/debug.h"
64 #include "wine/server.h"
65 #include "async.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] Undocumented
122  *      ea_length    [I] Undocumented
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     ANSI_STRING unix_name;
135     int created = FALSE;
136
137     TRACE("handle=%p access=%08lx name=%s objattr=%08lx root=%p sec=%p io=%p alloc_size=%p\n"
138           "attr=%08lx sharing=%08lx disp=%ld options=%08lx ea=%p.0x%08lx\n",
139           handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
140           attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
141           attributes, sharing, disposition, options, ea_buffer, ea_length );
142
143     if (attr->RootDirectory)
144     {
145         FIXME( "RootDirectory %p not supported\n", attr->RootDirectory );
146         return STATUS_OBJECT_NAME_NOT_FOUND;
147     }
148     if (alloc_size) FIXME( "alloc_size not supported\n" );
149
150     /* check for named pipe */
151
152     if (attr->ObjectName->Length > sizeof(pipeW) &&
153         !memicmpW( attr->ObjectName->Buffer, pipeW, sizeof(pipeW)/sizeof(WCHAR) ))
154     {
155         SERVER_START_REQ( open_named_pipe )
156         {
157             req->access = access;
158             req->inherit = (attr->Attributes & OBJ_INHERIT) != 0;
159             wine_server_add_data( req, attr->ObjectName->Buffer + 4,
160                                   attr->ObjectName->Length - 4*sizeof(WCHAR) );
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     io->u.Status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, disposition,
169                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) );
170
171     if (io->u.Status == STATUS_NO_SUCH_FILE &&
172         disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
173     {
174         created = TRUE;
175         io->u.Status = STATUS_SUCCESS;
176     }
177
178     if (io->u.Status == STATUS_SUCCESS)
179     {
180         SERVER_START_REQ( create_file )
181         {
182             req->access     = access;
183             req->inherit    = (attr->Attributes & OBJ_INHERIT) != 0;
184             req->sharing    = sharing;
185             req->create     = disposition;
186             req->options    = options;
187             req->attrs      = attributes;
188             wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
189             io->u.Status = wine_server_call( req );
190             *handle = reply->handle;
191         }
192         SERVER_END_REQ;
193         RtlFreeAnsiString( &unix_name );
194     }
195     else WARN("%s not found (%lx)\n", debugstr_us(attr->ObjectName), io->u.Status );
196
197     if (io->u.Status == STATUS_SUCCESS)
198     {
199         if (created) io->Information = FILE_CREATED;
200         else switch(disposition)
201         {
202         case FILE_SUPERSEDE:
203             io->Information = FILE_SUPERSEDED;
204             break;
205         case FILE_CREATE:
206             io->Information = FILE_CREATED;
207             break;
208         case FILE_OPEN:
209         case FILE_OPEN_IF:
210             io->Information = FILE_OPENED;
211             break;
212         case FILE_OVERWRITE:
213         case FILE_OVERWRITE_IF:
214             io->Information = FILE_OVERWRITTEN;
215             break;
216         }
217     }
218
219     return io->u.Status;
220 }
221
222 /***********************************************************************
223  *                  Asynchronous file I/O                              *
224  */
225 static DWORD fileio_get_async_count(const async_private *ovp);
226 static void CALLBACK fileio_call_completion_func(ULONG_PTR data);
227 static void fileio_async_cleanup(async_private *ovp);
228
229 static async_ops fileio_async_ops =
230 {
231     fileio_get_async_count,        /* get_count */
232     fileio_call_completion_func,   /* call_completion */
233     fileio_async_cleanup           /* cleanup */
234 };
235
236 static async_ops fileio_nocomp_async_ops =
237 {
238     fileio_get_async_count,        /* get_count */
239     NULL,                          /* call_completion */
240     fileio_async_cleanup           /* cleanup */
241 };
242
243 typedef struct async_fileio
244 {
245     struct async_private             async;
246     PIO_APC_ROUTINE                  apc;
247     void*                            apc_user;
248     char                             *buffer;
249     unsigned int                     count;
250     off_t                            offset;
251     int                              queue_apc_on_error;
252     BOOL                             avail_mode;
253 } async_fileio;
254
255 static DWORD fileio_get_async_count(const struct async_private *ovp)
256 {
257     const async_fileio *fileio = (const async_fileio*) ovp;
258
259     if (fileio->count < fileio->async.iosb->Information)
260         return 0;
261     return fileio->count - fileio->async.iosb->Information;
262 }
263
264 static void CALLBACK fileio_call_completion_func(ULONG_PTR data)
265 {
266     async_fileio *ovp = (async_fileio*) data;
267     TRACE("data: %p\n", ovp);
268
269     if ((ovp->async.iosb->u.Status == STATUS_SUCCESS) || ovp->queue_apc_on_error)
270         ovp->apc( ovp->apc_user, ovp->async.iosb, ovp->async.iosb->Information );
271
272     fileio_async_cleanup( &ovp->async );
273 }
274
275 static void fileio_async_cleanup( struct async_private *ovp )
276 {
277     RtlFreeHeap( GetProcessHeap(), 0, ovp );
278 }
279
280 /***********************************************************************
281  *           FILE_GetNtStatus(void)
282  *
283  * Retrieve the Nt Status code from errno.
284  * Try to be consistent with FILE_SetDosError().
285  */
286 NTSTATUS FILE_GetNtStatus(void)
287 {
288     int err = errno;
289
290     TRACE( "errno = %d\n", errno );
291     switch (err)
292     {
293     case EAGAIN:    return STATUS_SHARING_VIOLATION;
294     case EBADF:     return STATUS_INVALID_HANDLE;
295     case ENOSPC:    return STATUS_DISK_FULL;
296     case EPERM:
297     case EROFS:
298     case EACCES:    return STATUS_ACCESS_DENIED;
299     case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
300     case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
301     case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
302     case EMFILE:
303     case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
304     case EINVAL:    return STATUS_INVALID_PARAMETER;
305     case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
306     case EPIPE:     return STATUS_PIPE_BROKEN;
307     case EIO:       return STATUS_DEVICE_NOT_READY;
308 #ifdef ENOMEDIUM
309     case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
310 #endif
311     case ENOTTY:
312     case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
313     case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
314     case ENOEXEC:   /* ?? */
315     case ESPIPE:    /* ?? */
316     case EEXIST:    /* ?? */
317     default:
318         FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
319         return STATUS_UNSUCCESSFUL;
320     }
321 }
322
323 /***********************************************************************
324  *             FILE_AsyncReadService      (INTERNAL)
325  *
326  *  This function is called while the client is waiting on the
327  *  server, so we can't make any server calls here.
328  */
329 static void FILE_AsyncReadService(async_private *ovp)
330 {
331     async_fileio *fileio = (async_fileio*) ovp;
332     IO_STATUS_BLOCK*  io_status = fileio->async.iosb;
333     int result;
334     int already = io_status->Information;
335
336     TRACE("%p %p\n", io_status, fileio->buffer );
337
338     /* check to see if the data is ready (non-blocking) */
339
340     if ( fileio->avail_mode )
341         result = read(ovp->fd, &fileio->buffer[already], fileio->count - already);
342     else
343     {
344         result = pread(ovp->fd, &fileio->buffer[already], fileio->count - already,
345                        fileio->offset + already);
346         if ((result < 0) && (errno == ESPIPE))
347             result = read(ovp->fd, &fileio->buffer[already], fileio->count - already);
348     }
349
350     if ((result < 0) && ((errno == EAGAIN) || (errno == EINTR)))
351     {
352         TRACE("Deferred read %d\n",errno);
353         io_status->u.Status = STATUS_PENDING;
354         return;
355     }
356
357     /* check to see if the transfer is complete */
358     if (result < 0)
359     {
360         io_status->u.Status = FILE_GetNtStatus();
361         return;
362     }
363     else if (result == 0)
364     {
365         io_status->u.Status = io_status->Information ? STATUS_SUCCESS : STATUS_END_OF_FILE;
366         return;
367     }
368
369     TRACE("status before: %s\n", (io_status->u.Status == STATUS_SUCCESS) ? "success" : "pending");
370     io_status->Information += result;
371     if (io_status->Information >= fileio->count || fileio->avail_mode )
372         io_status->u.Status = STATUS_SUCCESS;
373     else
374         io_status->u.Status = STATUS_PENDING;
375
376     TRACE("read %d more bytes %ld/%d so far (%s)\n",
377           result, io_status->Information, fileio->count, (io_status->u.Status == STATUS_SUCCESS) ? "success" : "pending");
378 }
379
380
381 /******************************************************************************
382  *  NtReadFile                                  [NTDLL.@]
383  *  ZwReadFile                                  [NTDLL.@]
384  *
385  * Read from an open file handle.
386  *
387  * PARAMS
388  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
389  *  Event         [I] Event to signal upon completion (or NULL)
390  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
391  *  ApcContext    [I] Context for ApcRoutine (or NULL)
392  *  IoStatusBlock [O] Receives information about the operation on return
393  *  Buffer        [O] Destination for the data read
394  *  Length        [I] Size of Buffer
395  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
396  *  Key           [O] Function unknown (may be NULL)
397  *
398  * RETURNS
399  *  Success: 0. IoStatusBlock is updated, and the Information member contains
400  *           The number of bytes read.
401  *  Failure: An NTSTATUS error code describing the error.
402  */
403 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
404                            PIO_APC_ROUTINE apc, void* apc_user,
405                            PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
406                            PLARGE_INTEGER offset, PULONG key)
407 {
408     int unix_handle, flags;
409
410     TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p),partial stub!\n",
411           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
412
413     io_status->Information = 0;
414     io_status->u.Status = wine_server_handle_to_fd( hFile, GENERIC_READ, &unix_handle, &flags );
415     if (io_status->u.Status) return io_status->u.Status;
416
417     if (flags & FD_FLAG_RECV_SHUTDOWN)
418     {
419         wine_server_release_fd( hFile, unix_handle );
420         return STATUS_PIPE_DISCONNECTED;
421     }
422
423     if (flags & FD_FLAG_TIMEOUT)
424     {
425         if (hEvent)
426         {
427             /* this shouldn't happen, but check it */
428             FIXME("NIY-hEvent\n");
429             wine_server_release_fd( hFile, unix_handle );
430             return STATUS_NOT_IMPLEMENTED;
431         }
432         io_status->u.Status = NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, NULL, 0, 0);
433         if (io_status->u.Status)
434         {
435             wine_server_release_fd( hFile, unix_handle );
436             return io_status->u.Status;
437         }
438     }
439
440     if (flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT))
441     {
442         async_fileio*   ovp;
443         NTSTATUS ret;
444
445         if (!(ovp = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(async_fileio))))
446         {
447             wine_server_release_fd( hFile, unix_handle );
448             if (flags & FD_FLAG_TIMEOUT) NtClose(hEvent);
449             return STATUS_NO_MEMORY;
450         }
451         ovp->async.ops = (apc ? &fileio_async_ops : &fileio_nocomp_async_ops );
452         ovp->async.handle = hFile;
453         ovp->async.fd = unix_handle;  /* FIXME */
454         ovp->async.type = ASYNC_TYPE_READ;
455         ovp->async.func = FILE_AsyncReadService;
456         ovp->async.event = hEvent;
457         ovp->async.iosb = io_status;
458         ovp->count = length;
459         if ( offset == NULL ) 
460             ovp->offset = 0;
461         else
462         {
463             ovp->offset = offset->QuadPart;
464             if (offset->u.HighPart && ovp->offset == offset->u.LowPart)
465                 FIXME("High part of offset is lost\n");
466         } 
467         ovp->apc = apc;
468         ovp->apc_user = apc_user;
469         ovp->buffer = buffer;
470         ovp->queue_apc_on_error = 0;
471         ovp->avail_mode = (flags & FD_FLAG_AVAILABLE);
472         NtResetEvent(hEvent, NULL);
473
474         ret = register_new_async(&ovp->async);
475         if (ret != STATUS_SUCCESS)
476         {
477             wine_server_release_fd( hFile, unix_handle );
478             if (flags & FD_FLAG_TIMEOUT) NtClose(hEvent);
479             RtlFreeHeap(GetProcessHeap(), 0, ovp);
480             return ret;
481         }
482         if (flags & FD_FLAG_TIMEOUT)
483         {
484             ret = NtWaitForSingleObject(hEvent, TRUE, NULL);
485             NtClose(hEvent);
486             if (ret != STATUS_USER_APC)
487                 ovp->queue_apc_on_error = 1;
488         }
489         else
490         {
491             LARGE_INTEGER   timeout;
492
493             /* let some APC be run, this will read some already pending data */
494             timeout.u.LowPart = timeout.u.HighPart = 0;
495             ret = NtDelayExecution( TRUE, &timeout );
496             /* the apc didn't run and therefore the completion routine now
497              * needs to be sent errors.
498              * Note that there is no race between setting this flag and
499              * returning errors because apc's are run only during alertable
500              * waits */
501             if (ret != STATUS_USER_APC)
502                 ovp->queue_apc_on_error = 1;
503             /* if we only have to read the available data, and none is available,
504              * simply cancel the request. If data was available, it has been read
505              * while in by previous call (NtDelayExecution)
506              */
507             if ((flags & FD_FLAG_AVAILABLE) && io_status->u.Status == STATUS_PENDING)
508             {
509                 io_status->u.Status = STATUS_SUCCESS;
510                 register_old_async(&ovp->async);
511             }
512         }
513         TRACE("= 0x%08lx\n", io_status->u.Status);
514         return io_status->u.Status;
515     }
516
517     if (offset)
518     {
519         FILE_POSITION_INFORMATION   fpi;
520
521         fpi.CurrentByteOffset = *offset;
522         io_status->u.Status = NtSetInformationFile(hFile, io_status, &fpi, sizeof(fpi), 
523                                                    FilePositionInformation);
524         if (io_status->u.Status)
525         {
526             wine_server_release_fd( hFile, unix_handle );
527             return io_status->u.Status;
528         }
529     }
530     /* code for synchronous reads */
531     while ((io_status->Information = read( unix_handle, buffer, length )) == -1)
532     {
533         if ((errno == EAGAIN) || (errno == EINTR)) continue;
534         if (errno == EFAULT)
535         {
536             io_status->Information = 0;
537             io_status->u.Status = STATUS_ACCESS_VIOLATION;
538         }
539         else io_status->u.Status = FILE_GetNtStatus();
540         break;
541     }
542     wine_server_release_fd( hFile, unix_handle );
543     TRACE("= 0x%08lx\n", io_status->u.Status);
544     return io_status->u.Status;
545 }
546
547 /***********************************************************************
548  *             FILE_AsyncWriteService      (INTERNAL)
549  *
550  *  This function is called while the client is waiting on the
551  *  server, so we can't make any server calls here.
552  */
553 static void FILE_AsyncWriteService(struct async_private *ovp)
554 {
555     async_fileio *fileio = (async_fileio *) ovp;
556     PIO_STATUS_BLOCK io_status = fileio->async.iosb;
557     int result;
558     int already = io_status->Information;
559
560     TRACE("(%p %p)\n",io_status,fileio->buffer);
561
562     /* write some data (non-blocking) */
563
564     if ( fileio->avail_mode )
565         result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
566     else
567     {
568         result = pwrite(ovp->fd, &fileio->buffer[already], fileio->count - already,
569                         fileio->offset + already);
570         if ((result < 0) && (errno == ESPIPE))
571             result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
572     }
573
574     if ((result < 0) && ((errno == EAGAIN) || (errno == EINTR)))
575     {
576         io_status->u.Status = STATUS_PENDING;
577         return;
578     }
579
580     /* check to see if the transfer is complete */
581     if (result < 0)
582     {
583         io_status->u.Status = FILE_GetNtStatus();
584         return;
585     }
586
587     io_status->Information += result;
588     io_status->u.Status = (io_status->Information < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
589     TRACE("wrote %d more bytes %ld/%d so far\n",result,io_status->Information,fileio->count);
590 }
591
592 /******************************************************************************
593  *  NtWriteFile                                 [NTDLL.@]
594  *  ZwWriteFile                                 [NTDLL.@]
595  *
596  * Write to an open file handle.
597  *
598  * PARAMS
599  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
600  *  Event         [I] Event to signal upon completion (or NULL)
601  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
602  *  ApcContext    [I] Context for ApcRoutine (or NULL)
603  *  IoStatusBlock [O] Receives information about the operation on return
604  *  Buffer        [I] Source for the data to write
605  *  Length        [I] Size of Buffer
606  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
607  *  Key           [O] Function unknown (may be NULL)
608  *
609  * RETURNS
610  *  Success: 0. IoStatusBlock is updated, and the Information member contains
611  *           The number of bytes written.
612  *  Failure: An NTSTATUS error code describing the error.
613  */
614 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
615                             PIO_APC_ROUTINE apc, void* apc_user,
616                             PIO_STATUS_BLOCK io_status, 
617                             const void* buffer, ULONG length,
618                             PLARGE_INTEGER offset, PULONG key)
619 {
620     int unix_handle, flags;
621
622     TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p)!\n",
623           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
624
625     io_status->Information = 0;
626     io_status->u.Status = wine_server_handle_to_fd( hFile, GENERIC_WRITE, &unix_handle, &flags );
627     if (io_status->u.Status) return io_status->u.Status;
628
629     if (flags & FD_FLAG_SEND_SHUTDOWN)
630     {
631         wine_server_release_fd( hFile, unix_handle );
632         return STATUS_PIPE_DISCONNECTED;
633     }
634
635     if (flags & FD_FLAG_TIMEOUT)
636     {
637         if (hEvent)
638         {
639             /* this shouldn't happen, but check it */
640             FIXME("NIY-hEvent\n");
641             wine_server_release_fd( hFile, unix_handle );
642             return STATUS_NOT_IMPLEMENTED;
643         }
644         io_status->u.Status = NtCreateEvent(&hEvent, EVENT_ALL_ACCESS, NULL, 0, 0);
645         if (io_status->u.Status)
646         {
647             wine_server_release_fd( hFile, unix_handle );
648             return io_status->u.Status;
649         }
650     }
651
652     if (flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT))
653     {
654         async_fileio*   ovp;
655         NTSTATUS ret;
656
657         if (!(ovp = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(async_fileio))))
658         {
659             wine_server_release_fd( hFile, unix_handle );
660             return STATUS_NO_MEMORY;
661         }
662         ovp->async.ops = (apc ? &fileio_async_ops : &fileio_nocomp_async_ops );
663         ovp->async.handle = hFile;
664         ovp->async.fd = unix_handle;  /* FIXME */
665         ovp->async.type = ASYNC_TYPE_WRITE;
666         ovp->async.func = FILE_AsyncWriteService;
667         ovp->async.event = hEvent;
668         ovp->async.iosb = io_status;
669         ovp->count = length;
670         if (offset) {
671             ovp->offset = offset->QuadPart;
672             if (offset->u.HighPart && ovp->offset == offset->u.LowPart)
673                 FIXME("High part of offset is lost\n");
674         } else {
675             ovp->offset = 0;
676         }
677         ovp->apc = apc;
678         ovp->apc_user = apc_user;
679         ovp->buffer = (void*)buffer;
680         ovp->queue_apc_on_error = 0;
681         ovp->avail_mode = (flags & FD_FLAG_AVAILABLE);
682         NtResetEvent(hEvent, NULL);
683
684         io_status->Information = 0;
685         ret = register_new_async(&ovp->async);
686         if (ret != STATUS_SUCCESS)
687             return ret;
688         if (flags & FD_FLAG_TIMEOUT)
689         {
690             ret = NtWaitForSingleObject(hEvent, TRUE, NULL);
691             NtClose(hEvent);
692             if (ret != STATUS_USER_APC)
693                 ovp->queue_apc_on_error = 1;
694         }
695         else
696         {
697             LARGE_INTEGER   timeout;
698
699             /* let some APC be run, this will write as much data as possible */
700             timeout.u.LowPart = timeout.u.HighPart = 0;
701             ret = NtDelayExecution( TRUE, &timeout );
702             /* the apc didn't run and therefore the completion routine now
703              * needs to be sent errors.
704              * Note that there is no race between setting this flag and
705              * returning errors because apc's are run only during alertable
706              * waits */
707             if (ret != STATUS_USER_APC)
708                 ovp->queue_apc_on_error = 1;
709         }
710         return io_status->u.Status;
711     }
712
713     if (offset)
714     {
715         FILE_POSITION_INFORMATION   fpi;
716
717         fpi.CurrentByteOffset = *offset;
718         io_status->u.Status = NtSetInformationFile(hFile, io_status, &fpi, sizeof(fpi),
719                                                    FilePositionInformation);
720         if (io_status->u.Status)
721         {
722             wine_server_release_fd( hFile, unix_handle );
723             return io_status->u.Status;
724         }
725     }
726
727     /* synchronous file write */
728     while ((io_status->Information = write( unix_handle, buffer, length )) == -1)
729     {
730         if ((errno == EAGAIN) || (errno == EINTR)) continue;
731         if (errno == EFAULT)
732         {
733             io_status->Information = 0;
734             io_status->u.Status = STATUS_INVALID_USER_BUFFER;
735         }
736         else if (errno == ENOSPC) io_status->u.Status = STATUS_DISK_FULL;
737         else io_status->u.Status = FILE_GetNtStatus();
738         break;
739     }
740     wine_server_release_fd( hFile, unix_handle );
741     return io_status->u.Status;
742 }
743
744 /**************************************************************************
745  *              NtDeviceIoControlFile                   [NTDLL.@]
746  *              ZwDeviceIoControlFile                   [NTDLL.@]
747  *
748  * Perform an I/O control operation on an open file handle.
749  *
750  * PARAMS
751  *  DeviceHandle     [I] Handle returned from ZwOpenFile() or ZwCreateFile()
752  *  Event            [I] Event to signal upon completion (or NULL)
753  *  ApcRoutine       [I] Callback to call upon completion (or NULL)
754  *  ApcContext       [I] Context for ApcRoutine (or NULL)
755  *  IoStatusBlock    [O] Receives information about the operation on return
756  *  IoControlCode    [I] Control code for the operation to perform
757  *  InputBuffer      [I] Source for any input data required (or NULL)
758  *  InputBufferSize  [I] Size of InputBuffer
759  *  OutputBuffer     [O] Source for any output data returned (or NULL)
760  *  OutputBufferSize [I] Size of OutputBuffer
761  *
762  * RETURNS
763  *  Success: 0. IoStatusBlock is updated.
764  *  Failure: An NTSTATUS error code describing the error.
765  */
766 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE DeviceHandle, HANDLE hEvent,
767                                       PIO_APC_ROUTINE UserApcRoutine, 
768                                       PVOID UserApcContext,
769                                       PIO_STATUS_BLOCK IoStatusBlock,
770                                       ULONG IoControlCode,
771                                       PVOID InputBuffer,
772                                       ULONG InputBufferSize,
773                                       PVOID OutputBuffer,
774                                       ULONG OutputBufferSize)
775 {
776     TRACE("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx)\n",
777           DeviceHandle, hEvent, UserApcRoutine, UserApcContext,
778           IoStatusBlock, IoControlCode, 
779           InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize);
780
781     if (CDROM_DeviceIoControl(DeviceHandle, hEvent,
782                               UserApcRoutine, UserApcContext,
783                               IoStatusBlock, IoControlCode,
784                               InputBuffer, InputBufferSize,
785                               OutputBuffer, OutputBufferSize) == STATUS_NO_SUCH_DEVICE)
786     {
787         /* it wasn't a CDROM */
788         FIXME("Unimplemented dwIoControlCode=%08lx\n", IoControlCode);
789         IoStatusBlock->u.Status = STATUS_NOT_IMPLEMENTED;
790         IoStatusBlock->Information = 0;
791         if (hEvent) NtSetEvent(hEvent, NULL);
792     }
793     return IoStatusBlock->u.Status;
794 }
795
796 /******************************************************************************
797  * NtFsControlFile [NTDLL.@]
798  * ZwFsControlFile [NTDLL.@]
799  */
800 NTSTATUS WINAPI NtFsControlFile(
801         IN HANDLE DeviceHandle,
802         IN HANDLE Event OPTIONAL,
803         IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
804         IN PVOID ApcContext OPTIONAL,
805         OUT PIO_STATUS_BLOCK IoStatusBlock,
806         IN ULONG IoControlCode,
807         IN PVOID InputBuffer,
808         IN ULONG InputBufferSize,
809         OUT PVOID OutputBuffer,
810         IN ULONG OutputBufferSize)
811 {
812         FIXME("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx): stub\n",
813         DeviceHandle,Event,ApcRoutine,ApcContext,IoStatusBlock,IoControlCode,
814         InputBuffer,InputBufferSize,OutputBuffer,OutputBufferSize);
815         return 0;
816 }
817
818 /******************************************************************************
819  *  NtSetVolumeInformationFile          [NTDLL.@]
820  *  ZwSetVolumeInformationFile          [NTDLL.@]
821  *
822  * Set volume information for an open file handle.
823  *
824  * PARAMS
825  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
826  *  IoStatusBlock      [O] Receives information about the operation on return
827  *  FsInformation      [I] Source for volume information
828  *  Length             [I] Size of FsInformation
829  *  FsInformationClass [I] Type of volume information to set
830  *
831  * RETURNS
832  *  Success: 0. IoStatusBlock is updated.
833  *  Failure: An NTSTATUS error code describing the error.
834  */
835 NTSTATUS WINAPI NtSetVolumeInformationFile(
836         IN HANDLE FileHandle,
837         PIO_STATUS_BLOCK IoStatusBlock,
838         PVOID FsInformation,
839         ULONG Length,
840         FS_INFORMATION_CLASS FsInformationClass)
841 {
842         FIXME("(%p,%p,%p,0x%08lx,0x%08x) stub\n",
843         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
844         return 0;
845 }
846
847 /******************************************************************************
848  *  NtQueryInformationFile              [NTDLL.@]
849  *  ZwQueryInformationFile              [NTDLL.@]
850  *
851  * Get information about an open file handle.
852  *
853  * PARAMS
854  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
855  *  io       [O] Receives information about the operation on return
856  *  ptr      [O] Destination for file information
857  *  len      [I] Size of FileInformation
858  *  class    [I] Type of file information to get
859  *
860  * RETURNS
861  *  Success: 0. IoStatusBlock and FileInformation are updated.
862  *  Failure: An NTSTATUS error code describing the error.
863  */
864 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
865                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
866 {
867     static const size_t info_sizes[] =
868     {
869         0,
870         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
871         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
872         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
873         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
874         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
875         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
876         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
877         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
878         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
879         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
880         0,                                             /* FileLinkInformation */
881         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
882         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
883         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
884         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
885         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
886         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
887         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
888         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
889         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
890         0,                                             /* FileAlternateNameInformation */
891         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
892         0,                                             /* FilePipeInformation */
893         0,                                             /* FilePipeLocalInformation */
894         0,                                             /* FilePipeRemoteInformation */
895         0,                                             /* FileMailslotQueryInformation */
896         0,                                             /* FileMailslotSetInformation */
897         0,                                             /* FileCompressionInformation */
898         0,                                             /* FileObjectIdInformation */
899         0,                                             /* FileCompletionInformation */
900         0,                                             /* FileMoveClusterInformation */
901         0,                                             /* FileQuotaInformation */
902         0,                                             /* FileReparsePointInformation */
903         0,                                             /* FileNetworkOpenInformation */
904         0,                                             /* FileAttributeTagInformation */
905         0                                              /* FileTrackingInformation */
906     };
907
908     struct stat st;
909     int fd;
910
911     TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", hFile, io, ptr, len, class);
912
913     io->Information = 0;
914
915     if (class <= 0 || class >= FileMaximumInformation)
916         return io->u.Status = STATUS_INVALID_INFO_CLASS;
917     if (!info_sizes[class])
918     {
919         FIXME("Unsupported class (%d)\n", class);
920         return io->u.Status = STATUS_NOT_IMPLEMENTED;
921     }
922     if (len < info_sizes[class])
923         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
924
925     if ((io->u.Status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
926         return io->u.Status;
927
928     switch (class)
929     {
930     case FileBasicInformation:
931         {
932             FILE_BASIC_INFORMATION *info = ptr;
933
934             if (fstat( fd, &st ) == -1)
935                 io->u.Status = FILE_GetNtStatus();
936             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
937                 io->u.Status = STATUS_INVALID_INFO_CLASS;
938             else
939             {
940                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
941                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
942                 if (!(st.st_mode & S_IWUSR)) info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
943                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
944                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
945                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
946                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
947             }
948         }
949         break;
950     case FileStandardInformation:
951         {
952             FILE_STANDARD_INFORMATION *info = ptr;
953
954             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
955             else
956             {
957                 if ((info->Directory = S_ISDIR(st.st_mode)))
958                 {
959                     info->AllocationSize.QuadPart = 0;
960                     info->EndOfFile.QuadPart      = 0;
961                     info->NumberOfLinks           = 1;
962                     info->DeletePending           = FALSE;
963                 }
964                 else
965                 {
966                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
967                     info->EndOfFile.QuadPart      = st.st_size;
968                     info->NumberOfLinks           = st.st_nlink;
969                     info->DeletePending           = FALSE; /* FIXME */
970                 }
971             }
972         }
973         break;
974     case FilePositionInformation:
975         {
976             FILE_POSITION_INFORMATION *info = ptr;
977             off_t res = lseek( fd, 0, SEEK_CUR );
978             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
979             else info->CurrentByteOffset.QuadPart = res;
980         }
981         break;
982     case FileInternalInformation:
983         {
984             FILE_INTERNAL_INFORMATION *info = ptr;
985
986             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
987             else info->IndexNumber.QuadPart = st.st_ino;
988         }
989         break;
990     case FileEaInformation:
991         {
992             FILE_EA_INFORMATION *info = ptr;
993             info->EaSize = 0;
994         }
995         break;
996     case FileEndOfFileInformation:
997         {
998             FILE_END_OF_FILE_INFORMATION *info = ptr;
999
1000             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1001             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
1002         }
1003         break;
1004     case FileAllInformation:
1005         {
1006             FILE_ALL_INFORMATION *info = ptr;
1007
1008             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1009             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1010                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1011             else
1012             {
1013                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
1014                 {
1015                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1016                     info->StandardInformation.AllocationSize.QuadPart = 0;
1017                     info->StandardInformation.EndOfFile.QuadPart      = 0;
1018                     info->StandardInformation.NumberOfLinks           = 1;
1019                     info->StandardInformation.DeletePending           = FALSE;
1020                 }
1021                 else
1022                 {
1023                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1024                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1025                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1026                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1027                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1028                 }
1029                 if (!(st.st_mode & S_IWUSR))
1030                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1031                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1032                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1033                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1034                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1035                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1036                 info->EaInformation.EaSize = 0;
1037                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1038                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1039                 info->ModeInformation.Mode = 0;  /* FIXME */
1040                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1041                 info->NameInformation.FileNameLength = 0;
1042                 io->Information = sizeof(*info) - sizeof(WCHAR);
1043             }
1044         }
1045         break;
1046     default:
1047         FIXME("Unsupported class (%d)\n", class);
1048         io->u.Status = STATUS_NOT_IMPLEMENTED;
1049         break;
1050     }
1051     wine_server_release_fd( hFile, fd );
1052     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1053     return io->u.Status;
1054 }
1055
1056 /******************************************************************************
1057  *  NtSetInformationFile                [NTDLL.@]
1058  *  ZwSetInformationFile                [NTDLL.@]
1059  *
1060  * Set information about an open file handle.
1061  *
1062  * PARAMS
1063  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1064  *  io      [O] Receives information about the operation on return
1065  *  ptr     [I] Source for file information
1066  *  len     [I] Size of FileInformation
1067  *  class   [I] Type of file information to set
1068  *
1069  * RETURNS
1070  *  Success: 0. io is updated.
1071  *  Failure: An NTSTATUS error code describing the error.
1072  */
1073 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1074                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1075 {
1076     int fd;
1077
1078     TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", handle, io, ptr, len, class);
1079
1080     if ((io->u.Status = wine_server_handle_to_fd( handle, 0, &fd, NULL )))
1081         return io->u.Status;
1082
1083     io->u.Status = STATUS_SUCCESS;
1084     switch (class)
1085     {
1086     case FileBasicInformation:
1087         if (len >= sizeof(FILE_BASIC_INFORMATION))
1088         {
1089             struct stat st;
1090             const FILE_BASIC_INFORMATION *info = ptr;
1091
1092             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1093             {
1094                 ULONGLONG sec, nsec;
1095                 struct timeval tv[2];
1096
1097                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1098                 {
1099
1100                     tv[0].tv_sec = tv[0].tv_usec = 0;
1101                     tv[1].tv_sec = tv[1].tv_usec = 0;
1102                     if (!fstat( fd, &st ))
1103                     {
1104                         tv[0].tv_sec = st.st_atime;
1105                         tv[1].tv_sec = st.st_mtime;
1106                     }
1107                 }
1108                 if (info->LastAccessTime.QuadPart)
1109                 {
1110                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1111                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1112                     tv[0].tv_usec = (UINT)nsec / 10;
1113                 }
1114                 if (info->LastWriteTime.QuadPart)
1115                 {
1116                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1117                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1118                     tv[1].tv_usec = (UINT)nsec / 10;
1119                 }
1120                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1121             }
1122
1123             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1124             {
1125                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1126                 else
1127                 {
1128                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1129                     {
1130                         if (S_ISDIR( st.st_mode))
1131                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1132                         else
1133                             st.st_mode &= ~0222; /* clear write permission bits */
1134                     }
1135                     else
1136                     {
1137                         /* add write permission only where we already have read permission */
1138                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1139                     }
1140                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1141                 }
1142             }
1143         }
1144         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1145         break;
1146
1147     case FilePositionInformation:
1148         if (len >= sizeof(FILE_POSITION_INFORMATION))
1149         {
1150             const FILE_POSITION_INFORMATION *info = ptr;
1151
1152             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1153                 io->u.Status = FILE_GetNtStatus();
1154         }
1155         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1156         break;
1157
1158     case FileEndOfFileInformation:
1159         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1160         {
1161             struct stat st;
1162             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1163
1164             /* first try normal truncate */
1165             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1166
1167             /* now check for the need to extend the file */
1168             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1169             {
1170                 static const char zero;
1171
1172                 /* extend the file one byte beyond the requested size and then truncate it */
1173                 /* this should work around ftruncate implementations that can't extend files */
1174                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1175                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1176             }
1177             io->u.Status = FILE_GetNtStatus();
1178         }
1179         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1180         break;
1181
1182     default:
1183         FIXME("Unsupported class (%d)\n", class);
1184         io->u.Status = STATUS_NOT_IMPLEMENTED;
1185         break;
1186     }
1187     wine_server_release_fd( handle, fd );
1188     io->Information = 0;
1189     return io->u.Status;
1190 }
1191
1192
1193 /******************************************************************************
1194  *              NtQueryFullAttributesFile   (NTDLL.@)
1195  */
1196 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1197                                            FILE_NETWORK_OPEN_INFORMATION *info )
1198 {
1199     ANSI_STRING unix_name;
1200     NTSTATUS status;
1201
1202     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1203                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1204     {
1205         struct stat st;
1206
1207         if (stat( unix_name.Buffer, &st ) == -1)
1208             status = FILE_GetNtStatus();
1209         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1210             status = STATUS_INVALID_INFO_CLASS;
1211         else
1212         {
1213             if (S_ISDIR(st.st_mode))
1214             {
1215                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1216                 info->AllocationSize.QuadPart = 0;
1217                 info->EndOfFile.QuadPart      = 0;
1218             }
1219             else
1220             {
1221                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1222                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1223                 info->EndOfFile.QuadPart      = st.st_size;
1224             }
1225             if (!(st.st_mode & S_IWUSR)) info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1226             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1227             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1228             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1229             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1230             if (DIR_is_hidden_file( attr->ObjectName ))
1231                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1232         }
1233         RtlFreeAnsiString( &unix_name );
1234     }
1235     else WARN("%s not found (%lx)\n", debugstr_us(attr->ObjectName), status );
1236     return status;
1237 }
1238
1239
1240 /******************************************************************************
1241  *              NtQueryAttributesFile   (NTDLL.@)
1242  *              ZwQueryAttributesFile   (NTDLL.@)
1243  */
1244 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1245 {
1246     FILE_NETWORK_OPEN_INFORMATION full_info;
1247     NTSTATUS status;
1248
1249     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
1250     {
1251         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
1252         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
1253         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
1254         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
1255         info->FileAttributes          = full_info.FileAttributes;
1256     }
1257     return status;
1258 }
1259
1260
1261 /******************************************************************************
1262  *  NtQueryVolumeInformationFile                [NTDLL.@]
1263  *  ZwQueryVolumeInformationFile                [NTDLL.@]
1264  *
1265  * Get volume information for an open file handle.
1266  *
1267  * PARAMS
1268  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1269  *  io          [O] Receives information about the operation on return
1270  *  buffer      [O] Destination for volume information
1271  *  length      [I] Size of FsInformation
1272  *  info_class  [I] Type of volume information to set
1273  *
1274  * RETURNS
1275  *  Success: 0. io and buffer are updated.
1276  *  Failure: An NTSTATUS error code describing the error.
1277  */
1278 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
1279                                               PVOID buffer, ULONG length,
1280                                               FS_INFORMATION_CLASS info_class )
1281 {
1282     int fd;
1283     struct stat st;
1284
1285     if ((io->u.Status = wine_server_handle_to_fd( handle, 0, &fd, NULL )) != STATUS_SUCCESS)
1286         return io->u.Status;
1287
1288     io->u.Status = STATUS_NOT_IMPLEMENTED;
1289     io->Information = 0;
1290
1291     switch( info_class )
1292     {
1293     case FileFsVolumeInformation:
1294         FIXME( "%p: volume info not supported\n", handle );
1295         break;
1296     case FileFsLabelInformation:
1297         FIXME( "%p: label info not supported\n", handle );
1298         break;
1299     case FileFsSizeInformation:
1300         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
1301             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1302         else
1303         {
1304             FILE_FS_SIZE_INFORMATION *info = buffer;
1305             struct statvfs stvfs;
1306
1307             if (fstat( fd, &st ) < 0)
1308             {
1309                 io->u.Status = FILE_GetNtStatus();
1310                 break;
1311             }
1312             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1313             {
1314                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
1315                 break;
1316             }
1317             if (fstatvfs( fd, &stvfs ) < 0) io->u.Status = FILE_GetNtStatus();
1318             else
1319             {
1320                 info->TotalAllocationUnits.QuadPart = stvfs.f_blocks;
1321                 info->AvailableAllocationUnits.QuadPart = stvfs.f_bavail;
1322                 info->SectorsPerAllocationUnit = 1;
1323                 info->BytesPerSector = stvfs.f_frsize;
1324                 io->Information = sizeof(*info);
1325                 io->u.Status = STATUS_SUCCESS;
1326             }
1327         }
1328         break;
1329     case FileFsDeviceInformation:
1330         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
1331             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1332         else
1333         {
1334             FILE_FS_DEVICE_INFORMATION *info = buffer;
1335
1336             info->Characteristics = 0;
1337             if (fstat( fd, &st ) < 0)
1338             {
1339                 io->u.Status = FILE_GetNtStatus();
1340                 break;
1341             }
1342             if (S_ISCHR( st.st_mode ))
1343             {
1344                 info->DeviceType = FILE_DEVICE_UNKNOWN;
1345 #ifdef linux
1346                 switch(major(st.st_rdev))
1347                 {
1348                 case MEM_MAJOR:
1349                     info->DeviceType = FILE_DEVICE_NULL;
1350                     break;
1351                 case TTY_MAJOR:
1352                     info->DeviceType = FILE_DEVICE_SERIAL_PORT;
1353                     break;
1354                 case LP_MAJOR:
1355                     info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
1356                     break;
1357                 }
1358 #endif
1359             }
1360             else if (S_ISBLK( st.st_mode ))
1361             {
1362                 info->DeviceType = FILE_DEVICE_DISK;
1363             }
1364             else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
1365             {
1366                 info->DeviceType = FILE_DEVICE_NAMED_PIPE;
1367             }
1368             else  /* regular file or directory */
1369             {
1370 #if defined(linux) && defined(HAVE_FSTATFS)
1371                 struct statfs stfs;
1372
1373                 /* check for floppy disk */
1374                 if (major(st.st_dev) == FLOPPY_MAJOR)
1375                     info->Characteristics |= FILE_REMOVABLE_MEDIA;
1376
1377                 if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
1378                 switch (stfs.f_type)
1379                 {
1380                 case 0x9660:      /* iso9660 */
1381                 case 0x15013346:  /* udf */
1382                     info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1383                     info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1384                     break;
1385                 case 0x6969:  /* nfs */
1386                 case 0x517B:  /* smbfs */
1387                 case 0x564c:  /* ncpfs */
1388                     info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1389                     info->Characteristics |= FILE_REMOTE_DEVICE;
1390                     break;
1391                 case 0x01021994:  /* tmpfs */
1392                 case 0x28cd3d45:  /* cramfs */
1393                 case 0x1373:      /* devfs */
1394                 case 0x9fa0:      /* procfs */
1395                     info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1396                     break;
1397                 default:
1398                     info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1399                     break;
1400                 }
1401 #elif defined (__APPLE__)
1402                 #include <IOKit/IOKitLib.h>
1403                 #include <CoreFoundation/CFNumber.h> /* for kCFBooleanTrue, kCFBooleanFalse */
1404                 #include <paths.h>
1405                 struct statfs stfs;
1406                 
1407                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1408                 
1409                 if (fstatfs( fd, &stfs ) < 0) break;
1410
1411                 /* stfs.f_type is reserved (always set to 0) so use IOKit */
1412                 kern_return_t kernResult = KERN_FAILURE; 
1413                 mach_port_t masterPort;
1414                 
1415                 char bsdName[6]; /* disk#\0 */
1416                 
1417                 strncpy(bsdName, stfs.f_mntfromname+strlen(_PATH_DEV) , 5);
1418                 bsdName[5] = 0;
1419
1420                 kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
1421
1422                 if (kernResult == KERN_SUCCESS)
1423                 {
1424                     CFMutableDictionaryRef matching = IOBSDNameMatching(masterPort, 0, bsdName);
1425                     
1426                     if (matching)
1427                     {
1428                         CFMutableDictionaryRef properties;
1429                         io_service_t devService = IOServiceGetMatchingService(masterPort, matching);
1430                         
1431                         if (IORegistryEntryCreateCFProperties(devService, 
1432                                                                 &properties,
1433                                                                 kCFAllocatorDefault, 0) != KERN_SUCCESS)
1434                                                                     break;
1435                         if ( CFEqual(
1436                                         CFDictionaryGetValue(properties, CFSTR("Removable")),
1437                                         kCFBooleanTrue)
1438                             ) info->Characteristics |= FILE_REMOVABLE_MEDIA;
1439                             
1440                         if ( CFEqual(
1441                                         CFDictionaryGetValue(properties, CFSTR("Writable")),
1442                                         kCFBooleanFalse)
1443                             ) info->Characteristics |= FILE_READ_ONLY_DEVICE;
1444
1445                         /*
1446                             NB : mounted disk image (.img/.dmg) don't provide specific type
1447                         */
1448                         CFStringRef type;
1449                         if ( (type = CFDictionaryGetValue(properties, CFSTR("Type"))) )
1450                         {
1451                             if ( CFStringCompare(type, CFSTR("CD-ROM"), 0) == kCFCompareEqualTo
1452                                 || CFStringCompare(type, CFSTR("DVD-ROM"), 0) == kCFCompareEqualTo
1453                             )
1454                             {
1455                                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1456                             }
1457                         } 
1458                         
1459                         if (properties)
1460                             CFRelease(properties);
1461                     }
1462                 }
1463 #else
1464                 static int warned;
1465                 if (!warned++) FIXME( "device info not properly supported on this platform\n" );
1466                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1467 #endif
1468                 info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
1469             }
1470             io->Information = sizeof(*info);
1471             io->u.Status = STATUS_SUCCESS;
1472         }
1473         break;
1474     case FileFsAttributeInformation:
1475         FIXME( "%p: attribute info not supported\n", handle );
1476         break;
1477     case FileFsControlInformation:
1478         FIXME( "%p: control info not supported\n", handle );
1479         break;
1480     case FileFsFullSizeInformation:
1481         FIXME( "%p: full size info not supported\n", handle );
1482         break;
1483     case FileFsObjectIdInformation:
1484         FIXME( "%p: object id info not supported\n", handle );
1485         break;
1486     case FileFsMaximumInformation:
1487         FIXME( "%p: maximum info not supported\n", handle );
1488         break;
1489     default:
1490         io->u.Status = STATUS_INVALID_PARAMETER;
1491         break;
1492     }
1493     wine_server_release_fd( handle, fd );
1494     return io->u.Status;
1495 }
1496
1497
1498 /******************************************************************
1499  *              NtFlushBuffersFile  (NTDLL.@)
1500  *
1501  * Flush any buffered data on an open file handle.
1502  *
1503  * PARAMS
1504  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1505  *  IoStatusBlock      [O] Receives information about the operation on return
1506  *
1507  * RETURNS
1508  *  Success: 0. IoStatusBlock is updated.
1509  *  Failure: An NTSTATUS error code describing the error.
1510  */
1511 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
1512 {
1513     NTSTATUS ret;
1514     HANDLE hEvent = NULL;
1515
1516     SERVER_START_REQ( flush_file )
1517     {
1518         req->handle = hFile;
1519         ret = wine_server_call( req );
1520         hEvent = reply->event;
1521     }
1522     SERVER_END_REQ;
1523     if (!ret && hEvent)
1524     {
1525         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
1526         NtClose( hEvent );
1527     }
1528     return ret;
1529 }
1530
1531 /******************************************************************
1532  *              NtLockFile       (NTDLL.@)
1533  *
1534  *
1535  */
1536 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
1537                             PIO_APC_ROUTINE apc, void* apc_user,
1538                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
1539                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
1540                             BOOLEAN exclusive )
1541 {
1542     NTSTATUS    ret;
1543     HANDLE      handle;
1544     BOOLEAN     async;
1545
1546     if (apc || io_status || key)
1547     {
1548         FIXME("Unimplemented yet parameter\n");
1549         return STATUS_NOT_IMPLEMENTED;
1550     }
1551
1552     for (;;)
1553     {
1554         SERVER_START_REQ( lock_file )
1555         {
1556             req->handle      = hFile;
1557             req->offset_low  = offset->u.LowPart;
1558             req->offset_high = offset->u.HighPart;
1559             req->count_low   = count->u.LowPart;
1560             req->count_high  = count->u.HighPart;
1561             req->shared      = !exclusive;
1562             req->wait        = !dont_wait;
1563             ret = wine_server_call( req );
1564             handle = reply->handle;
1565             async  = reply->overlapped;
1566         }
1567         SERVER_END_REQ;
1568         if (ret != STATUS_PENDING)
1569         {
1570             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
1571             return ret;
1572         }
1573
1574         if (async)
1575         {
1576             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
1577             if (handle) NtClose( handle );
1578             return STATUS_PENDING;
1579         }
1580         if (handle)
1581         {
1582             NtWaitForSingleObject( handle, FALSE, NULL );
1583             NtClose( handle );
1584         }
1585         else
1586         {
1587             LARGE_INTEGER time;
1588     
1589             /* Unix lock conflict, sleep a bit and retry */
1590             time.QuadPart = 100 * (ULONGLONG)10000;
1591             time.QuadPart = -time.QuadPart;
1592             NtDelayExecution( FALSE, &time );
1593         }
1594     }
1595 }
1596
1597
1598 /******************************************************************
1599  *              NtUnlockFile    (NTDLL.@)
1600  *
1601  *
1602  */
1603 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
1604                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
1605                               PULONG key )
1606 {
1607     NTSTATUS status;
1608
1609     TRACE( "%p %lx%08lx %lx%08lx\n",
1610            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
1611
1612     if (io_status || key)
1613     {
1614         FIXME("Unimplemented yet parameter\n");
1615         return STATUS_NOT_IMPLEMENTED;
1616     }
1617
1618     SERVER_START_REQ( unlock_file )
1619     {
1620         req->handle      = hFile;
1621         req->offset_low  = offset->u.LowPart;
1622         req->offset_high = offset->u.HighPart;
1623         req->count_low   = count->u.LowPart;
1624         req->count_high  = count->u.HighPart;
1625         status = wine_server_call( req );
1626     }
1627     SERVER_END_REQ;
1628     return status;
1629 }
1630
1631 /******************************************************************
1632  *              NtCreateNamedPipeFile    (NTDLL.@)
1633  *
1634  *
1635  */
1636 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE FileHandle, ULONG DesiredAccess,
1637      POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock,
1638      ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions,
1639      ULONG NamedPipeType, ULONG ReadMode, ULONG CompletionMode,
1640      ULONG MaximumInstances, ULONG InboundQuota, ULONG OutboundQuota,
1641      PLARGE_INTEGER DefaultTimeout)
1642 {
1643     FIXME("(%p %lx %p %p %lx %ld %lx %ld %ld %ld %ld %ld %ld %p): stub\n",
1644           FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock,
1645           ShareAccess, CreateDisposition, CreateOptions, NamedPipeType,
1646           ReadMode, CompletionMode, MaximumInstances, InboundQuota,
1647           OutboundQuota, DefaultTimeout);
1648     return STATUS_NOT_IMPLEMENTED;
1649 }
1650
1651 /******************************************************************
1652  *              NtDeleteFile    (NTDLL.@)
1653  *
1654  *
1655  */
1656 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
1657 {
1658     NTSTATUS status;
1659     HANDLE hFile;
1660     IO_STATUS_BLOCK io;
1661
1662     TRACE("%p\n", ObjectAttributes);
1663     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE, ObjectAttributes, 
1664                            &io, NULL, 0,
1665                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
1666                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
1667     if (status == STATUS_SUCCESS) status = NtClose(hFile);
1668     return status;
1669 }
1670
1671 /******************************************************************
1672  *              NtCancelIoFile    (NTDLL.@)
1673  *
1674  *
1675  */
1676 NTSTATUS WINAPI NtCancelIoFile( HANDLE FileHandle,
1677     PIO_STATUS_BLOCK IoStatusBlock)
1678 {
1679     FIXME("%p %p\n", FileHandle, IoStatusBlock );
1680     return STATUS_NOT_IMPLEMENTED;
1681 }