Avoid integer overflows in NTDLL_get_server_timeout (spotted by Mike
[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] Structue 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, SYNCHRONIZE, 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) FIXME( "EFAULT handling broken for now\n" );
535         io_status->u.Status = FILE_GetNtStatus();
536         break;
537     }
538     wine_server_release_fd( hFile, unix_handle );
539     TRACE("= 0x%08lx\n", io_status->u.Status);
540     return io_status->u.Status;
541 }
542
543 /***********************************************************************
544  *             FILE_AsyncWriteService      (INTERNAL)
545  *
546  *  This function is called while the client is waiting on the
547  *  server, so we can't make any server calls here.
548  */
549 static void FILE_AsyncWriteService(struct async_private *ovp)
550 {
551     async_fileio *fileio = (async_fileio *) ovp;
552     PIO_STATUS_BLOCK io_status = fileio->async.iosb;
553     int result;
554     int already = io_status->Information;
555
556     TRACE("(%p %p)\n",io_status,fileio->buffer);
557
558     /* write some data (non-blocking) */
559
560     if ( fileio->avail_mode )
561         result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
562     else
563     {
564         result = pwrite(ovp->fd, &fileio->buffer[already], fileio->count - already,
565                         fileio->offset + already);
566         if ((result < 0) && (errno == ESPIPE))
567             result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
568     }
569
570     if ((result < 0) && ((errno == EAGAIN) || (errno == EINTR)))
571     {
572         io_status->u.Status = STATUS_PENDING;
573         return;
574     }
575
576     /* check to see if the transfer is complete */
577     if (result < 0)
578     {
579         io_status->u.Status = FILE_GetNtStatus();
580         return;
581     }
582
583     io_status->Information += result;
584     io_status->u.Status = (io_status->Information < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
585     TRACE("wrote %d more bytes %ld/%d so far\n",result,io_status->Information,fileio->count);
586 }
587
588 /******************************************************************************
589  *  NtWriteFile                                 [NTDLL.@]
590  *  ZwWriteFile                                 [NTDLL.@]
591  *
592  * Write to an open file handle.
593  *
594  * PARAMS
595  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
596  *  Event         [I] Event to signal upon completion (or NULL)
597  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
598  *  ApcContext    [I] Context for ApcRoutine (or NULL)
599  *  IoStatusBlock [O] Receives information about the operation on return
600  *  Buffer        [I] Source for the data to write
601  *  Length        [I] Size of Buffer
602  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
603  *  Key           [O] Function unknown (may be NULL)
604  *
605  * RETURNS
606  *  Success: 0. IoStatusBlock is updated, and the Information member contains
607  *           The number of bytes written.
608  *  Failure: An NTSTATUS error code describing the error.
609  */
610 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
611                             PIO_APC_ROUTINE apc, void* apc_user,
612                             PIO_STATUS_BLOCK io_status, 
613                             const void* buffer, ULONG length,
614                             PLARGE_INTEGER offset, PULONG key)
615 {
616     int unix_handle, flags;
617
618     TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p)!\n",
619           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
620
621     io_status->Information = 0;
622     io_status->u.Status = wine_server_handle_to_fd( hFile, GENERIC_WRITE, &unix_handle, &flags );
623     if (io_status->u.Status) return io_status->u.Status;
624
625     if (flags & FD_FLAG_SEND_SHUTDOWN)
626     {
627         wine_server_release_fd( hFile, unix_handle );
628         return STATUS_PIPE_DISCONNECTED;
629     }
630
631     if (flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT))
632     {
633         async_fileio*   ovp;
634         NTSTATUS ret;
635
636         if (!(ovp = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(async_fileio))))
637         {
638             wine_server_release_fd( hFile, unix_handle );
639             return STATUS_NO_MEMORY;
640         }
641         ovp->async.ops = (apc ? &fileio_async_ops : &fileio_nocomp_async_ops );
642         ovp->async.handle = hFile;
643         ovp->async.fd = unix_handle;  /* FIXME */
644         ovp->async.type = ASYNC_TYPE_WRITE;
645         ovp->async.func = FILE_AsyncWriteService;
646         ovp->async.event = hEvent;
647         ovp->async.iosb = io_status;
648         ovp->count = length;
649         if (offset) {
650             ovp->offset = offset->QuadPart;
651             if (offset->u.HighPart && ovp->offset == offset->u.LowPart)
652                 FIXME("High part of offset is lost\n");
653         } else {
654             ovp->offset = 0;
655         }
656         ovp->apc = apc;
657         ovp->apc_user = apc_user;
658         ovp->buffer = (void*)buffer;
659         ovp->queue_apc_on_error = 0;
660         ovp->avail_mode = (flags & FD_FLAG_AVAILABLE);
661         NtResetEvent(hEvent, NULL);
662
663         io_status->Information = 0;
664         ret = register_new_async(&ovp->async);
665         if (ret != STATUS_SUCCESS)
666             return ret;
667         if (flags & FD_FLAG_TIMEOUT)
668         {
669             ret = NtWaitForSingleObject(hEvent, TRUE, NULL);
670             NtClose(hEvent);
671             if (ret != STATUS_USER_APC)
672                 ovp->queue_apc_on_error = 1;
673         }
674         else
675         {
676             LARGE_INTEGER   timeout;
677
678             /* let some APC be run, this will write as much data as possible */
679             timeout.u.LowPart = timeout.u.HighPart = 0;
680             ret = NtDelayExecution( TRUE, &timeout );
681             /* the apc didn't run and therefore the completion routine now
682              * needs to be sent errors.
683              * Note that there is no race between setting this flag and
684              * returning errors because apc's are run only during alertable
685              * waits */
686             if (ret != STATUS_USER_APC)
687                 ovp->queue_apc_on_error = 1;
688         }
689         return io_status->u.Status;
690     }
691
692     if (offset)
693     {
694         FILE_POSITION_INFORMATION   fpi;
695
696         fpi.CurrentByteOffset = *offset;
697         io_status->u.Status = NtSetInformationFile(hFile, io_status, &fpi, sizeof(fpi),
698                                                    FilePositionInformation);
699         if (io_status->u.Status)
700         {
701             wine_server_release_fd( hFile, unix_handle );
702             return io_status->u.Status;
703         }
704     }
705
706     /* synchronous file write */
707     while ((io_status->Information = write( unix_handle, buffer, length )) == -1)
708     {
709         if ((errno == EAGAIN) || (errno == EINTR)) continue;
710         if (errno == EFAULT) FIXME( "EFAULT handling broken for now\n" );
711         if (errno == ENOSPC) io_status->u.Status = STATUS_DISK_FULL;
712         else io_status->u.Status = FILE_GetNtStatus();
713         break;
714     }
715     wine_server_release_fd( hFile, unix_handle );
716     return io_status->u.Status;
717 }
718
719 /**************************************************************************
720  *              NtDeviceIoControlFile                   [NTDLL.@]
721  *              ZwDeviceIoControlFile                   [NTDLL.@]
722  *
723  * Perform an I/O control operation on an open file handle.
724  *
725  * PARAMS
726  *  DeviceHandle     [I] Handle returned from ZwOpenFile() or ZwCreateFile()
727  *  Event            [I] Event to signal upon completion (or NULL)
728  *  ApcRoutine       [I] Callback to call upon completion (or NULL)
729  *  ApcContext       [I] Context for ApcRoutine (or NULL)
730  *  IoStatusBlock    [O] Receives information about the operation on return
731  *  IoControlCode    [I] Control code for the operation to perform
732  *  InputBuffer      [I] Source for any input data required (or NULL)
733  *  InputBufferSize  [I] Size of InputBuffer
734  *  OutputBuffer     [O] Source for any output data returned (or NULL)
735  *  OutputBufferSize [I] Size of OutputBuffer
736  *
737  * RETURNS
738  *  Success: 0. IoStatusBlock is updated.
739  *  Failure: An NTSTATUS error code describing the error.
740  */
741 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE DeviceHandle, HANDLE hEvent,
742                                       PIO_APC_ROUTINE UserApcRoutine, 
743                                       PVOID UserApcContext,
744                                       PIO_STATUS_BLOCK IoStatusBlock,
745                                       ULONG IoControlCode,
746                                       PVOID InputBuffer,
747                                       ULONG InputBufferSize,
748                                       PVOID OutputBuffer,
749                                       ULONG OutputBufferSize)
750 {
751     TRACE("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx)\n",
752           DeviceHandle, hEvent, UserApcRoutine, UserApcContext,
753           IoStatusBlock, IoControlCode, 
754           InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize);
755
756     if (CDROM_DeviceIoControl(DeviceHandle, hEvent,
757                               UserApcRoutine, UserApcContext,
758                               IoStatusBlock, IoControlCode,
759                               InputBuffer, InputBufferSize,
760                               OutputBuffer, OutputBufferSize) == STATUS_NO_SUCH_DEVICE)
761     {
762         /* it wasn't a CDROM */
763         FIXME("Unimplemented dwIoControlCode=%08lx\n", IoControlCode);
764         IoStatusBlock->u.Status = STATUS_NOT_IMPLEMENTED;
765         IoStatusBlock->Information = 0;
766         if (hEvent) NtSetEvent(hEvent, NULL);
767     }
768     return IoStatusBlock->u.Status;
769 }
770
771 /******************************************************************************
772  * NtFsControlFile [NTDLL.@]
773  * ZwFsControlFile [NTDLL.@]
774  */
775 NTSTATUS WINAPI NtFsControlFile(
776         IN HANDLE DeviceHandle,
777         IN HANDLE Event OPTIONAL,
778         IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
779         IN PVOID ApcContext OPTIONAL,
780         OUT PIO_STATUS_BLOCK IoStatusBlock,
781         IN ULONG IoControlCode,
782         IN PVOID InputBuffer,
783         IN ULONG InputBufferSize,
784         OUT PVOID OutputBuffer,
785         IN ULONG OutputBufferSize)
786 {
787         FIXME("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx): stub\n",
788         DeviceHandle,Event,ApcRoutine,ApcContext,IoStatusBlock,IoControlCode,
789         InputBuffer,InputBufferSize,OutputBuffer,OutputBufferSize);
790         return 0;
791 }
792
793 /******************************************************************************
794  *  NtSetVolumeInformationFile          [NTDLL.@]
795  *  ZwSetVolumeInformationFile          [NTDLL.@]
796  *
797  * Set volume information for an open file handle.
798  *
799  * PARAMS
800  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
801  *  IoStatusBlock      [O] Receives information about the operation on return
802  *  FsInformation      [I] Source for volume information
803  *  Length             [I] Size of FsInformation
804  *  FsInformationClass [I] Type of volume information to set
805  *
806  * RETURNS
807  *  Success: 0. IoStatusBlock is updated.
808  *  Failure: An NTSTATUS error code describing the error.
809  */
810 NTSTATUS WINAPI NtSetVolumeInformationFile(
811         IN HANDLE FileHandle,
812         PIO_STATUS_BLOCK IoStatusBlock,
813         PVOID FsInformation,
814         ULONG Length,
815         FS_INFORMATION_CLASS FsInformationClass)
816 {
817         FIXME("(%p,%p,%p,0x%08lx,0x%08x) stub\n",
818         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
819         return 0;
820 }
821
822 /******************************************************************************
823  *  NtQueryInformationFile              [NTDLL.@]
824  *  ZwQueryInformationFile              [NTDLL.@]
825  *
826  * Get information about an open file handle.
827  *
828  * PARAMS
829  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
830  *  io       [O] Receives information about the operation on return
831  *  ptr      [O] Destination for file information
832  *  len      [I] Size of FileInformation
833  *  class    [I] Type of file information to get
834  *
835  * RETURNS
836  *  Success: 0. IoStatusBlock and FileInformation are updated.
837  *  Failure: An NTSTATUS error code describing the error.
838  */
839 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
840                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
841 {
842     static const size_t info_sizes[] =
843     {
844         0,
845         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
846         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
847         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
848         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
849         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
850         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
851         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
852         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
853         sizeof(FILE_NAME_INFORMATION)-sizeof(WCHAR),   /* FileNameInformation */
854         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
855         0,                                             /* FileLinkInformation */
856         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
857         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
858         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
859         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
860         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
861         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
862         sizeof(FILE_ALL_INFORMATION)-sizeof(WCHAR),    /* FileAllInformation */
863         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
864         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
865         0,                                             /* FileAlternateNameInformation */
866         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
867         0,                                             /* FilePipeInformation */
868         0,                                             /* FilePipeLocalInformation */
869         0,                                             /* FilePipeRemoteInformation */
870         0,                                             /* FileMailslotQueryInformation */
871         0,                                             /* FileMailslotSetInformation */
872         0,                                             /* FileCompressionInformation */
873         0,                                             /* FileObjectIdInformation */
874         0,                                             /* FileCompletionInformation */
875         0,                                             /* FileMoveClusterInformation */
876         0,                                             /* FileQuotaInformation */
877         0,                                             /* FileReparsePointInformation */
878         0,                                             /* FileNetworkOpenInformation */
879         0,                                             /* FileAttributeTagInformation */
880         0                                              /* FileTrackingInformation */
881     };
882
883     struct stat st;
884     int fd;
885
886     TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", hFile, io, ptr, len, class);
887
888     io->Information = 0;
889
890     if (class <= 0 || class >= FileMaximumInformation)
891         return io->u.Status = STATUS_INVALID_INFO_CLASS;
892     if (!info_sizes[class])
893     {
894         FIXME("Unsupported class (%d)\n", class);
895         return io->u.Status = STATUS_NOT_IMPLEMENTED;
896     }
897     if (len < info_sizes[class])
898         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
899
900     if ((io->u.Status = wine_server_handle_to_fd( hFile, 0, &fd, NULL )))
901         return io->u.Status;
902
903     switch (class)
904     {
905     case FileBasicInformation:
906         {
907             FILE_BASIC_INFORMATION *info = ptr;
908
909             if (fstat( fd, &st ) == -1)
910                 io->u.Status = FILE_GetNtStatus();
911             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
912                 io->u.Status = STATUS_INVALID_INFO_CLASS;
913             else
914             {
915                 if (S_ISDIR(st.st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
916                 else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
917                 if (!(st.st_mode & S_IWUSR)) info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
918                 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime);
919                 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime);
920                 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime);
921                 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime);
922             }
923         }
924         break;
925     case FileStandardInformation:
926         {
927             FILE_STANDARD_INFORMATION *info = ptr;
928
929             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
930             else
931             {
932                 if ((info->Directory = S_ISDIR(st.st_mode)))
933                 {
934                     info->AllocationSize.QuadPart = 0;
935                     info->EndOfFile.QuadPart      = 0;
936                     info->NumberOfLinks           = 1;
937                     info->DeletePending           = FALSE;
938                 }
939                 else
940                 {
941                     info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
942                     info->EndOfFile.QuadPart      = st.st_size;
943                     info->NumberOfLinks           = st.st_nlink;
944                     info->DeletePending           = FALSE; /* FIXME */
945                 }
946             }
947         }
948         break;
949     case FilePositionInformation:
950         {
951             FILE_POSITION_INFORMATION *info = ptr;
952             off_t res = lseek( fd, 0, SEEK_CUR );
953             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
954             else info->CurrentByteOffset.QuadPart = res;
955         }
956         break;
957     case FileInternalInformation:
958         {
959             FILE_INTERNAL_INFORMATION *info = ptr;
960
961             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
962             else info->IndexNumber.QuadPart = st.st_ino;
963         }
964         break;
965     case FileEaInformation:
966         {
967             FILE_EA_INFORMATION *info = ptr;
968             info->EaSize = 0;
969         }
970         break;
971     case FileEndOfFileInformation:
972         {
973             FILE_END_OF_FILE_INFORMATION *info = ptr;
974
975             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
976             else info->EndOfFile.QuadPart = S_ISDIR(st.st_mode) ? 0 : st.st_size;
977         }
978         break;
979     case FileAllInformation:
980         {
981             FILE_ALL_INFORMATION *info = ptr;
982
983             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
984             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
985                 io->u.Status = STATUS_INVALID_INFO_CLASS;
986             else
987             {
988                 if ((info->StandardInformation.Directory = S_ISDIR(st.st_mode)))
989                 {
990                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
991                     info->StandardInformation.AllocationSize.QuadPart = 0;
992                     info->StandardInformation.EndOfFile.QuadPart      = 0;
993                     info->StandardInformation.NumberOfLinks           = 1;
994                     info->StandardInformation.DeletePending           = FALSE;
995                 }
996                 else
997                 {
998                     info->BasicInformation.FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
999                     info->StandardInformation.AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1000                     info->StandardInformation.EndOfFile.QuadPart      = st.st_size;
1001                     info->StandardInformation.NumberOfLinks           = st.st_nlink;
1002                     info->StandardInformation.DeletePending           = FALSE; /* FIXME */
1003                 }
1004                 if (!(st.st_mode & S_IWUSR))
1005                     info->BasicInformation.FileAttributes |= FILE_ATTRIBUTE_READONLY;
1006                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.CreationTime);
1007                 RtlSecondsSince1970ToTime( st.st_mtime, &info->BasicInformation.LastWriteTime);
1008                 RtlSecondsSince1970ToTime( st.st_ctime, &info->BasicInformation.ChangeTime);
1009                 RtlSecondsSince1970ToTime( st.st_atime, &info->BasicInformation.LastAccessTime);
1010                 info->InternalInformation.IndexNumber.QuadPart = st.st_ino;
1011                 info->EaInformation.EaSize = 0;
1012                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1013                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1014                 info->ModeInformation.Mode = 0;  /* FIXME */
1015                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1016                 info->NameInformation.FileNameLength = 0;
1017                 io->Information = sizeof(*info) - sizeof(WCHAR);
1018             }
1019         }
1020         break;
1021     default:
1022         FIXME("Unsupported class (%d)\n", class);
1023         io->u.Status = STATUS_NOT_IMPLEMENTED;
1024         break;
1025     }
1026     wine_server_release_fd( hFile, fd );
1027     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
1028     return io->u.Status;
1029 }
1030
1031 /******************************************************************************
1032  *  NtSetInformationFile                [NTDLL.@]
1033  *  ZwSetInformationFile                [NTDLL.@]
1034  *
1035  * Set information about an open file handle.
1036  *
1037  * PARAMS
1038  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1039  *  io      [O] Receives information about the operation on return
1040  *  ptr     [I] Source for file information
1041  *  len     [I] Size of FileInformation
1042  *  class   [I] Type of file information to set
1043  *
1044  * RETURNS
1045  *  Success: 0. io is updated.
1046  *  Failure: An NTSTATUS error code describing the error.
1047  */
1048 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
1049                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
1050 {
1051     int fd;
1052
1053     TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", handle, io, ptr, len, class);
1054
1055     if ((io->u.Status = wine_server_handle_to_fd( handle, 0, &fd, NULL )))
1056         return io->u.Status;
1057
1058     io->u.Status = STATUS_SUCCESS;
1059     switch (class)
1060     {
1061     case FileBasicInformation:
1062         if (len >= sizeof(FILE_BASIC_INFORMATION))
1063         {
1064             struct stat st;
1065             const FILE_BASIC_INFORMATION *info = ptr;
1066
1067 #ifdef HAVE_FUTIMES
1068             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
1069             {
1070                 ULONGLONG sec, nsec;
1071                 struct timeval tv[2];
1072
1073                 if (!info->LastAccessTime.QuadPart || !info->LastWriteTime.QuadPart)
1074                 {
1075
1076                     tv[0].tv_sec = tv[0].tv_usec = 0;
1077                     tv[1].tv_sec = tv[1].tv_usec = 0;
1078                     if (!fstat( fd, &st ))
1079                     {
1080                         tv[0].tv_sec = st.st_atime;
1081                         tv[1].tv_sec = st.st_mtime;
1082                     }
1083                 }
1084                 if (info->LastAccessTime.QuadPart)
1085                 {
1086                     sec = RtlLargeIntegerDivide( info->LastAccessTime.QuadPart, 10000000, &nsec );
1087                     tv[0].tv_sec = sec - SECS_1601_TO_1970;
1088                     tv[0].tv_usec = (UINT)nsec / 10;
1089                 }
1090                 if (info->LastWriteTime.QuadPart)
1091                 {
1092                     sec = RtlLargeIntegerDivide( info->LastWriteTime.QuadPart, 10000000, &nsec );
1093                     tv[1].tv_sec = sec - SECS_1601_TO_1970;
1094                     tv[1].tv_usec = (UINT)nsec / 10;
1095                 }
1096                 if (futimes( fd, tv ) == -1) io->u.Status = FILE_GetNtStatus();
1097             }
1098 #endif  /* HAVE_FUTIMES */
1099             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
1100             {
1101                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1102                 else
1103                 {
1104                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
1105                     {
1106                         if (S_ISDIR( st.st_mode))
1107                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
1108                         else
1109                             st.st_mode &= ~0222; /* clear write permission bits */
1110                     }
1111                     else
1112                     {
1113                         /* add write permission only where we already have read permission */
1114                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
1115                     }
1116                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
1117                 }
1118             }
1119         }
1120         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1121         break;
1122
1123     case FilePositionInformation:
1124         if (len >= sizeof(FILE_POSITION_INFORMATION))
1125         {
1126             const FILE_POSITION_INFORMATION *info = ptr;
1127
1128             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
1129                 io->u.Status = FILE_GetNtStatus();
1130         }
1131         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1132         break;
1133
1134     case FileEndOfFileInformation:
1135         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
1136         {
1137             struct stat st;
1138             const FILE_END_OF_FILE_INFORMATION *info = ptr;
1139
1140             /* first try normal truncate */
1141             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1142
1143             /* now check for the need to extend the file */
1144             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
1145             {
1146                 static const char zero;
1147
1148                 /* extend the file one byte beyond the requested size and then truncate it */
1149                 /* this should work around ftruncate implementations that can't extend files */
1150                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
1151                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
1152             }
1153             io->u.Status = FILE_GetNtStatus();
1154         }
1155         else io->u.Status = STATUS_INVALID_PARAMETER_3;
1156         break;
1157
1158     default:
1159         FIXME("Unsupported class (%d)\n", class);
1160         io->u.Status = STATUS_NOT_IMPLEMENTED;
1161         break;
1162     }
1163     wine_server_release_fd( handle, fd );
1164     io->Information = 0;
1165     return io->u.Status;
1166 }
1167
1168
1169 /******************************************************************************
1170  *              NtQueryFullAttributesFile   (NTDLL.@)
1171  */
1172 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
1173                                            FILE_NETWORK_OPEN_INFORMATION *info )
1174 {
1175     ANSI_STRING unix_name;
1176     NTSTATUS status;
1177
1178     if (!(status = wine_nt_to_unix_file_name( attr->ObjectName, &unix_name, FILE_OPEN,
1179                                               !(attr->Attributes & OBJ_CASE_INSENSITIVE) )))
1180     {
1181         struct stat st;
1182
1183         if (stat( unix_name.Buffer, &st ) == -1)
1184             status = FILE_GetNtStatus();
1185         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1186             status = STATUS_INVALID_INFO_CLASS;
1187         else
1188         {
1189             if (S_ISDIR(st.st_mode))
1190             {
1191                 info->FileAttributes          = FILE_ATTRIBUTE_DIRECTORY;
1192                 info->AllocationSize.QuadPart = 0;
1193                 info->EndOfFile.QuadPart      = 0;
1194             }
1195             else
1196             {
1197                 info->FileAttributes          = FILE_ATTRIBUTE_ARCHIVE;
1198                 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1199                 info->EndOfFile.QuadPart      = st.st_size;
1200             }
1201             if (!(st.st_mode & S_IWUSR)) info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1202             RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1203             RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1204             RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1205             RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1206             if (DIR_is_hidden_file( attr->ObjectName ))
1207                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1208         }
1209         RtlFreeAnsiString( &unix_name );
1210     }
1211     else WARN("%s not found (%lx)\n", debugstr_us(attr->ObjectName), status );
1212     return status;
1213 }
1214
1215
1216 /******************************************************************************
1217  *              NtQueryAttributesFile   (NTDLL.@)
1218  *              ZwQueryAttributesFile   (NTDLL.@)
1219  */
1220 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
1221 {
1222     FILE_NETWORK_OPEN_INFORMATION full_info;
1223     NTSTATUS status;
1224
1225     if (!(status = NtQueryFullAttributesFile( attr, &full_info )))
1226     {
1227         info->CreationTime.QuadPart   = full_info.CreationTime.QuadPart;
1228         info->LastAccessTime.QuadPart = full_info.LastAccessTime.QuadPart;
1229         info->LastWriteTime.QuadPart  = full_info.LastWriteTime.QuadPart;
1230         info->ChangeTime.QuadPart     = full_info.ChangeTime.QuadPart;
1231         info->FileAttributes          = full_info.FileAttributes;
1232     }
1233     return status;
1234 }
1235
1236
1237 /******************************************************************************
1238  *  NtQueryVolumeInformationFile                [NTDLL.@]
1239  *  ZwQueryVolumeInformationFile                [NTDLL.@]
1240  *
1241  * Get volume information for an open file handle.
1242  *
1243  * PARAMS
1244  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1245  *  io          [O] Receives information about the operation on return
1246  *  buffer      [O] Destination for volume information
1247  *  length      [I] Size of FsInformation
1248  *  info_class  [I] Type of volume information to set
1249  *
1250  * RETURNS
1251  *  Success: 0. io and buffer are updated.
1252  *  Failure: An NTSTATUS error code describing the error.
1253  */
1254 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
1255                                               PVOID buffer, ULONG length,
1256                                               FS_INFORMATION_CLASS info_class )
1257 {
1258     int fd;
1259     struct stat st;
1260
1261     if ((io->u.Status = wine_server_handle_to_fd( handle, 0, &fd, NULL )) != STATUS_SUCCESS)
1262         return io->u.Status;
1263
1264     io->u.Status = STATUS_NOT_IMPLEMENTED;
1265     io->Information = 0;
1266
1267     switch( info_class )
1268     {
1269     case FileFsVolumeInformation:
1270         FIXME( "%p: volume info not supported\n", handle );
1271         break;
1272     case FileFsLabelInformation:
1273         FIXME( "%p: label info not supported\n", handle );
1274         break;
1275     case FileFsSizeInformation:
1276         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
1277             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1278         else
1279         {
1280             FILE_FS_SIZE_INFORMATION *info = buffer;
1281             struct statvfs stvfs;
1282
1283             if (fstat( fd, &st ) < 0)
1284             {
1285                 io->u.Status = FILE_GetNtStatus();
1286                 break;
1287             }
1288             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1289             {
1290                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
1291                 break;
1292             }
1293             if (fstatvfs( fd, &stvfs ) < 0) io->u.Status = FILE_GetNtStatus();
1294             else
1295             {
1296                 info->TotalAllocationUnits.QuadPart = stvfs.f_blocks;
1297                 info->AvailableAllocationUnits.QuadPart = stvfs.f_bavail;
1298                 info->SectorsPerAllocationUnit = 1;
1299                 info->BytesPerSector = stvfs.f_frsize;
1300                 io->Information = sizeof(*info);
1301                 io->u.Status = STATUS_SUCCESS;
1302             }
1303         }
1304         break;
1305     case FileFsDeviceInformation:
1306         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
1307             io->u.Status = STATUS_BUFFER_TOO_SMALL;
1308         else
1309         {
1310             FILE_FS_DEVICE_INFORMATION *info = buffer;
1311
1312             info->Characteristics = 0;
1313             if (fstat( fd, &st ) < 0)
1314             {
1315                 io->u.Status = FILE_GetNtStatus();
1316                 break;
1317             }
1318             if (S_ISCHR( st.st_mode ))
1319             {
1320                 info->DeviceType = FILE_DEVICE_UNKNOWN;
1321 #ifdef linux
1322                 switch(major(st.st_rdev))
1323                 {
1324                 case MEM_MAJOR:
1325                     info->DeviceType = FILE_DEVICE_NULL;
1326                     break;
1327                 case TTY_MAJOR:
1328                     info->DeviceType = FILE_DEVICE_SERIAL_PORT;
1329                     break;
1330                 case LP_MAJOR:
1331                     info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
1332                     break;
1333                 }
1334 #endif
1335             }
1336             else if (S_ISBLK( st.st_mode ))
1337             {
1338                 info->DeviceType = FILE_DEVICE_DISK;
1339             }
1340             else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
1341             {
1342                 info->DeviceType = FILE_DEVICE_NAMED_PIPE;
1343             }
1344             else  /* regular file or directory */
1345             {
1346 #if defined(linux) && defined(HAVE_FSTATFS)
1347                 struct statfs stfs;
1348
1349                 /* check for floppy disk */
1350                 if (major(st.st_dev) == FLOPPY_MAJOR)
1351                     info->Characteristics |= FILE_REMOVABLE_MEDIA;
1352
1353                 if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
1354                 switch (stfs.f_type)
1355                 {
1356                 case 0x9660:      /* iso9660 */
1357                 case 0x15013346:  /* udf */
1358                     info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1359                     info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
1360                     break;
1361                 case 0x6969:  /* nfs */
1362                 case 0x517B:  /* smbfs */
1363                 case 0x564c:  /* ncpfs */
1364                     info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
1365                     info->Characteristics |= FILE_REMOTE_DEVICE;
1366                     break;
1367                 case 0x01021994:  /* tmpfs */
1368                 case 0x28cd3d45:  /* cramfs */
1369                 case 0x1373:      /* devfs */
1370                 case 0x9fa0:      /* procfs */
1371                     info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
1372                     break;
1373                 default:
1374                     info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1375                     break;
1376                 }
1377 #elif defined (__APPLE__)
1378                 #include <IOKit/IOKitLib.h>
1379                 #include <CoreFoundation/CFNumber.h> /* for kCFBooleanTrue, kCFBooleanFalse */
1380                 #include <paths.h>
1381                 struct statfs stfs;
1382                 
1383                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1384                 
1385                 if (fstatfs( fd, &stfs ) < 0) break;
1386
1387                 /* stfs.f_type is reserved (always set to 0) so use IOKit */
1388                 kern_return_t kernResult = KERN_FAILURE; 
1389                 mach_port_t masterPort;
1390                 
1391                 char bsdName[6]; /* disk#\0 */
1392                 
1393                 strncpy(bsdName, stfs.f_mntfromname+strlen(_PATH_DEV) , 5);
1394                 bsdName[5] = 0;
1395
1396                 kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
1397
1398                 if (kernResult == KERN_SUCCESS)
1399                 {
1400                     CFMutableDictionaryRef matching = IOBSDNameMatching(masterPort, 0, bsdName);
1401                     
1402                     if (matching)
1403                     {
1404                         CFMutableDictionaryRef properties;
1405                         io_service_t devService = IOServiceGetMatchingService(masterPort, matching);
1406                         
1407                         if (IORegistryEntryCreateCFProperties(devService, 
1408                                                                 &properties,
1409                                                                 kCFAllocatorDefault, 0) != KERN_SUCCESS)
1410                                                                     break;
1411                         if ( CFEqual(
1412                                         CFDictionaryGetValue(properties, CFSTR("Removable")),
1413                                         kCFBooleanTrue)
1414                             ) info->Characteristics |= FILE_REMOVABLE_MEDIA;
1415                             
1416                         if ( CFEqual(
1417                                         CFDictionaryGetValue(properties, CFSTR("Writable")),
1418                                         kCFBooleanFalse)
1419                             ) info->Characteristics |= FILE_READ_ONLY_DEVICE;
1420
1421                         /*
1422                             NB : mounted disk image (.img/.dmg) don't provide specific type
1423                         */
1424                         CFStringRef type;
1425                         if ( (type = CFDictionaryGetValue(properties, CFSTR("Type"))) )
1426                         {
1427                             if ( CFStringCompare(type, CFSTR("CD-ROM"), 0) == kCFCompareEqualTo
1428                                 || CFStringCompare(type, CFSTR("DVD-ROM"), 0) == kCFCompareEqualTo
1429                             )
1430                             {
1431                                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
1432                             }
1433                         } 
1434                         
1435                         if (properties)
1436                             CFRelease(properties);
1437                     }
1438                 }
1439 #else
1440                 static int warned;
1441                 if (!warned++) FIXME( "device info not properly supported on this platform\n" );
1442                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
1443 #endif
1444                 info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
1445             }
1446             io->Information = sizeof(*info);
1447             io->u.Status = STATUS_SUCCESS;
1448         }
1449         break;
1450     case FileFsAttributeInformation:
1451         FIXME( "%p: attribute info not supported\n", handle );
1452         break;
1453     case FileFsControlInformation:
1454         FIXME( "%p: control info not supported\n", handle );
1455         break;
1456     case FileFsFullSizeInformation:
1457         FIXME( "%p: full size info not supported\n", handle );
1458         break;
1459     case FileFsObjectIdInformation:
1460         FIXME( "%p: object id info not supported\n", handle );
1461         break;
1462     case FileFsMaximumInformation:
1463         FIXME( "%p: maximum info not supported\n", handle );
1464         break;
1465     default:
1466         io->u.Status = STATUS_INVALID_PARAMETER;
1467         break;
1468     }
1469     wine_server_release_fd( handle, fd );
1470     return io->u.Status;
1471 }
1472
1473
1474 /******************************************************************
1475  *              NtFlushBuffersFile  (NTDLL.@)
1476  *
1477  * Flush any buffered data on an open file handle.
1478  *
1479  * PARAMS
1480  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1481  *  IoStatusBlock      [O] Receives information about the operation on return
1482  *
1483  * RETURNS
1484  *  Success: 0. IoStatusBlock is updated.
1485  *  Failure: An NTSTATUS error code describing the error.
1486  */
1487 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
1488 {
1489     NTSTATUS ret;
1490     HANDLE hEvent = NULL;
1491
1492     SERVER_START_REQ( flush_file )
1493     {
1494         req->handle = hFile;
1495         ret = wine_server_call( req );
1496         hEvent = reply->event;
1497     }
1498     SERVER_END_REQ;
1499     if (!ret && hEvent)
1500     {
1501         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
1502         NtClose( hEvent );
1503     }
1504     return ret;
1505 }
1506
1507 /******************************************************************
1508  *              NtLockFile       (NTDLL.@)
1509  *
1510  *
1511  */
1512 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
1513                             PIO_APC_ROUTINE apc, void* apc_user,
1514                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
1515                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
1516                             BOOLEAN exclusive )
1517 {
1518     NTSTATUS    ret;
1519     HANDLE      handle;
1520     BOOLEAN     async;
1521
1522     if (apc || io_status || key)
1523     {
1524         FIXME("Unimplemented yet parameter\n");
1525         return STATUS_NOT_IMPLEMENTED;
1526     }
1527
1528     for (;;)
1529     {
1530         SERVER_START_REQ( lock_file )
1531         {
1532             req->handle      = hFile;
1533             req->offset_low  = offset->u.LowPart;
1534             req->offset_high = offset->u.HighPart;
1535             req->count_low   = count->u.LowPart;
1536             req->count_high  = count->u.HighPart;
1537             req->shared      = !exclusive;
1538             req->wait        = !dont_wait;
1539             ret = wine_server_call( req );
1540             handle = reply->handle;
1541             async  = reply->overlapped;
1542         }
1543         SERVER_END_REQ;
1544         if (ret != STATUS_PENDING)
1545         {
1546             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
1547             return ret;
1548         }
1549
1550         if (async)
1551         {
1552             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
1553             if (handle) NtClose( handle );
1554             return STATUS_PENDING;
1555         }
1556         if (handle)
1557         {
1558             NtWaitForSingleObject( handle, FALSE, NULL );
1559             NtClose( handle );
1560         }
1561         else
1562         {
1563             LARGE_INTEGER time;
1564     
1565             /* Unix lock conflict, sleep a bit and retry */
1566             time.QuadPart = 100 * (ULONGLONG)10000;
1567             time.QuadPart = -time.QuadPart;
1568             NtDelayExecution( FALSE, &time );
1569         }
1570     }
1571 }
1572
1573
1574 /******************************************************************
1575  *              NtUnlockFile    (NTDLL.@)
1576  *
1577  *
1578  */
1579 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
1580                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
1581                               PULONG key )
1582 {
1583     NTSTATUS status;
1584
1585     TRACE( "%p %lx%08lx %lx%08lx\n",
1586            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
1587
1588     if (io_status || key)
1589     {
1590         FIXME("Unimplemented yet parameter\n");
1591         return STATUS_NOT_IMPLEMENTED;
1592     }
1593
1594     SERVER_START_REQ( unlock_file )
1595     {
1596         req->handle      = hFile;
1597         req->offset_low  = offset->u.LowPart;
1598         req->offset_high = offset->u.HighPart;
1599         req->count_low   = count->u.LowPart;
1600         req->count_high  = count->u.HighPart;
1601         status = wine_server_call( req );
1602     }
1603     SERVER_END_REQ;
1604     return status;
1605 }
1606
1607 /******************************************************************
1608  *              NtCreateNamedPipeFile    (NTDLL.@)
1609  *
1610  *
1611  */
1612 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE FileHandle, ULONG DesiredAccess,
1613      POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock,
1614      ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions,
1615      ULONG NamedPipeType, ULONG ReadMode, ULONG CompletionMode,
1616      ULONG MaximumInstances, ULONG InboundQuota, ULONG OutboundQuota,
1617      PLARGE_INTEGER DefaultTimeout)
1618 {
1619     FIXME("(%p %lx %p %p %lx %ld %lx %ld %ld %ld %ld %ld %ld %p): stub\n",
1620           FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock,
1621           ShareAccess, CreateDisposition, CreateOptions, NamedPipeType,
1622           ReadMode, CompletionMode, MaximumInstances, InboundQuota,
1623           OutboundQuota, DefaultTimeout);
1624     return STATUS_NOT_IMPLEMENTED;
1625 }
1626
1627 /******************************************************************
1628  *              NtDeleteFile    (NTDLL.@)
1629  *
1630  *
1631  */
1632 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
1633 {
1634     FIXME("%p\n", ObjectAttributes);
1635     return STATUS_NOT_IMPLEMENTED;
1636 }
1637
1638 /******************************************************************
1639  *              NtCancelIoFile    (NTDLL.@)
1640  *
1641  *
1642  */
1643 NTSTATUS WINAPI NtCancelIoFile( HANDLE FileHandle,
1644     PIO_STATUS_BLOCK IoStatusBlock)
1645 {
1646     FIXME("%p %p\n", FileHandle, IoStatusBlock );
1647     return STATUS_NOT_IMPLEMENTED;
1648 }