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