include: Add constants for CryptProtectMemory/CryptUnprotectMemory.
[wine.git] / dlls / ntdll / file.c
blob907c2aa0682f03e47b878af6bb44040e7e95e04b
1 /*
2 * Copyright 1999, 2000 Juergen Schmied
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.
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.
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
19 #include "config.h"
20 #include "wine/port.h"
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_LINUX_MAJOR_H
31 # include <linux/major.h>
32 #endif
33 #ifdef HAVE_SYS_STATVFS_H
34 # include <sys/statvfs.h>
35 #endif
36 #ifdef HAVE_SYS_PARAM_H
37 # include <sys/param.h>
38 #endif
39 #ifdef HAVE_SYS_SYSCALL_H
40 # include <sys/syscall.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_SYS_FILIO_H
49 # include <sys/filio.h>
50 #endif
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #endif
54 #ifdef HAVE_SYS_POLL_H
55 #include <sys/poll.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
59 #endif
60 #ifdef MAJOR_IN_MKDEV
61 # include <sys/mkdev.h>
62 #elif defined(MAJOR_IN_SYSMACROS)
63 # include <sys/sysmacros.h>
64 #endif
65 #ifdef HAVE_UTIME_H
66 # include <utime.h>
67 #endif
68 #ifdef HAVE_SYS_VFS_H
69 /* Work around a conflict with Solaris' system list defined in sys/list.h. */
70 #define list SYSLIST
71 #define list_next SYSLIST_NEXT
72 #define list_prev SYSLIST_PREV
73 #define list_head SYSLIST_HEAD
74 #define list_tail SYSLIST_TAIL
75 #define list_move_tail SYSLIST_MOVE_TAIL
76 #define list_remove SYSLIST_REMOVE
77 # include <sys/vfs.h>
78 #undef list
79 #undef list_next
80 #undef list_prev
81 #undef list_head
82 #undef list_tail
83 #undef list_move_tail
84 #undef list_remove
85 #endif
86 #ifdef HAVE_SYS_MOUNT_H
87 # include <sys/mount.h>
88 #endif
89 #ifdef HAVE_SYS_STATFS_H
90 # include <sys/statfs.h>
91 #endif
92 #ifdef HAVE_TERMIOS_H
93 #include <termios.h>
94 #endif
95 #ifdef HAVE_VALGRIND_MEMCHECK_H
96 # include <valgrind/memcheck.h>
97 #endif
99 #include "ntstatus.h"
100 #define WIN32_NO_STATUS
101 #define NONAMELESSUNION
102 #include "wine/unicode.h"
103 #include "wine/debug.h"
104 #include "wine/server.h"
105 #include "ntdll_misc.h"
107 #include "winternl.h"
108 #include "winioctl.h"
109 #include "ddk/ntddk.h"
110 #include "ddk/ntddser.h"
112 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
113 WINE_DECLARE_DEBUG_CHANNEL(winediag);
115 mode_t FILE_umask = 0;
117 #define SECSPERDAY 86400
118 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
120 #define FILE_WRITE_TO_END_OF_FILE ((LONGLONG)-1)
121 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
123 static const WCHAR ntfsW[] = {'N','T','F','S'};
125 /* fetch the attributes of a file */
126 static inline ULONG get_file_attributes( const struct stat *st )
128 ULONG attr;
130 if (S_ISDIR(st->st_mode))
131 attr = FILE_ATTRIBUTE_DIRECTORY;
132 else
133 attr = FILE_ATTRIBUTE_ARCHIVE;
134 if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
135 attr |= FILE_ATTRIBUTE_READONLY;
136 return attr;
139 /* get the stat info and file attributes for a file (by file descriptor) */
140 int fd_get_file_info( int fd, struct stat *st, ULONG *attr )
142 int ret;
144 *attr = 0;
145 ret = fstat( fd, st );
146 if (ret == -1) return ret;
147 *attr |= get_file_attributes( st );
148 return ret;
151 /* get the stat info and file attributes for a file (by name) */
152 int get_file_info( const char *path, struct stat *st, ULONG *attr )
154 int ret;
156 *attr = 0;
157 ret = lstat( path, st );
158 if (ret == -1) return ret;
159 if (S_ISLNK( st->st_mode ))
161 ret = stat( path, st );
162 if (ret == -1) return ret;
163 /* is a symbolic link and a directory, consider these "reparse points" */
164 if (S_ISDIR( st->st_mode )) *attr |= FILE_ATTRIBUTE_REPARSE_POINT;
166 *attr |= get_file_attributes( st );
167 return ret;
170 /**************************************************************************
171 * FILE_CreateFile (internal)
172 * Open a file.
174 * Parameter set fully identical with NtCreateFile
176 static NTSTATUS FILE_CreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
177 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
178 ULONG attributes, ULONG sharing, ULONG disposition,
179 ULONG options, PVOID ea_buffer, ULONG ea_length )
181 ANSI_STRING unix_name;
182 BOOL created = FALSE;
184 TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
185 "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
186 handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
187 attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
188 attributes, sharing, disposition, options, ea_buffer, ea_length );
190 if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
192 if (alloc_size) FIXME( "alloc_size not supported\n" );
194 if (options & FILE_OPEN_BY_FILE_ID)
195 io->u.Status = file_id_to_unix_file_name( attr, &unix_name );
196 else
197 io->u.Status = nt_to_unix_file_name_attr( attr, &unix_name, disposition );
199 if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
201 SERVER_START_REQ( open_file_object )
203 req->access = access;
204 req->attributes = attr->Attributes;
205 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
206 req->sharing = sharing;
207 req->options = options;
208 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
209 io->u.Status = wine_server_call( req );
210 *handle = wine_server_ptr_handle( reply->handle );
212 SERVER_END_REQ;
213 if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
214 return io->u.Status;
217 if (io->u.Status == STATUS_NO_SUCH_FILE &&
218 disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
220 created = TRUE;
221 io->u.Status = STATUS_SUCCESS;
224 if (io->u.Status == STATUS_SUCCESS)
226 static UNICODE_STRING empty_string;
227 OBJECT_ATTRIBUTES unix_attr = *attr;
228 data_size_t len;
229 struct object_attributes *objattr;
231 unix_attr.ObjectName = &empty_string; /* we send the unix name instead */
232 if ((io->u.Status = alloc_object_attributes( &unix_attr, &objattr, &len )))
234 RtlFreeAnsiString( &unix_name );
235 return io->u.Status;
238 SERVER_START_REQ( create_file )
240 req->access = access;
241 req->sharing = sharing;
242 req->create = disposition;
243 req->options = options;
244 req->attrs = attributes;
245 wine_server_add_data( req, objattr, len );
246 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
247 io->u.Status = wine_server_call( req );
248 *handle = wine_server_ptr_handle( reply->handle );
250 SERVER_END_REQ;
251 RtlFreeHeap( GetProcessHeap(), 0, objattr );
252 RtlFreeAnsiString( &unix_name );
254 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
256 if (io->u.Status == STATUS_SUCCESS)
258 if (created) io->Information = FILE_CREATED;
259 else switch(disposition)
261 case FILE_SUPERSEDE:
262 io->Information = FILE_SUPERSEDED;
263 break;
264 case FILE_CREATE:
265 io->Information = FILE_CREATED;
266 break;
267 case FILE_OPEN:
268 case FILE_OPEN_IF:
269 io->Information = FILE_OPENED;
270 break;
271 case FILE_OVERWRITE:
272 case FILE_OVERWRITE_IF:
273 io->Information = FILE_OVERWRITTEN;
274 break;
277 else if (io->u.Status == STATUS_TOO_MANY_OPENED_FILES)
279 static int once;
280 if (!once++) ERR_(winediag)( "Too many open files, ulimit -n probably needs to be increased\n" );
283 return io->u.Status;
286 /**************************************************************************
287 * NtOpenFile [NTDLL.@]
288 * ZwOpenFile [NTDLL.@]
290 * Open a file.
292 * PARAMS
293 * handle [O] Variable that receives the file handle on return
294 * access [I] Access desired by the caller to the file
295 * attr [I] Structure describing the file to be opened
296 * io [O] Receives details about the result of the operation
297 * sharing [I] Type of shared access the caller requires
298 * options [I] Options for the file open
300 * RETURNS
301 * Success: 0. FileHandle and IoStatusBlock are updated.
302 * Failure: An NTSTATUS error code describing the error.
304 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
305 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
306 ULONG sharing, ULONG options )
308 return FILE_CreateFile( handle, access, attr, io, NULL, 0,
309 sharing, FILE_OPEN, options, NULL, 0 );
312 /**************************************************************************
313 * NtCreateFile [NTDLL.@]
314 * ZwCreateFile [NTDLL.@]
316 * Either create a new file or directory, or open an existing file, device,
317 * directory or volume.
319 * PARAMS
320 * handle [O] Points to a variable which receives the file handle on return
321 * access [I] Desired access to the file
322 * attr [I] Structure describing the file
323 * io [O] Receives information about the operation on return
324 * alloc_size [I] Initial size of the file in bytes
325 * attributes [I] Attributes to create the file with
326 * sharing [I] Type of shared access the caller would like to the file
327 * disposition [I] Specifies what to do, depending on whether the file already exists
328 * options [I] Options for creating a new file
329 * ea_buffer [I] Pointer to an extended attributes buffer
330 * ea_length [I] Length of ea_buffer
332 * RETURNS
333 * Success: 0. handle and io are updated.
334 * Failure: An NTSTATUS error code describing the error.
336 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
337 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
338 ULONG attributes, ULONG sharing, ULONG disposition,
339 ULONG options, PVOID ea_buffer, ULONG ea_length )
341 return FILE_CreateFile( handle, access, attr, io, alloc_size, attributes,
342 sharing, disposition, options, ea_buffer, ea_length );
345 /***********************************************************************
346 * Asynchronous file I/O *
349 struct async_fileio
351 struct async_fileio *next;
352 HANDLE handle;
353 PIO_APC_ROUTINE apc;
354 void *apc_arg;
357 struct async_fileio_read
359 struct async_fileio io;
360 char* buffer;
361 unsigned int already;
362 unsigned int count;
363 BOOL avail_mode;
366 struct async_fileio_write
368 struct async_fileio io;
369 const char *buffer;
370 unsigned int already;
371 unsigned int count;
374 struct async_irp
376 struct async_fileio io;
377 HANDLE event; /* async event */
378 void *buffer; /* buffer for output */
379 ULONG size; /* size of buffer */
382 static struct async_fileio *fileio_freelist;
384 static void release_fileio( struct async_fileio *io )
386 for (;;)
388 struct async_fileio *next = fileio_freelist;
389 io->next = next;
390 if (interlocked_cmpxchg_ptr( (void **)&fileio_freelist, io, next ) == next) return;
394 static struct async_fileio *alloc_fileio( DWORD size, HANDLE handle, PIO_APC_ROUTINE apc, void *arg )
396 /* first free remaining previous fileinfos */
398 struct async_fileio *io = interlocked_xchg_ptr( (void **)&fileio_freelist, NULL );
400 while (io)
402 struct async_fileio *next = io->next;
403 RtlFreeHeap( GetProcessHeap(), 0, io );
404 io = next;
407 if ((io = RtlAllocateHeap( GetProcessHeap(), 0, size )))
409 io->handle = handle;
410 io->apc = apc;
411 io->apc_arg = arg;
413 return io;
416 /* callback for irp async I/O completion */
417 static NTSTATUS irp_completion( void *user, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc, void **arg )
419 struct async_irp *async = user;
421 if (status == STATUS_ALERTED)
423 SERVER_START_REQ( get_async_result )
425 req->user_arg = wine_server_client_ptr( async );
426 wine_server_set_reply( req, async->buffer, async->size );
427 status = wine_server_call( req );
428 if (status != STATUS_PENDING) io->Information = reply->size;
430 SERVER_END_REQ;
432 if (status != STATUS_PENDING)
434 io->u.Status = status;
435 *apc = async->io.apc;
436 *arg = async->io.apc_arg;
437 release_fileio( &async->io );
439 return status;
442 /***********************************************************************
443 * FILE_GetNtStatus(void)
445 * Retrieve the Nt Status code from errno.
446 * Try to be consistent with FILE_SetDosError().
448 NTSTATUS FILE_GetNtStatus(void)
450 int err = errno;
452 TRACE( "errno = %d\n", errno );
453 switch (err)
455 case EAGAIN: return STATUS_SHARING_VIOLATION;
456 case EBADF: return STATUS_INVALID_HANDLE;
457 case EBUSY: return STATUS_DEVICE_BUSY;
458 case ENOSPC: return STATUS_DISK_FULL;
459 case EPERM:
460 case EROFS:
461 case EACCES: return STATUS_ACCESS_DENIED;
462 case ENOTDIR: return STATUS_OBJECT_PATH_NOT_FOUND;
463 case ENOENT: return STATUS_OBJECT_NAME_NOT_FOUND;
464 case EISDIR: return STATUS_FILE_IS_A_DIRECTORY;
465 case EMFILE:
466 case ENFILE: return STATUS_TOO_MANY_OPENED_FILES;
467 case EINVAL: return STATUS_INVALID_PARAMETER;
468 case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
469 case EPIPE: return STATUS_PIPE_DISCONNECTED;
470 case EIO: return STATUS_DEVICE_NOT_READY;
471 #ifdef ENOMEDIUM
472 case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
473 #endif
474 case ENXIO: return STATUS_NO_SUCH_DEVICE;
475 case ENOTTY:
476 case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
477 case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
478 case EFAULT: return STATUS_ACCESS_VIOLATION;
479 case ESPIPE: return STATUS_ILLEGAL_FUNCTION;
480 #ifdef ETIME /* Missing on FreeBSD */
481 case ETIME: return STATUS_IO_TIMEOUT;
482 #endif
483 case ENOEXEC: /* ?? */
484 case EEXIST: /* ?? */
485 default:
486 FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
487 return STATUS_UNSUCCESSFUL;
491 /***********************************************************************
492 * FILE_AsyncReadService (INTERNAL)
494 static NTSTATUS FILE_AsyncReadService( void *user, IO_STATUS_BLOCK *iosb,
495 NTSTATUS status, void **apc, void **arg )
497 struct async_fileio_read *fileio = user;
498 int fd, needs_close, result;
500 switch (status)
502 case STATUS_ALERTED: /* got some new data */
503 /* check to see if the data is ready (non-blocking) */
504 if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
505 &needs_close, NULL, NULL )))
506 break;
508 result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
509 if (needs_close) close( fd );
511 if (result < 0)
513 if (errno == EAGAIN || errno == EINTR)
514 status = STATUS_PENDING;
515 else /* check to see if the transfer is complete */
516 status = FILE_GetNtStatus();
518 else if (result == 0)
520 status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
522 else
524 fileio->already += result;
525 if (fileio->already >= fileio->count || fileio->avail_mode)
526 status = STATUS_SUCCESS;
527 else
528 status = STATUS_PENDING;
530 break;
532 case STATUS_TIMEOUT:
533 case STATUS_IO_TIMEOUT:
534 if (fileio->already) status = STATUS_SUCCESS;
535 break;
537 if (status != STATUS_PENDING)
539 iosb->u.Status = status;
540 iosb->Information = fileio->already;
541 *apc = fileio->io.apc;
542 *arg = fileio->io.apc_arg;
543 release_fileio( &fileio->io );
545 return status;
548 /* do a read call through the server */
549 static NTSTATUS server_read_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
550 IO_STATUS_BLOCK *io, void *buffer, ULONG size,
551 LARGE_INTEGER *offset, ULONG *key )
553 struct async_irp *async;
554 NTSTATUS status;
555 HANDLE wait_handle;
556 ULONG options;
557 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
559 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
560 return STATUS_NO_MEMORY;
562 async->event = event;
563 async->buffer = buffer;
564 async->size = size;
566 SERVER_START_REQ( read )
568 req->blocking = !apc && !event && !cvalue;
569 req->async.handle = wine_server_obj_handle( handle );
570 req->async.callback = wine_server_client_ptr( irp_completion );
571 req->async.iosb = wine_server_client_ptr( io );
572 req->async.arg = wine_server_client_ptr( async );
573 req->async.event = wine_server_obj_handle( event );
574 req->async.cvalue = cvalue;
575 req->pos = offset ? offset->QuadPart : 0;
576 wine_server_set_reply( req, buffer, size );
577 status = wine_server_call( req );
578 wait_handle = wine_server_ptr_handle( reply->wait );
579 options = reply->options;
580 if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
582 SERVER_END_REQ;
584 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
586 if (wait_handle)
588 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
589 status = io->u.Status;
590 NtClose( wait_handle );
593 return status;
596 /* do a write call through the server */
597 static NTSTATUS server_write_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
598 IO_STATUS_BLOCK *io, const void *buffer, ULONG size,
599 LARGE_INTEGER *offset, ULONG *key )
601 struct async_irp *async;
602 NTSTATUS status;
603 HANDLE wait_handle;
604 ULONG options;
605 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
607 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
608 return STATUS_NO_MEMORY;
610 async->event = event;
611 async->buffer = NULL;
612 async->size = 0;
614 SERVER_START_REQ( write )
616 req->blocking = !apc && !event && !cvalue;
617 req->async.handle = wine_server_obj_handle( handle );
618 req->async.callback = wine_server_client_ptr( irp_completion );
619 req->async.iosb = wine_server_client_ptr( io );
620 req->async.arg = wine_server_client_ptr( async );
621 req->async.event = wine_server_obj_handle( event );
622 req->async.cvalue = cvalue;
623 req->pos = offset ? offset->QuadPart : 0;
624 wine_server_add_data( req, buffer, size );
625 status = wine_server_call( req );
626 wait_handle = wine_server_ptr_handle( reply->wait );
627 options = reply->options;
628 if (status != STATUS_PENDING) io->Information = reply->size;
630 SERVER_END_REQ;
632 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
634 if (wait_handle)
636 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
637 status = io->u.Status;
638 NtClose( wait_handle );
641 return status;
644 struct io_timeouts
646 int interval; /* max interval between two bytes */
647 int total; /* total timeout for the whole operation */
648 int end_time; /* absolute time of end of operation */
651 /* retrieve the I/O timeouts to use for a given handle */
652 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
653 struct io_timeouts *timeouts )
655 NTSTATUS status = STATUS_SUCCESS;
657 timeouts->interval = timeouts->total = -1;
659 switch(type)
661 case FD_TYPE_SERIAL:
663 /* GetCommTimeouts */
664 SERIAL_TIMEOUTS st;
665 IO_STATUS_BLOCK io;
667 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
668 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
669 if (status) break;
671 if (is_read)
673 if (st.ReadIntervalTimeout)
674 timeouts->interval = st.ReadIntervalTimeout;
676 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
678 timeouts->total = st.ReadTotalTimeoutConstant;
679 if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
680 timeouts->total += count * st.ReadTotalTimeoutMultiplier;
682 else if (st.ReadIntervalTimeout == MAXDWORD)
683 timeouts->interval = timeouts->total = 0;
685 else /* write */
687 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
689 timeouts->total = st.WriteTotalTimeoutConstant;
690 if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
691 timeouts->total += count * st.WriteTotalTimeoutMultiplier;
695 break;
696 case FD_TYPE_MAILSLOT:
697 if (is_read)
699 timeouts->interval = 0; /* return as soon as we got something */
700 SERVER_START_REQ( set_mailslot_info )
702 req->handle = wine_server_obj_handle( handle );
703 req->flags = 0;
704 if (!(status = wine_server_call( req )) &&
705 reply->read_timeout != TIMEOUT_INFINITE)
706 timeouts->total = reply->read_timeout / -10000;
708 SERVER_END_REQ;
710 break;
711 case FD_TYPE_SOCKET:
712 case FD_TYPE_PIPE:
713 case FD_TYPE_CHAR:
714 if (is_read) timeouts->interval = 0; /* return as soon as we got something */
715 break;
716 default:
717 break;
719 if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
720 return STATUS_SUCCESS;
724 /* retrieve the timeout for the next wait, in milliseconds */
725 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
727 int ret = -1;
729 if (timeouts->total != -1)
731 ret = timeouts->end_time - NtGetTickCount();
732 if (ret < 0) ret = 0;
734 if (already && timeouts->interval != -1)
736 if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
738 return ret;
742 /* retrieve the avail_mode flag for async reads */
743 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
745 NTSTATUS status = STATUS_SUCCESS;
747 switch(type)
749 case FD_TYPE_SERIAL:
751 /* GetCommTimeouts */
752 SERIAL_TIMEOUTS st;
753 IO_STATUS_BLOCK io;
755 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
756 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
757 if (status) break;
758 *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
759 !st.ReadTotalTimeoutConstant &&
760 st.ReadIntervalTimeout == MAXDWORD);
762 break;
763 case FD_TYPE_MAILSLOT:
764 case FD_TYPE_SOCKET:
765 case FD_TYPE_PIPE:
766 case FD_TYPE_CHAR:
767 *avail_mode = TRUE;
768 break;
769 default:
770 *avail_mode = FALSE;
771 break;
773 return status;
776 /* register an async I/O for a file read; helper for NtReadFile */
777 static NTSTATUS register_async_file_read( HANDLE handle, HANDLE event,
778 PIO_APC_ROUTINE apc, void *apc_user,
779 IO_STATUS_BLOCK *iosb, void *buffer,
780 ULONG already, ULONG length, BOOL avail_mode )
782 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
783 struct async_fileio_read *fileio;
784 NTSTATUS status;
786 if (!(fileio = (struct async_fileio_read *)alloc_fileio( sizeof(*fileio), handle, apc, apc_user )))
787 return STATUS_NO_MEMORY;
789 fileio->already = already;
790 fileio->count = length;
791 fileio->buffer = buffer;
792 fileio->avail_mode = avail_mode;
794 SERVER_START_REQ( register_async )
796 req->type = ASYNC_TYPE_READ;
797 req->count = length;
798 req->async.handle = wine_server_obj_handle( handle );
799 req->async.event = wine_server_obj_handle( event );
800 req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
801 req->async.iosb = wine_server_client_ptr( iosb );
802 req->async.arg = wine_server_client_ptr( fileio );
803 req->async.cvalue = cvalue;
804 status = wine_server_call( req );
806 SERVER_END_REQ;
808 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
809 return status;
813 /******************************************************************************
814 * NtReadFile [NTDLL.@]
815 * ZwReadFile [NTDLL.@]
817 * Read from an open file handle.
819 * PARAMS
820 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
821 * Event [I] Event to signal upon completion (or NULL)
822 * ApcRoutine [I] Callback to call upon completion (or NULL)
823 * ApcContext [I] Context for ApcRoutine (or NULL)
824 * IoStatusBlock [O] Receives information about the operation on return
825 * Buffer [O] Destination for the data read
826 * Length [I] Size of Buffer
827 * ByteOffset [O] Destination for the new file pointer position (or NULL)
828 * Key [O] Function unknown (may be NULL)
830 * RETURNS
831 * Success: 0. IoStatusBlock is updated, and the Information member contains
832 * The number of bytes read.
833 * Failure: An NTSTATUS error code describing the error.
835 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
836 PIO_APC_ROUTINE apc, void* apc_user,
837 PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
838 PLARGE_INTEGER offset, PULONG key)
840 int result, unix_handle, needs_close;
841 unsigned int options;
842 struct io_timeouts timeouts;
843 NTSTATUS status;
844 ULONG total = 0;
845 enum server_fd_type type;
846 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
847 BOOL send_completion = FALSE, async_read, timeout_init_done = FALSE;
849 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
850 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
852 if (!io_status) return STATUS_ACCESS_VIOLATION;
854 status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
855 &needs_close, &type, &options );
856 if (status && status != STATUS_BAD_DEVICE_TYPE) return status;
858 if (!virtual_check_buffer_for_write( buffer, length )) return STATUS_ACCESS_VIOLATION;
860 if (status == STATUS_BAD_DEVICE_TYPE)
861 return server_read_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
863 async_read = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
865 if (type == FD_TYPE_FILE)
867 if (async_read && (!offset || offset->QuadPart < 0))
869 status = STATUS_INVALID_PARAMETER;
870 goto done;
873 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
875 /* async I/O doesn't make sense on regular files */
876 while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
878 if (errno != EINTR)
880 status = FILE_GetNtStatus();
881 goto done;
884 if (!async_read)
885 /* update file pointer position */
886 lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
888 total = result;
889 status = (total || !length) ? STATUS_SUCCESS : STATUS_END_OF_FILE;
890 goto done;
893 else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
895 if (async_read && (!offset || offset->QuadPart < 0))
897 status = STATUS_INVALID_PARAMETER;
898 goto done;
902 if (type == FD_TYPE_SERIAL && async_read && length)
904 /* an asynchronous serial port read with a read interval timeout needs to
905 skip the synchronous read to make sure that the server starts the read
906 interval timer after the first read */
907 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts ))) goto err;
908 if (timeouts.interval)
910 status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
911 buffer, total, length, FALSE );
912 goto err;
916 for (;;)
918 if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
920 total += result;
921 if (!result || total == length)
923 if (total)
925 status = STATUS_SUCCESS;
926 goto done;
928 switch (type)
930 case FD_TYPE_FILE:
931 case FD_TYPE_CHAR:
932 case FD_TYPE_DEVICE:
933 status = length ? STATUS_END_OF_FILE : STATUS_SUCCESS;
934 goto done;
935 case FD_TYPE_SERIAL:
936 if (!length)
938 status = STATUS_SUCCESS;
939 goto done;
941 break;
942 default:
943 status = STATUS_PIPE_BROKEN;
944 goto done;
947 else if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
949 else if (errno != EAGAIN)
951 if (errno == EINTR) continue;
952 if (!total) status = FILE_GetNtStatus();
953 goto done;
956 if (async_read)
958 BOOL avail_mode;
960 if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
961 goto err;
962 if (total && avail_mode)
964 status = STATUS_SUCCESS;
965 goto done;
967 status = register_async_file_read( hFile, hEvent, apc, apc_user, io_status,
968 buffer, total, length, avail_mode );
969 goto err;
971 else /* synchronous read, wait for the fd to become ready */
973 struct pollfd pfd;
974 int ret, timeout;
976 if (!timeout_init_done)
978 timeout_init_done = TRUE;
979 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
980 goto err;
981 if (hEvent) NtResetEvent( hEvent, NULL );
983 timeout = get_next_io_timeout( &timeouts, total );
985 pfd.fd = unix_handle;
986 pfd.events = POLLIN;
988 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
990 if (total) /* return with what we got so far */
991 status = STATUS_SUCCESS;
992 else
993 status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
994 goto done;
996 if (ret == -1 && errno != EINTR)
998 status = FILE_GetNtStatus();
999 goto done;
1001 /* will now restart the read */
1005 done:
1006 send_completion = cvalue != 0;
1008 err:
1009 if (needs_close) close( unix_handle );
1010 if (status == STATUS_SUCCESS || (status == STATUS_END_OF_FILE && !async_read))
1012 io_status->u.Status = status;
1013 io_status->Information = total;
1014 TRACE("= SUCCESS (%u)\n", total);
1015 if (hEvent) NtSetEvent( hEvent, NULL );
1016 if (apc && !status) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1017 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1019 else
1021 TRACE("= 0x%08x\n", status);
1022 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1025 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1027 return status;
1031 /******************************************************************************
1032 * NtReadFileScatter [NTDLL.@]
1033 * ZwReadFileScatter [NTDLL.@]
1035 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1036 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1037 ULONG length, PLARGE_INTEGER offset, PULONG key )
1039 int result, unix_handle, needs_close;
1040 unsigned int options;
1041 NTSTATUS status;
1042 ULONG pos = 0, total = 0;
1043 enum server_fd_type type;
1044 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1045 BOOL send_completion = FALSE;
1047 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1048 file, event, apc, apc_user, io_status, segments, length, offset, key);
1050 if (length % page_size) return STATUS_INVALID_PARAMETER;
1051 if (!io_status) return STATUS_ACCESS_VIOLATION;
1053 status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
1054 &needs_close, &type, &options );
1055 if (status) return status;
1057 if ((type != FD_TYPE_FILE) ||
1058 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1059 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1061 status = STATUS_INVALID_PARAMETER;
1062 goto error;
1065 while (length)
1067 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1068 result = pread( unix_handle, (char *)segments->Buffer + pos,
1069 page_size - pos, offset->QuadPart + total );
1070 else
1071 result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1073 if (result == -1)
1075 if (errno == EINTR) continue;
1076 status = FILE_GetNtStatus();
1077 break;
1079 if (!result)
1081 status = STATUS_END_OF_FILE;
1082 break;
1084 total += result;
1085 length -= result;
1086 if ((pos += result) == page_size)
1088 pos = 0;
1089 segments++;
1093 send_completion = cvalue != 0;
1095 error:
1096 if (needs_close) close( unix_handle );
1097 if (status == STATUS_SUCCESS)
1099 io_status->u.Status = status;
1100 io_status->Information = total;
1101 TRACE("= SUCCESS (%u)\n", total);
1102 if (event) NtSetEvent( event, NULL );
1103 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1104 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1106 else
1108 TRACE("= 0x%08x\n", status);
1109 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1112 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1114 return status;
1118 /***********************************************************************
1119 * FILE_AsyncWriteService (INTERNAL)
1121 static NTSTATUS FILE_AsyncWriteService( void *user, IO_STATUS_BLOCK *iosb,
1122 NTSTATUS status, void **apc, void **arg )
1124 struct async_fileio_write *fileio = user;
1125 int result, fd, needs_close;
1126 enum server_fd_type type;
1128 switch (status)
1130 case STATUS_ALERTED:
1131 /* write some data (non-blocking) */
1132 if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
1133 &needs_close, &type, NULL )))
1134 break;
1136 if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1137 result = send( fd, fileio->buffer, 0, 0 );
1138 else
1139 result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
1141 if (needs_close) close( fd );
1143 if (result < 0)
1145 if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
1146 else status = FILE_GetNtStatus();
1148 else
1150 fileio->already += result;
1151 status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
1153 break;
1155 case STATUS_TIMEOUT:
1156 case STATUS_IO_TIMEOUT:
1157 if (fileio->already) status = STATUS_SUCCESS;
1158 break;
1160 if (status != STATUS_PENDING)
1162 iosb->u.Status = status;
1163 iosb->Information = fileio->already;
1164 *apc = fileio->io.apc;
1165 *arg = fileio->io.apc_arg;
1166 release_fileio( &fileio->io );
1168 return status;
1171 static NTSTATUS set_pending_write( HANDLE device )
1173 NTSTATUS status;
1175 SERVER_START_REQ( set_serial_info )
1177 req->handle = wine_server_obj_handle( device );
1178 req->flags = SERIALINFO_PENDING_WRITE;
1179 status = wine_server_call( req );
1181 SERVER_END_REQ;
1182 return status;
1185 /******************************************************************************
1186 * NtWriteFile [NTDLL.@]
1187 * ZwWriteFile [NTDLL.@]
1189 * Write to an open file handle.
1191 * PARAMS
1192 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1193 * Event [I] Event to signal upon completion (or NULL)
1194 * ApcRoutine [I] Callback to call upon completion (or NULL)
1195 * ApcContext [I] Context for ApcRoutine (or NULL)
1196 * IoStatusBlock [O] Receives information about the operation on return
1197 * Buffer [I] Source for the data to write
1198 * Length [I] Size of Buffer
1199 * ByteOffset [O] Destination for the new file pointer position (or NULL)
1200 * Key [O] Function unknown (may be NULL)
1202 * RETURNS
1203 * Success: 0. IoStatusBlock is updated, and the Information member contains
1204 * The number of bytes written.
1205 * Failure: An NTSTATUS error code describing the error.
1207 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
1208 PIO_APC_ROUTINE apc, void* apc_user,
1209 PIO_STATUS_BLOCK io_status,
1210 const void* buffer, ULONG length,
1211 PLARGE_INTEGER offset, PULONG key)
1213 int result, unix_handle, needs_close;
1214 unsigned int options;
1215 struct io_timeouts timeouts;
1216 NTSTATUS status;
1217 ULONG total = 0;
1218 enum server_fd_type type;
1219 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1220 BOOL send_completion = FALSE, async_write, append_write = FALSE, timeout_init_done = FALSE;
1221 LARGE_INTEGER offset_eof;
1223 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
1224 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
1226 if (!io_status) return STATUS_ACCESS_VIOLATION;
1228 status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
1229 &needs_close, &type, &options );
1230 if (status == STATUS_ACCESS_DENIED)
1232 status = server_get_unix_fd( hFile, FILE_APPEND_DATA, &unix_handle,
1233 &needs_close, &type, &options );
1234 append_write = TRUE;
1236 if (status && status != STATUS_BAD_DEVICE_TYPE) return status;
1238 if (!virtual_check_buffer_for_read( buffer, length ))
1240 status = STATUS_INVALID_USER_BUFFER;
1241 goto done;
1244 if (status == STATUS_BAD_DEVICE_TYPE)
1245 return server_write_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
1247 async_write = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
1249 if (type == FD_TYPE_FILE)
1251 if (async_write &&
1252 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1254 status = STATUS_INVALID_PARAMETER;
1255 goto done;
1258 if (append_write)
1260 offset_eof.QuadPart = FILE_WRITE_TO_END_OF_FILE;
1261 offset = &offset_eof;
1264 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1266 off_t off = offset->QuadPart;
1268 if (offset->QuadPart == FILE_WRITE_TO_END_OF_FILE)
1270 struct stat st;
1272 if (fstat( unix_handle, &st ) == -1)
1274 status = FILE_GetNtStatus();
1275 goto done;
1277 off = st.st_size;
1279 else if (offset->QuadPart < 0)
1281 status = STATUS_INVALID_PARAMETER;
1282 goto done;
1285 /* async I/O doesn't make sense on regular files */
1286 while ((result = pwrite( unix_handle, buffer, length, off )) == -1)
1288 if (errno != EINTR)
1290 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1291 else status = FILE_GetNtStatus();
1292 goto done;
1296 if (!async_write)
1297 /* update file pointer position */
1298 lseek( unix_handle, off + result, SEEK_SET );
1300 total = result;
1301 status = STATUS_SUCCESS;
1302 goto done;
1305 else if (type == FD_TYPE_SERIAL || type == FD_TYPE_DEVICE)
1307 if (async_write &&
1308 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1310 status = STATUS_INVALID_PARAMETER;
1311 goto done;
1315 for (;;)
1317 /* zero-length writes on sockets may not work with plain write(2) */
1318 if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1319 result = send( unix_handle, buffer, 0, 0 );
1320 else
1321 result = write( unix_handle, (const char *)buffer + total, length - total );
1323 if (result >= 0)
1325 total += result;
1326 if (total == length)
1328 status = STATUS_SUCCESS;
1329 goto done;
1331 if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
1333 else if (errno != EAGAIN)
1335 if (errno == EINTR) continue;
1336 if (!total)
1338 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1339 else status = FILE_GetNtStatus();
1341 goto done;
1344 if (async_write)
1346 struct async_fileio_write *fileio;
1348 fileio = (struct async_fileio_write *)alloc_fileio( sizeof(*fileio), hFile, apc, apc_user );
1349 if (!fileio)
1351 status = STATUS_NO_MEMORY;
1352 goto err;
1354 fileio->already = total;
1355 fileio->count = length;
1356 fileio->buffer = buffer;
1358 SERVER_START_REQ( register_async )
1360 req->type = ASYNC_TYPE_WRITE;
1361 req->count = length;
1362 req->async.handle = wine_server_obj_handle( hFile );
1363 req->async.event = wine_server_obj_handle( hEvent );
1364 req->async.callback = wine_server_client_ptr( FILE_AsyncWriteService );
1365 req->async.iosb = wine_server_client_ptr( io_status );
1366 req->async.arg = wine_server_client_ptr( fileio );
1367 req->async.cvalue = cvalue;
1368 status = wine_server_call( req );
1370 SERVER_END_REQ;
1372 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1373 goto err;
1375 else /* synchronous write, wait for the fd to become ready */
1377 struct pollfd pfd;
1378 int ret, timeout;
1380 if (!timeout_init_done)
1382 timeout_init_done = TRUE;
1383 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1384 goto err;
1385 if (hEvent) NtResetEvent( hEvent, NULL );
1387 timeout = get_next_io_timeout( &timeouts, total );
1389 pfd.fd = unix_handle;
1390 pfd.events = POLLOUT;
1392 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1394 /* return with what we got so far */
1395 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1396 goto done;
1398 if (ret == -1 && errno != EINTR)
1400 status = FILE_GetNtStatus();
1401 goto done;
1403 /* will now restart the write */
1407 done:
1408 send_completion = cvalue != 0;
1410 err:
1411 if (needs_close) close( unix_handle );
1413 if (type == FD_TYPE_SERIAL && (status == STATUS_SUCCESS || status == STATUS_PENDING))
1414 set_pending_write( hFile );
1416 if (status == STATUS_SUCCESS)
1418 io_status->u.Status = status;
1419 io_status->Information = total;
1420 TRACE("= SUCCESS (%u)\n", total);
1421 if (hEvent) NtSetEvent( hEvent, NULL );
1422 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1423 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1425 else
1427 TRACE("= 0x%08x\n", status);
1428 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1431 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1433 return status;
1437 /******************************************************************************
1438 * NtWriteFileGather [NTDLL.@]
1439 * ZwWriteFileGather [NTDLL.@]
1441 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1442 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1443 ULONG length, PLARGE_INTEGER offset, PULONG key )
1445 int result, unix_handle, needs_close;
1446 unsigned int options;
1447 NTSTATUS status;
1448 ULONG pos = 0, total = 0;
1449 enum server_fd_type type;
1450 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1451 BOOL send_completion = FALSE;
1453 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1454 file, event, apc, apc_user, io_status, segments, length, offset, key);
1456 if (length % page_size) return STATUS_INVALID_PARAMETER;
1457 if (!io_status) return STATUS_ACCESS_VIOLATION;
1459 status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1460 &needs_close, &type, &options );
1461 if (status) return status;
1463 if ((type != FD_TYPE_FILE) ||
1464 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1465 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1467 status = STATUS_INVALID_PARAMETER;
1468 goto error;
1471 while (length)
1473 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1474 result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1475 page_size - pos, offset->QuadPart + total );
1476 else
1477 result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1479 if (result == -1)
1481 if (errno == EINTR) continue;
1482 if (errno == EFAULT)
1484 status = STATUS_INVALID_USER_BUFFER;
1485 goto error;
1487 status = FILE_GetNtStatus();
1488 break;
1490 if (!result)
1492 status = STATUS_DISK_FULL;
1493 break;
1495 total += result;
1496 length -= result;
1497 if ((pos += result) == page_size)
1499 pos = 0;
1500 segments++;
1504 send_completion = cvalue != 0;
1506 error:
1507 if (needs_close) close( unix_handle );
1508 if (status == STATUS_SUCCESS)
1510 io_status->u.Status = status;
1511 io_status->Information = total;
1512 TRACE("= SUCCESS (%u)\n", total);
1513 if (event) NtSetEvent( event, NULL );
1514 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1515 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1517 else
1519 TRACE("= 0x%08x\n", status);
1520 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1523 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1525 return status;
1529 /* do an ioctl call through the server */
1530 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1531 PIO_APC_ROUTINE apc, PVOID apc_context,
1532 IO_STATUS_BLOCK *io, ULONG code,
1533 const void *in_buffer, ULONG in_size,
1534 PVOID out_buffer, ULONG out_size )
1536 struct async_irp *async;
1537 NTSTATUS status;
1538 HANDLE wait_handle;
1539 ULONG options;
1540 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1542 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
1543 return STATUS_NO_MEMORY;
1544 async->event = event;
1545 async->buffer = out_buffer;
1546 async->size = out_size;
1548 SERVER_START_REQ( ioctl )
1550 req->code = code;
1551 req->blocking = !apc && !event && !cvalue;
1552 req->async.handle = wine_server_obj_handle( handle );
1553 req->async.callback = wine_server_client_ptr( irp_completion );
1554 req->async.iosb = wine_server_client_ptr( io );
1555 req->async.arg = wine_server_client_ptr( async );
1556 req->async.event = wine_server_obj_handle( event );
1557 req->async.cvalue = cvalue;
1558 wine_server_add_data( req, in_buffer, in_size );
1559 if ((code & 3) != METHOD_BUFFERED)
1560 wine_server_add_data( req, out_buffer, out_size );
1561 wine_server_set_reply( req, out_buffer, out_size );
1562 status = wine_server_call( req );
1563 wait_handle = wine_server_ptr_handle( reply->wait );
1564 options = reply->options;
1565 if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1567 SERVER_END_REQ;
1569 if (status == STATUS_NOT_SUPPORTED)
1570 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1571 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1573 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1575 if (wait_handle)
1577 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1578 status = io->u.Status;
1579 NtClose( wait_handle );
1582 return status;
1585 /* Tell Valgrind to ignore any holes in structs we will be passing to the
1586 * server */
1587 static void ignore_server_ioctl_struct_holes (ULONG code, const void *in_buffer,
1588 ULONG in_size)
1590 #ifdef VALGRIND_MAKE_MEM_DEFINED
1591 # define IGNORE_STRUCT_HOLE(buf, size, t, f1, f2) \
1592 do { \
1593 if (FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1) < FIELD_OFFSET(t, f2)) \
1594 if ((size) >= FIELD_OFFSET(t, f2)) \
1595 VALGRIND_MAKE_MEM_DEFINED( \
1596 (const char *)(buf) + FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1), \
1597 FIELD_OFFSET(t, f2) - FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1)); \
1598 } while (0)
1600 switch (code)
1602 case FSCTL_PIPE_WAIT:
1603 IGNORE_STRUCT_HOLE(in_buffer, in_size, FILE_PIPE_WAIT_FOR_BUFFER, TimeoutSpecified, Name);
1604 break;
1606 #endif
1610 /**************************************************************************
1611 * NtDeviceIoControlFile [NTDLL.@]
1612 * ZwDeviceIoControlFile [NTDLL.@]
1614 * Perform an I/O control operation on an open file handle.
1616 * PARAMS
1617 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1618 * event [I] Event to signal upon completion (or NULL)
1619 * apc [I] Callback to call upon completion (or NULL)
1620 * apc_context [I] Context for ApcRoutine (or NULL)
1621 * io [O] Receives information about the operation on return
1622 * code [I] Control code for the operation to perform
1623 * in_buffer [I] Source for any input data required (or NULL)
1624 * in_size [I] Size of InputBuffer
1625 * out_buffer [O] Source for any output data returned (or NULL)
1626 * out_size [I] Size of OutputBuffer
1628 * RETURNS
1629 * Success: 0. IoStatusBlock is updated.
1630 * Failure: An NTSTATUS error code describing the error.
1632 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1633 PIO_APC_ROUTINE apc, PVOID apc_context,
1634 PIO_STATUS_BLOCK io, ULONG code,
1635 PVOID in_buffer, ULONG in_size,
1636 PVOID out_buffer, ULONG out_size)
1638 ULONG device = (code >> 16);
1639 NTSTATUS status = STATUS_NOT_SUPPORTED;
1641 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1642 handle, event, apc, apc_context, io, code,
1643 in_buffer, in_size, out_buffer, out_size);
1645 switch(device)
1647 case FILE_DEVICE_DISK:
1648 case FILE_DEVICE_CD_ROM:
1649 case FILE_DEVICE_DVD:
1650 case FILE_DEVICE_CONTROLLER:
1651 case FILE_DEVICE_MASS_STORAGE:
1652 status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1653 in_buffer, in_size, out_buffer, out_size);
1654 break;
1655 case FILE_DEVICE_SERIAL_PORT:
1656 status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1657 in_buffer, in_size, out_buffer, out_size);
1658 break;
1659 case FILE_DEVICE_TAPE:
1660 status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1661 in_buffer, in_size, out_buffer, out_size);
1662 break;
1665 if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1666 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1667 in_buffer, in_size, out_buffer, out_size );
1669 if (status != STATUS_PENDING) io->u.Status = status;
1670 return status;
1674 /**************************************************************************
1675 * NtFsControlFile [NTDLL.@]
1676 * ZwFsControlFile [NTDLL.@]
1678 * Perform a file system control operation on an open file handle.
1680 * PARAMS
1681 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1682 * event [I] Event to signal upon completion (or NULL)
1683 * apc [I] Callback to call upon completion (or NULL)
1684 * apc_context [I] Context for ApcRoutine (or NULL)
1685 * io [O] Receives information about the operation on return
1686 * code [I] Control code for the operation to perform
1687 * in_buffer [I] Source for any input data required (or NULL)
1688 * in_size [I] Size of InputBuffer
1689 * out_buffer [O] Source for any output data returned (or NULL)
1690 * out_size [I] Size of OutputBuffer
1692 * RETURNS
1693 * Success: 0. IoStatusBlock is updated.
1694 * Failure: An NTSTATUS error code describing the error.
1696 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1697 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1698 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1700 NTSTATUS status;
1702 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1703 handle, event, apc, apc_context, io, code,
1704 in_buffer, in_size, out_buffer, out_size);
1706 if (!io) return STATUS_INVALID_PARAMETER;
1708 ignore_server_ioctl_struct_holes( code, in_buffer, in_size );
1710 switch(code)
1712 case FSCTL_DISMOUNT_VOLUME:
1713 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1714 in_buffer, in_size, out_buffer, out_size );
1715 if (!status) status = DIR_unmount_device( handle );
1716 break;
1718 case FSCTL_PIPE_PEEK:
1720 FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1721 int avail = 0, fd, needs_close;
1723 if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1725 status = STATUS_INFO_LENGTH_MISMATCH;
1726 break;
1729 if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1730 break;
1732 #ifdef FIONREAD
1733 if (ioctl( fd, FIONREAD, &avail ) != 0)
1735 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1736 if (needs_close) close( fd );
1737 status = FILE_GetNtStatus();
1738 break;
1740 #endif
1741 if (!avail) /* check for closed pipe */
1743 struct pollfd pollfd;
1744 int ret;
1746 pollfd.fd = fd;
1747 pollfd.events = POLLIN;
1748 pollfd.revents = 0;
1749 ret = poll( &pollfd, 1, 0 );
1750 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1752 if (needs_close) close( fd );
1753 status = STATUS_PIPE_BROKEN;
1754 break;
1757 buffer->NamedPipeState = 0; /* FIXME */
1758 buffer->ReadDataAvailable = avail;
1759 buffer->NumberOfMessages = 0; /* FIXME */
1760 buffer->MessageLength = 0; /* FIXME */
1761 io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1762 status = STATUS_SUCCESS;
1763 if (avail)
1765 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1766 if (data_size)
1768 int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1769 if (res >= 0) io->Information += res;
1772 if (needs_close) close( fd );
1774 break;
1776 case FSCTL_PIPE_DISCONNECT:
1777 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1778 in_buffer, in_size, out_buffer, out_size );
1779 if (!status)
1781 int fd = server_remove_fd_from_cache( handle );
1782 if (fd != -1) close( fd );
1784 break;
1786 case FSCTL_PIPE_LISTEN:
1787 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1788 in_buffer, in_size, out_buffer, out_size );
1789 return status;
1791 case FSCTL_PIPE_IMPERSONATE:
1792 FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1793 status = RtlImpersonateSelf( SecurityImpersonation );
1794 break;
1796 case FSCTL_IS_VOLUME_MOUNTED:
1797 case FSCTL_LOCK_VOLUME:
1798 case FSCTL_UNLOCK_VOLUME:
1799 FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1800 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1801 status = STATUS_SUCCESS;
1802 break;
1804 case FSCTL_GET_RETRIEVAL_POINTERS:
1806 RETRIEVAL_POINTERS_BUFFER *buffer = (RETRIEVAL_POINTERS_BUFFER *)out_buffer;
1808 FIXME("stub: FSCTL_GET_RETRIEVAL_POINTERS\n");
1810 if (out_size >= sizeof(RETRIEVAL_POINTERS_BUFFER))
1812 buffer->ExtentCount = 1;
1813 buffer->StartingVcn.QuadPart = 1;
1814 buffer->Extents[0].NextVcn.QuadPart = 0;
1815 buffer->Extents[0].Lcn.QuadPart = 0;
1816 io->Information = sizeof(RETRIEVAL_POINTERS_BUFFER);
1817 status = STATUS_SUCCESS;
1819 else
1821 io->Information = 0;
1822 status = STATUS_BUFFER_TOO_SMALL;
1824 break;
1826 case FSCTL_SET_SPARSE:
1827 TRACE("FSCTL_SET_SPARSE: Ignoring request\n");
1828 io->Information = 0;
1829 status = STATUS_SUCCESS;
1830 break;
1831 case FSCTL_PIPE_WAIT:
1832 default:
1833 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1834 in_buffer, in_size, out_buffer, out_size );
1835 break;
1838 if (status != STATUS_PENDING) io->u.Status = status;
1839 return status;
1843 struct read_changes_fileio
1845 struct async_fileio io;
1846 void *buffer;
1847 ULONG buffer_size;
1848 ULONG data_size;
1849 char data[1];
1852 static NTSTATUS read_changes_apc( void *user, IO_STATUS_BLOCK *iosb,
1853 NTSTATUS status, void **apc, void **arg )
1855 struct read_changes_fileio *fileio = user;
1856 int size = 0;
1858 if (status == STATUS_ALERTED)
1860 SERVER_START_REQ( read_change )
1862 req->handle = wine_server_obj_handle( fileio->io.handle );
1863 wine_server_set_reply( req, fileio->data, fileio->data_size );
1864 status = wine_server_call( req );
1865 size = wine_server_reply_size( reply );
1867 SERVER_END_REQ;
1869 if (status == STATUS_SUCCESS && fileio->buffer)
1871 FILE_NOTIFY_INFORMATION *pfni = fileio->buffer;
1872 int i, left = fileio->buffer_size;
1873 DWORD *last_entry_offset = NULL;
1874 struct filesystem_event *event = (struct filesystem_event*)fileio->data;
1876 while (size && left >= sizeof(*pfni))
1878 /* convert to an NT style path */
1879 for (i = 0; i < event->len; i++)
1880 if (event->name[i] == '/') event->name[i] = '\\';
1882 pfni->Action = event->action;
1883 pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
1884 (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
1885 last_entry_offset = &pfni->NextEntryOffset;
1887 if (pfni->FileNameLength == -1 || pfni->FileNameLength == -2) break;
1889 i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
1890 pfni->FileNameLength *= sizeof(WCHAR);
1891 pfni->NextEntryOffset = i;
1892 pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
1893 left -= i;
1895 i = (offsetof(struct filesystem_event, name[event->len])
1896 + sizeof(int)-1) / sizeof(int) * sizeof(int);
1897 event = (struct filesystem_event*)((char*)event + i);
1898 size -= i;
1901 if (size)
1903 status = STATUS_NOTIFY_ENUM_DIR;
1904 size = 0;
1906 else
1908 if (last_entry_offset) *last_entry_offset = 0;
1909 size = fileio->buffer_size - left;
1912 else
1914 status = STATUS_NOTIFY_ENUM_DIR;
1915 size = 0;
1919 if (status != STATUS_PENDING)
1921 iosb->u.Status = status;
1922 iosb->Information = size;
1923 *apc = fileio->io.apc;
1924 *arg = fileio->io.apc_arg;
1925 release_fileio( &fileio->io );
1927 return status;
1930 #define FILE_NOTIFY_ALL ( \
1931 FILE_NOTIFY_CHANGE_FILE_NAME | \
1932 FILE_NOTIFY_CHANGE_DIR_NAME | \
1933 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
1934 FILE_NOTIFY_CHANGE_SIZE | \
1935 FILE_NOTIFY_CHANGE_LAST_WRITE | \
1936 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
1937 FILE_NOTIFY_CHANGE_CREATION | \
1938 FILE_NOTIFY_CHANGE_SECURITY )
1940 /******************************************************************************
1941 * NtNotifyChangeDirectoryFile [NTDLL.@]
1943 NTSTATUS WINAPI NtNotifyChangeDirectoryFile( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1944 void *apc_context, PIO_STATUS_BLOCK iosb, void *buffer,
1945 ULONG buffer_size, ULONG filter, BOOLEAN subtree )
1947 struct read_changes_fileio *fileio;
1948 NTSTATUS status;
1949 ULONG size = max( 4096, buffer_size );
1950 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1952 TRACE( "%p %p %p %p %p %p %u %u %d\n",
1953 handle, event, apc, apc_context, iosb, buffer, buffer_size, filter, subtree );
1955 if (!iosb) return STATUS_ACCESS_VIOLATION;
1956 if (filter == 0 || (filter & ~FILE_NOTIFY_ALL)) return STATUS_INVALID_PARAMETER;
1958 fileio = (struct read_changes_fileio *)alloc_fileio( offsetof(struct read_changes_fileio, data[size]),
1959 handle, apc, apc_context );
1960 if (!fileio) return STATUS_NO_MEMORY;
1962 fileio->buffer = buffer;
1963 fileio->buffer_size = buffer_size;
1964 fileio->data_size = size;
1966 SERVER_START_REQ( read_directory_changes )
1968 req->filter = filter;
1969 req->want_data = (buffer != NULL);
1970 req->subtree = subtree;
1971 req->async.handle = wine_server_obj_handle( handle );
1972 req->async.callback = wine_server_client_ptr( read_changes_apc );
1973 req->async.iosb = wine_server_client_ptr( iosb );
1974 req->async.arg = wine_server_client_ptr( fileio );
1975 req->async.event = wine_server_obj_handle( event );
1976 req->async.cvalue = cvalue;
1977 status = wine_server_call( req );
1979 SERVER_END_REQ;
1981 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1982 return status;
1985 /******************************************************************************
1986 * NtSetVolumeInformationFile [NTDLL.@]
1987 * ZwSetVolumeInformationFile [NTDLL.@]
1989 * Set volume information for an open file handle.
1991 * PARAMS
1992 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1993 * IoStatusBlock [O] Receives information about the operation on return
1994 * FsInformation [I] Source for volume information
1995 * Length [I] Size of FsInformation
1996 * FsInformationClass [I] Type of volume information to set
1998 * RETURNS
1999 * Success: 0. IoStatusBlock is updated.
2000 * Failure: An NTSTATUS error code describing the error.
2002 NTSTATUS WINAPI NtSetVolumeInformationFile(
2003 IN HANDLE FileHandle,
2004 PIO_STATUS_BLOCK IoStatusBlock,
2005 PVOID FsInformation,
2006 ULONG Length,
2007 FS_INFORMATION_CLASS FsInformationClass)
2009 FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
2010 FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
2011 return 0;
2014 #if defined(__ANDROID__) && !defined(HAVE_FUTIMENS)
2015 static int futimens( int fd, const struct timespec spec[2] )
2017 return syscall( __NR_utimensat, fd, NULL, spec, 0 );
2019 #define HAVE_FUTIMENS
2020 #endif /* __ANDROID__ */
2022 #ifndef UTIME_OMIT
2023 #define UTIME_OMIT ((1 << 30) - 2)
2024 #endif
2026 static NTSTATUS set_file_times( int fd, const LARGE_INTEGER *mtime, const LARGE_INTEGER *atime )
2028 NTSTATUS status = STATUS_SUCCESS;
2030 #ifdef HAVE_FUTIMENS
2031 struct timespec tv[2];
2033 tv[0].tv_sec = tv[1].tv_sec = 0;
2034 tv[0].tv_nsec = tv[1].tv_nsec = UTIME_OMIT;
2035 if (atime->QuadPart)
2037 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
2038 tv[0].tv_nsec = (atime->QuadPart % 10000000) * 100;
2040 if (mtime->QuadPart)
2042 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
2043 tv[1].tv_nsec = (mtime->QuadPart % 10000000) * 100;
2045 if (futimens( fd, tv ) == -1) status = FILE_GetNtStatus();
2047 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT)
2048 struct timeval tv[2];
2049 struct stat st;
2051 if (!atime->QuadPart || !mtime->QuadPart)
2054 tv[0].tv_sec = tv[0].tv_usec = 0;
2055 tv[1].tv_sec = tv[1].tv_usec = 0;
2056 if (!fstat( fd, &st ))
2058 tv[0].tv_sec = st.st_atime;
2059 tv[1].tv_sec = st.st_mtime;
2060 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2061 tv[0].tv_usec = st.st_atim.tv_nsec / 1000;
2062 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2063 tv[0].tv_usec = st.st_atimespec.tv_nsec / 1000;
2064 #endif
2065 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2066 tv[1].tv_usec = st.st_mtim.tv_nsec / 1000;
2067 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2068 tv[1].tv_usec = st.st_mtimespec.tv_nsec / 1000;
2069 #endif
2072 if (atime->QuadPart)
2074 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
2075 tv[0].tv_usec = (atime->QuadPart % 10000000) / 10;
2077 if (mtime->QuadPart)
2079 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
2080 tv[1].tv_usec = (mtime->QuadPart % 10000000) / 10;
2082 #ifdef HAVE_FUTIMES
2083 if (futimes( fd, tv ) == -1) status = FILE_GetNtStatus();
2084 #elif defined(HAVE_FUTIMESAT)
2085 if (futimesat( fd, NULL, tv ) == -1) status = FILE_GetNtStatus();
2086 #endif
2088 #else /* HAVE_FUTIMES || HAVE_FUTIMESAT */
2089 FIXME( "setting file times not supported\n" );
2090 status = STATUS_NOT_IMPLEMENTED;
2091 #endif
2092 return status;
2095 static inline void get_file_times( const struct stat *st, LARGE_INTEGER *mtime, LARGE_INTEGER *ctime,
2096 LARGE_INTEGER *atime, LARGE_INTEGER *creation )
2098 RtlSecondsSince1970ToTime( st->st_mtime, mtime );
2099 RtlSecondsSince1970ToTime( st->st_ctime, ctime );
2100 RtlSecondsSince1970ToTime( st->st_atime, atime );
2101 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2102 mtime->QuadPart += st->st_mtim.tv_nsec / 100;
2103 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2104 mtime->QuadPart += st->st_mtimespec.tv_nsec / 100;
2105 #endif
2106 #ifdef HAVE_STRUCT_STAT_ST_CTIM
2107 ctime->QuadPart += st->st_ctim.tv_nsec / 100;
2108 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
2109 ctime->QuadPart += st->st_ctimespec.tv_nsec / 100;
2110 #endif
2111 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2112 atime->QuadPart += st->st_atim.tv_nsec / 100;
2113 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2114 atime->QuadPart += st->st_atimespec.tv_nsec / 100;
2115 #endif
2116 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2117 RtlSecondsSince1970ToTime( st->st_birthtime, creation );
2118 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIM
2119 creation->QuadPart += st->st_birthtim.tv_nsec / 100;
2120 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
2121 creation->QuadPart += st->st_birthtimespec.tv_nsec / 100;
2122 #endif
2123 #elif defined(HAVE_STRUCT_STAT___ST_BIRTHTIME)
2124 RtlSecondsSince1970ToTime( st->__st_birthtime, creation );
2125 #ifdef HAVE_STRUCT_STAT___ST_BIRTHTIM
2126 creation->QuadPart += st->__st_birthtim.tv_nsec / 100;
2127 #endif
2128 #else
2129 *creation = *mtime;
2130 #endif
2133 /* fill in the file information that depends on the stat and attribute info */
2134 NTSTATUS fill_file_info( const struct stat *st, ULONG attr, void *ptr,
2135 FILE_INFORMATION_CLASS class )
2137 switch (class)
2139 case FileBasicInformation:
2141 FILE_BASIC_INFORMATION *info = ptr;
2143 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2144 &info->LastAccessTime, &info->CreationTime );
2145 info->FileAttributes = attr;
2147 break;
2148 case FileStandardInformation:
2150 FILE_STANDARD_INFORMATION *info = ptr;
2152 if ((info->Directory = S_ISDIR(st->st_mode)))
2154 info->AllocationSize.QuadPart = 0;
2155 info->EndOfFile.QuadPart = 0;
2156 info->NumberOfLinks = 1;
2158 else
2160 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2161 info->EndOfFile.QuadPart = st->st_size;
2162 info->NumberOfLinks = st->st_nlink;
2165 break;
2166 case FileInternalInformation:
2168 FILE_INTERNAL_INFORMATION *info = ptr;
2169 info->IndexNumber.QuadPart = st->st_ino;
2171 break;
2172 case FileEndOfFileInformation:
2174 FILE_END_OF_FILE_INFORMATION *info = ptr;
2175 info->EndOfFile.QuadPart = S_ISDIR(st->st_mode) ? 0 : st->st_size;
2177 break;
2178 case FileAllInformation:
2180 FILE_ALL_INFORMATION *info = ptr;
2181 fill_file_info( st, attr, &info->BasicInformation, FileBasicInformation );
2182 fill_file_info( st, attr, &info->StandardInformation, FileStandardInformation );
2183 fill_file_info( st, attr, &info->InternalInformation, FileInternalInformation );
2185 break;
2186 /* all directory structures start with the FileDirectoryInformation layout */
2187 case FileBothDirectoryInformation:
2188 case FileFullDirectoryInformation:
2189 case FileDirectoryInformation:
2191 FILE_DIRECTORY_INFORMATION *info = ptr;
2193 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2194 &info->LastAccessTime, &info->CreationTime );
2195 if (S_ISDIR(st->st_mode))
2197 info->AllocationSize.QuadPart = 0;
2198 info->EndOfFile.QuadPart = 0;
2200 else
2202 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2203 info->EndOfFile.QuadPart = st->st_size;
2205 info->FileAttributes = attr;
2207 break;
2208 case FileIdFullDirectoryInformation:
2210 FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
2211 info->FileId.QuadPart = st->st_ino;
2212 fill_file_info( st, attr, info, FileDirectoryInformation );
2214 break;
2215 case FileIdBothDirectoryInformation:
2217 FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
2218 info->FileId.QuadPart = st->st_ino;
2219 fill_file_info( st, attr, info, FileDirectoryInformation );
2221 break;
2222 case FileIdGlobalTxDirectoryInformation:
2224 FILE_ID_GLOBAL_TX_DIR_INFORMATION *info = ptr;
2225 info->FileId.QuadPart = st->st_ino;
2226 fill_file_info( st, attr, info, FileDirectoryInformation );
2228 break;
2230 default:
2231 return STATUS_INVALID_INFO_CLASS;
2233 return STATUS_SUCCESS;
2236 NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
2238 data_size_t size = 1024;
2239 NTSTATUS ret;
2240 char *name;
2242 for (;;)
2244 name = RtlAllocateHeap( GetProcessHeap(), 0, size + 1 );
2245 if (!name) return STATUS_NO_MEMORY;
2246 unix_name->MaximumLength = size + 1;
2248 SERVER_START_REQ( get_handle_unix_name )
2250 req->handle = wine_server_obj_handle( handle );
2251 wine_server_set_reply( req, name, size );
2252 ret = wine_server_call( req );
2253 size = reply->name_len;
2255 SERVER_END_REQ;
2257 if (!ret)
2259 name[size] = 0;
2260 unix_name->Buffer = name;
2261 unix_name->Length = size;
2262 break;
2264 RtlFreeHeap( GetProcessHeap(), 0, name );
2265 if (ret != STATUS_BUFFER_OVERFLOW) break;
2267 return ret;
2270 static NTSTATUS fill_name_info( const ANSI_STRING *unix_name, FILE_NAME_INFORMATION *info, LONG *name_len )
2272 UNICODE_STRING nt_name;
2273 NTSTATUS status;
2275 if (!(status = wine_unix_to_nt_file_name( unix_name, &nt_name )))
2277 const WCHAR *ptr = nt_name.Buffer;
2278 const WCHAR *end = ptr + (nt_name.Length / sizeof(WCHAR));
2280 /* Skip the volume mount point. */
2281 while (ptr != end && *ptr == '\\') ++ptr;
2282 while (ptr != end && *ptr != '\\') ++ptr;
2283 while (ptr != end && *ptr == '\\') ++ptr;
2284 while (ptr != end && *ptr != '\\') ++ptr;
2286 info->FileNameLength = (end - ptr) * sizeof(WCHAR);
2287 if (*name_len < info->FileNameLength) status = STATUS_BUFFER_OVERFLOW;
2288 else *name_len = info->FileNameLength;
2290 memcpy( info->FileName, ptr, *name_len );
2291 RtlFreeUnicodeString( &nt_name );
2294 return status;
2297 /******************************************************************************
2298 * NtQueryInformationFile [NTDLL.@]
2299 * ZwQueryInformationFile [NTDLL.@]
2301 * Get information about an open file handle.
2303 * PARAMS
2304 * hFile [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2305 * io [O] Receives information about the operation on return
2306 * ptr [O] Destination for file information
2307 * len [I] Size of FileInformation
2308 * class [I] Type of file information to get
2310 * RETURNS
2311 * Success: 0. IoStatusBlock and FileInformation are updated.
2312 * Failure: An NTSTATUS error code describing the error.
2314 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
2315 PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
2317 static const size_t info_sizes[] =
2320 sizeof(FILE_DIRECTORY_INFORMATION), /* FileDirectoryInformation */
2321 sizeof(FILE_FULL_DIRECTORY_INFORMATION), /* FileFullDirectoryInformation */
2322 sizeof(FILE_BOTH_DIRECTORY_INFORMATION), /* FileBothDirectoryInformation */
2323 sizeof(FILE_BASIC_INFORMATION), /* FileBasicInformation */
2324 sizeof(FILE_STANDARD_INFORMATION), /* FileStandardInformation */
2325 sizeof(FILE_INTERNAL_INFORMATION), /* FileInternalInformation */
2326 sizeof(FILE_EA_INFORMATION), /* FileEaInformation */
2327 sizeof(FILE_ACCESS_INFORMATION), /* FileAccessInformation */
2328 sizeof(FILE_NAME_INFORMATION), /* FileNameInformation */
2329 sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
2330 0, /* FileLinkInformation */
2331 sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR), /* FileNamesInformation */
2332 sizeof(FILE_DISPOSITION_INFORMATION), /* FileDispositionInformation */
2333 sizeof(FILE_POSITION_INFORMATION), /* FilePositionInformation */
2334 sizeof(FILE_FULL_EA_INFORMATION), /* FileFullEaInformation */
2335 sizeof(FILE_MODE_INFORMATION), /* FileModeInformation */
2336 sizeof(FILE_ALIGNMENT_INFORMATION), /* FileAlignmentInformation */
2337 sizeof(FILE_ALL_INFORMATION), /* FileAllInformation */
2338 sizeof(FILE_ALLOCATION_INFORMATION), /* FileAllocationInformation */
2339 sizeof(FILE_END_OF_FILE_INFORMATION), /* FileEndOfFileInformation */
2340 0, /* FileAlternateNameInformation */
2341 sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
2342 sizeof(FILE_PIPE_INFORMATION), /* FilePipeInformation */
2343 sizeof(FILE_PIPE_LOCAL_INFORMATION), /* FilePipeLocalInformation */
2344 0, /* FilePipeRemoteInformation */
2345 sizeof(FILE_MAILSLOT_QUERY_INFORMATION), /* FileMailslotQueryInformation */
2346 0, /* FileMailslotSetInformation */
2347 0, /* FileCompressionInformation */
2348 0, /* FileObjectIdInformation */
2349 0, /* FileCompletionInformation */
2350 0, /* FileMoveClusterInformation */
2351 0, /* FileQuotaInformation */
2352 0, /* FileReparsePointInformation */
2353 sizeof(FILE_NETWORK_OPEN_INFORMATION), /* FileNetworkOpenInformation */
2354 0, /* FileAttributeTagInformation */
2355 0, /* FileTrackingInformation */
2356 0, /* FileIdBothDirectoryInformation */
2357 0, /* FileIdFullDirectoryInformation */
2358 0, /* FileValidDataLengthInformation */
2359 0, /* FileShortNameInformation */
2360 0, /* FileIoCompletionNotificationInformation, */
2361 0, /* FileIoStatusBlockRangeInformation */
2362 0, /* FileIoPriorityHintInformation */
2363 0, /* FileSfioReserveInformation */
2364 0, /* FileSfioVolumeInformation */
2365 0, /* FileHardLinkInformation */
2366 0, /* FileProcessIdsUsingFileInformation */
2367 0, /* FileNormalizedNameInformation */
2368 0, /* FileNetworkPhysicalNameInformation */
2369 0, /* FileIdGlobalTxDirectoryInformation */
2370 0, /* FileIsRemoteDeviceInformation */
2371 0, /* FileAttributeCacheInformation */
2372 0, /* FileNumaNodeInformation */
2373 0, /* FileStandardLinkInformation */
2374 0, /* FileRemoteProtocolInformation */
2375 0, /* FileReplaceCompletionInformation */
2378 struct stat st;
2379 int fd, needs_close = FALSE;
2380 ULONG attr;
2382 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
2384 io->Information = 0;
2386 if (class <= 0 || class >= FileMaximumInformation)
2387 return io->u.Status = STATUS_INVALID_INFO_CLASS;
2388 if (!info_sizes[class])
2390 FIXME("Unsupported class (%d)\n", class);
2391 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2393 if (len < info_sizes[class])
2394 return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2396 if (class != FilePipeInformation && class != FilePipeLocalInformation)
2398 if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
2399 return io->u.Status;
2402 switch (class)
2404 case FileBasicInformation:
2405 if (fd_get_file_info( fd, &st, &attr ) == -1)
2406 io->u.Status = FILE_GetNtStatus();
2407 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2408 io->u.Status = STATUS_INVALID_INFO_CLASS;
2409 else
2410 fill_file_info( &st, attr, ptr, class );
2411 break;
2412 case FileStandardInformation:
2414 FILE_STANDARD_INFORMATION *info = ptr;
2416 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2417 else
2419 fill_file_info( &st, attr, info, class );
2420 info->DeletePending = FALSE; /* FIXME */
2423 break;
2424 case FilePositionInformation:
2426 FILE_POSITION_INFORMATION *info = ptr;
2427 off_t res = lseek( fd, 0, SEEK_CUR );
2428 if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
2429 else info->CurrentByteOffset.QuadPart = res;
2431 break;
2432 case FileInternalInformation:
2433 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2434 else fill_file_info( &st, attr, ptr, class );
2435 break;
2436 case FileEaInformation:
2438 FILE_EA_INFORMATION *info = ptr;
2439 info->EaSize = 0;
2441 break;
2442 case FileEndOfFileInformation:
2443 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2444 else fill_file_info( &st, attr, ptr, class );
2445 break;
2446 case FileAllInformation:
2448 FILE_ALL_INFORMATION *info = ptr;
2449 ANSI_STRING unix_name;
2451 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2452 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2453 io->u.Status = STATUS_INVALID_INFO_CLASS;
2454 else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2456 LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);
2458 fill_file_info( &st, attr, info, FileAllInformation );
2459 info->StandardInformation.DeletePending = FALSE; /* FIXME */
2460 info->EaInformation.EaSize = 0;
2461 info->AccessInformation.AccessFlags = 0; /* FIXME */
2462 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
2463 info->ModeInformation.Mode = 0; /* FIXME */
2464 info->AlignmentInformation.AlignmentRequirement = 1; /* FIXME */
2466 io->u.Status = fill_name_info( &unix_name, &info->NameInformation, &name_len );
2467 RtlFreeAnsiString( &unix_name );
2468 io->Information = FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + name_len;
2471 break;
2472 case FileMailslotQueryInformation:
2474 FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
2476 SERVER_START_REQ( set_mailslot_info )
2478 req->handle = wine_server_obj_handle( hFile );
2479 req->flags = 0;
2480 io->u.Status = wine_server_call( req );
2481 if( io->u.Status == STATUS_SUCCESS )
2483 info->MaximumMessageSize = reply->max_msgsize;
2484 info->MailslotQuota = 0;
2485 info->NextMessageSize = 0;
2486 info->MessagesAvailable = 0;
2487 info->ReadTimeout.QuadPart = reply->read_timeout;
2490 SERVER_END_REQ;
2491 if (!io->u.Status)
2493 char *tmpbuf;
2494 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
2495 if (size > 0x10000) size = 0x10000;
2496 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2498 if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
2500 int res = recv( fd, tmpbuf, size, MSG_PEEK );
2501 info->MessagesAvailable = (res > 0);
2502 info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
2503 if (needs_close) close( fd );
2505 RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
2509 break;
2510 case FilePipeInformation:
2512 FILE_PIPE_INFORMATION* pi = ptr;
2514 SERVER_START_REQ( get_named_pipe_info )
2516 req->handle = wine_server_obj_handle( hFile );
2517 if (!(io->u.Status = wine_server_call( req )))
2519 pi->ReadMode = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_READ) ?
2520 FILE_PIPE_MESSAGE_MODE : FILE_PIPE_BYTE_STREAM_MODE;
2521 pi->CompletionMode = (reply->flags & NAMED_PIPE_NONBLOCKING_MODE) ?
2522 FILE_PIPE_COMPLETE_OPERATION : FILE_PIPE_QUEUE_OPERATION;
2525 SERVER_END_REQ;
2527 break;
2528 case FilePipeLocalInformation:
2530 FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
2532 SERVER_START_REQ( get_named_pipe_info )
2534 req->handle = wine_server_obj_handle( hFile );
2535 if (!(io->u.Status = wine_server_call( req )))
2537 pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ?
2538 FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
2539 switch (reply->sharing)
2541 case FILE_SHARE_READ:
2542 pli->NamedPipeConfiguration = FILE_PIPE_OUTBOUND;
2543 break;
2544 case FILE_SHARE_WRITE:
2545 pli->NamedPipeConfiguration = FILE_PIPE_INBOUND;
2546 break;
2547 case FILE_SHARE_READ | FILE_SHARE_WRITE:
2548 pli->NamedPipeConfiguration = FILE_PIPE_FULL_DUPLEX;
2549 break;
2551 pli->MaximumInstances = reply->maxinstances;
2552 pli->CurrentInstances = reply->instances;
2553 pli->InboundQuota = reply->insize;
2554 pli->ReadDataAvailable = 0; /* FIXME */
2555 pli->OutboundQuota = reply->outsize;
2556 pli->WriteQuotaAvailable = 0; /* FIXME */
2557 pli->NamedPipeState = 0; /* FIXME */
2558 pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
2559 FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
2562 SERVER_END_REQ;
2564 break;
2565 case FileNameInformation:
2567 FILE_NAME_INFORMATION *info = ptr;
2568 ANSI_STRING unix_name;
2570 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2572 LONG name_len = len - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
2573 io->u.Status = fill_name_info( &unix_name, info, &name_len );
2574 RtlFreeAnsiString( &unix_name );
2575 io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2578 break;
2579 case FileNetworkOpenInformation:
2581 FILE_NETWORK_OPEN_INFORMATION *info = ptr;
2582 ANSI_STRING unix_name;
2584 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2586 ULONG attributes;
2587 struct stat st;
2589 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2590 io->u.Status = FILE_GetNtStatus();
2591 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2592 io->u.Status = STATUS_INVALID_INFO_CLASS;
2593 else
2595 FILE_BASIC_INFORMATION basic;
2596 FILE_STANDARD_INFORMATION std;
2598 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2599 fill_file_info( &st, attributes, &std, FileStandardInformation );
2601 info->CreationTime = basic.CreationTime;
2602 info->LastAccessTime = basic.LastAccessTime;
2603 info->LastWriteTime = basic.LastWriteTime;
2604 info->ChangeTime = basic.ChangeTime;
2605 info->AllocationSize = std.AllocationSize;
2606 info->EndOfFile = std.EndOfFile;
2607 info->FileAttributes = basic.FileAttributes;
2609 RtlFreeAnsiString( &unix_name );
2612 break;
2613 default:
2614 FIXME("Unsupported class (%d)\n", class);
2615 io->u.Status = STATUS_NOT_IMPLEMENTED;
2616 break;
2618 if (needs_close) close( fd );
2619 if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2620 return io->u.Status;
2623 /******************************************************************************
2624 * NtSetInformationFile [NTDLL.@]
2625 * ZwSetInformationFile [NTDLL.@]
2627 * Set information about an open file handle.
2629 * PARAMS
2630 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2631 * io [O] Receives information about the operation on return
2632 * ptr [I] Source for file information
2633 * len [I] Size of FileInformation
2634 * class [I] Type of file information to set
2636 * RETURNS
2637 * Success: 0. io is updated.
2638 * Failure: An NTSTATUS error code describing the error.
2640 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
2641 PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
2643 int fd, needs_close;
2645 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2647 io->u.Status = STATUS_SUCCESS;
2648 switch (class)
2650 case FileBasicInformation:
2651 if (len >= sizeof(FILE_BASIC_INFORMATION))
2653 struct stat st;
2654 const FILE_BASIC_INFORMATION *info = ptr;
2656 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2657 return io->u.Status;
2659 if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2660 io->u.Status = set_file_times( fd, &info->LastWriteTime, &info->LastAccessTime );
2662 if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
2664 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2665 else
2667 if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
2669 if (S_ISDIR( st.st_mode))
2670 WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
2671 else
2672 st.st_mode &= ~0222; /* clear write permission bits */
2674 else
2676 /* add write permission only where we already have read permission */
2677 st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
2679 if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
2683 if (needs_close) close( fd );
2685 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2686 break;
2688 case FilePositionInformation:
2689 if (len >= sizeof(FILE_POSITION_INFORMATION))
2691 const FILE_POSITION_INFORMATION *info = ptr;
2693 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2694 return io->u.Status;
2696 if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
2697 io->u.Status = FILE_GetNtStatus();
2699 if (needs_close) close( fd );
2701 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2702 break;
2704 case FileEndOfFileInformation:
2705 if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
2707 struct stat st;
2708 const FILE_END_OF_FILE_INFORMATION *info = ptr;
2710 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2711 return io->u.Status;
2713 /* first try normal truncate */
2714 if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2716 /* now check for the need to extend the file */
2717 if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
2719 static const char zero;
2721 /* extend the file one byte beyond the requested size and then truncate it */
2722 /* this should work around ftruncate implementations that can't extend files */
2723 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
2724 ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2726 io->u.Status = FILE_GetNtStatus();
2728 if (needs_close) close( fd );
2730 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2731 break;
2733 case FilePipeInformation:
2734 if (len >= sizeof(FILE_PIPE_INFORMATION))
2736 FILE_PIPE_INFORMATION *info = ptr;
2738 if ((info->CompletionMode | info->ReadMode) & ~1)
2740 io->u.Status = STATUS_INVALID_PARAMETER;
2741 break;
2744 SERVER_START_REQ( set_named_pipe_info )
2746 req->handle = wine_server_obj_handle( handle );
2747 req->flags = (info->CompletionMode ? NAMED_PIPE_NONBLOCKING_MODE : 0) |
2748 (info->ReadMode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0);
2749 io->u.Status = wine_server_call( req );
2751 SERVER_END_REQ;
2753 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2754 break;
2756 case FileMailslotSetInformation:
2758 FILE_MAILSLOT_SET_INFORMATION *info = ptr;
2760 SERVER_START_REQ( set_mailslot_info )
2762 req->handle = wine_server_obj_handle( handle );
2763 req->flags = MAILSLOT_SET_READ_TIMEOUT;
2764 req->read_timeout = info->ReadTimeout.QuadPart;
2765 io->u.Status = wine_server_call( req );
2767 SERVER_END_REQ;
2769 break;
2771 case FileCompletionInformation:
2772 if (len >= sizeof(FILE_COMPLETION_INFORMATION))
2774 FILE_COMPLETION_INFORMATION *info = ptr;
2776 SERVER_START_REQ( set_completion_info )
2778 req->handle = wine_server_obj_handle( handle );
2779 req->chandle = wine_server_obj_handle( info->CompletionPort );
2780 req->ckey = info->CompletionKey;
2781 io->u.Status = wine_server_call( req );
2783 SERVER_END_REQ;
2784 } else
2785 io->u.Status = STATUS_INVALID_PARAMETER_3;
2786 break;
2788 case FileAllInformation:
2789 io->u.Status = STATUS_INVALID_INFO_CLASS;
2790 break;
2792 case FileValidDataLengthInformation:
2793 if (len >= sizeof(FILE_VALID_DATA_LENGTH_INFORMATION))
2795 struct stat st;
2796 const FILE_VALID_DATA_LENGTH_INFORMATION *info = ptr;
2798 if ((io->u.Status = server_get_unix_fd( handle, FILE_WRITE_DATA, &fd, &needs_close, NULL, NULL )))
2799 return io->u.Status;
2801 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2802 else if (info->ValidDataLength.QuadPart <= 0 || (off_t)info->ValidDataLength.QuadPart > st.st_size)
2803 io->u.Status = STATUS_INVALID_PARAMETER;
2804 else
2806 #ifdef HAVE_FALLOCATE
2807 if (fallocate( fd, 0, 0, (off_t)info->ValidDataLength.QuadPart ) == -1)
2809 NTSTATUS status = FILE_GetNtStatus();
2810 if (status == STATUS_NOT_SUPPORTED) WARN( "fallocate not supported on this filesystem\n" );
2811 else io->u.Status = status;
2813 #else
2814 FIXME( "setting valid data length not supported\n" );
2815 #endif
2817 if (needs_close) close( fd );
2819 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2820 break;
2822 case FileDispositionInformation:
2823 if (len >= sizeof(FILE_DISPOSITION_INFORMATION))
2825 FILE_DISPOSITION_INFORMATION *info = ptr;
2827 SERVER_START_REQ( set_fd_disp_info )
2829 req->handle = wine_server_obj_handle( handle );
2830 req->unlink = info->DoDeleteFile;
2831 io->u.Status = wine_server_call( req );
2833 SERVER_END_REQ;
2834 } else
2835 io->u.Status = STATUS_INVALID_PARAMETER_3;
2836 break;
2838 case FileRenameInformation:
2839 if (len >= sizeof(FILE_RENAME_INFORMATION))
2841 FILE_RENAME_INFORMATION *info = ptr;
2842 UNICODE_STRING name_str;
2843 OBJECT_ATTRIBUTES attr;
2844 ANSI_STRING unix_name;
2846 name_str.Buffer = info->FileName;
2847 name_str.Length = info->FileNameLength;
2848 name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);
2850 attr.Length = sizeof(attr);
2851 attr.ObjectName = &name_str;
2852 attr.RootDirectory = info->RootDir;
2853 attr.Attributes = OBJ_CASE_INSENSITIVE;
2855 io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
2856 if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
2857 break;
2859 if (!info->Replace && io->u.Status == STATUS_SUCCESS)
2861 RtlFreeAnsiString( &unix_name );
2862 io->u.Status = STATUS_OBJECT_NAME_COLLISION;
2863 break;
2866 SERVER_START_REQ( set_fd_name_info )
2868 req->handle = wine_server_obj_handle( handle );
2869 req->rootdir = wine_server_obj_handle( attr.RootDirectory );
2870 req->link = FALSE;
2871 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
2872 io->u.Status = wine_server_call( req );
2874 SERVER_END_REQ;
2876 RtlFreeAnsiString( &unix_name );
2878 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2879 break;
2881 case FileLinkInformation:
2882 if (len >= sizeof(FILE_LINK_INFORMATION))
2884 FILE_LINK_INFORMATION *info = ptr;
2885 UNICODE_STRING name_str;
2886 OBJECT_ATTRIBUTES attr;
2887 ANSI_STRING unix_name;
2889 name_str.Buffer = info->FileName;
2890 name_str.Length = info->FileNameLength;
2891 name_str.MaximumLength = info->FileNameLength + sizeof(WCHAR);
2893 attr.Length = sizeof(attr);
2894 attr.ObjectName = &name_str;
2895 attr.RootDirectory = info->RootDirectory;
2896 attr.Attributes = OBJ_CASE_INSENSITIVE;
2898 io->u.Status = nt_to_unix_file_name_attr( &attr, &unix_name, FILE_OPEN_IF );
2899 if (io->u.Status != STATUS_SUCCESS && io->u.Status != STATUS_NO_SUCH_FILE)
2900 break;
2902 if (!info->ReplaceIfExists && io->u.Status == STATUS_SUCCESS)
2904 RtlFreeAnsiString( &unix_name );
2905 io->u.Status = STATUS_OBJECT_NAME_COLLISION;
2906 break;
2909 SERVER_START_REQ( set_fd_name_info )
2911 req->handle = wine_server_obj_handle( handle );
2912 req->rootdir = wine_server_obj_handle( attr.RootDirectory );
2913 req->link = TRUE;
2914 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
2915 io->u.Status = wine_server_call( req );
2917 SERVER_END_REQ;
2919 RtlFreeAnsiString( &unix_name );
2921 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2922 break;
2924 default:
2925 FIXME("Unsupported class (%d)\n", class);
2926 io->u.Status = STATUS_NOT_IMPLEMENTED;
2927 break;
2929 io->Information = 0;
2930 return io->u.Status;
2934 /******************************************************************************
2935 * NtQueryFullAttributesFile (NTDLL.@)
2937 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
2938 FILE_NETWORK_OPEN_INFORMATION *info )
2940 ANSI_STRING unix_name;
2941 NTSTATUS status;
2943 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2945 ULONG attributes;
2946 struct stat st;
2948 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2949 status = FILE_GetNtStatus();
2950 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2951 status = STATUS_INVALID_INFO_CLASS;
2952 else
2954 FILE_BASIC_INFORMATION basic;
2955 FILE_STANDARD_INFORMATION std;
2957 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2958 fill_file_info( &st, attributes, &std, FileStandardInformation );
2960 info->CreationTime = basic.CreationTime;
2961 info->LastAccessTime = basic.LastAccessTime;
2962 info->LastWriteTime = basic.LastWriteTime;
2963 info->ChangeTime = basic.ChangeTime;
2964 info->AllocationSize = std.AllocationSize;
2965 info->EndOfFile = std.EndOfFile;
2966 info->FileAttributes = basic.FileAttributes;
2967 if (DIR_is_hidden_file( attr->ObjectName ))
2968 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2970 RtlFreeAnsiString( &unix_name );
2972 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2973 return status;
2977 /******************************************************************************
2978 * NtQueryAttributesFile (NTDLL.@)
2979 * ZwQueryAttributesFile (NTDLL.@)
2981 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
2983 ANSI_STRING unix_name;
2984 NTSTATUS status;
2986 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2988 ULONG attributes;
2989 struct stat st;
2991 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2992 status = FILE_GetNtStatus();
2993 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2994 status = STATUS_INVALID_INFO_CLASS;
2995 else
2997 status = fill_file_info( &st, attributes, info, FileBasicInformation );
2998 if (DIR_is_hidden_file( attr->ObjectName ))
2999 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
3001 RtlFreeAnsiString( &unix_name );
3003 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
3004 return status;
3008 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3009 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
3010 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
3011 unsigned int flags )
3013 if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
3015 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3016 /* Don't assume read-only, let the mount options set it below */
3017 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3019 else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
3020 !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
3022 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3023 info->Characteristics |= FILE_REMOTE_DEVICE;
3025 else if (!strcmp("procfs", fstypename))
3026 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3027 else
3028 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3030 if (flags & MNT_RDONLY)
3031 info->Characteristics |= FILE_READ_ONLY_DEVICE;
3033 if (!(flags & MNT_LOCAL))
3035 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3036 info->Characteristics |= FILE_REMOTE_DEVICE;
3039 #endif
3041 static inline BOOL is_device_placeholder( int fd )
3043 static const char wine_placeholder[] = "Wine device placeholder";
3044 char buffer[sizeof(wine_placeholder)-1];
3046 if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
3047 return FALSE;
3048 return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
3051 /******************************************************************************
3052 * get_device_info
3054 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
3056 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
3058 struct stat st;
3060 info->Characteristics = 0;
3061 if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
3062 if (S_ISCHR( st.st_mode ))
3064 info->DeviceType = FILE_DEVICE_UNKNOWN;
3065 #ifdef linux
3066 switch(major(st.st_rdev))
3068 case MEM_MAJOR:
3069 info->DeviceType = FILE_DEVICE_NULL;
3070 break;
3071 case TTY_MAJOR:
3072 info->DeviceType = FILE_DEVICE_SERIAL_PORT;
3073 break;
3074 case LP_MAJOR:
3075 info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
3076 break;
3077 case SCSI_TAPE_MAJOR:
3078 info->DeviceType = FILE_DEVICE_TAPE;
3079 break;
3081 #endif
3083 else if (S_ISBLK( st.st_mode ))
3085 info->DeviceType = FILE_DEVICE_DISK;
3087 else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
3089 info->DeviceType = FILE_DEVICE_NAMED_PIPE;
3091 else if (is_device_placeholder( fd ))
3093 info->DeviceType = FILE_DEVICE_DISK;
3095 else /* regular file or directory */
3097 #if defined(linux) && defined(HAVE_FSTATFS)
3098 struct statfs stfs;
3100 /* check for floppy disk */
3101 if (major(st.st_dev) == FLOPPY_MAJOR)
3102 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3104 if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
3105 switch (stfs.f_type)
3107 case 0x9660: /* iso9660 */
3108 case 0x9fa1: /* supermount */
3109 case 0x15013346: /* udf */
3110 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3111 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
3112 break;
3113 case 0x6969: /* nfs */
3114 case 0x517B: /* smbfs */
3115 case 0x564c: /* ncpfs */
3116 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
3117 info->Characteristics |= FILE_REMOTE_DEVICE;
3118 break;
3119 case 0x01021994: /* tmpfs */
3120 case 0x28cd3d45: /* cramfs */
3121 case 0x1373: /* devfs */
3122 case 0x9fa0: /* procfs */
3123 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3124 break;
3125 default:
3126 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3127 break;
3129 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
3130 struct statfs stfs;
3132 if (fstatfs( fd, &stfs ) < 0)
3133 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3134 else
3135 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
3136 #elif defined(__NetBSD__)
3137 struct statvfs stfs;
3139 if (fstatvfs( fd, &stfs) < 0)
3140 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3141 else
3142 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
3143 #elif defined(sun)
3144 /* Use dkio to work out device types */
3146 # include <sys/dkio.h>
3147 # include <sys/vtoc.h>
3148 struct dk_cinfo dkinf;
3149 int retval = ioctl(fd, DKIOCINFO, &dkinf);
3150 if(retval==-1){
3151 WARN("Unable to get disk device type information - assuming a disk like device\n");
3152 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3154 switch (dkinf.dki_ctype)
3156 case DKC_CDROM:
3157 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
3158 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
3159 break;
3160 case DKC_NCRFLOPPY:
3161 case DKC_SMSFLOPPY:
3162 case DKC_INTEL82072:
3163 case DKC_INTEL82077:
3164 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3165 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3166 break;
3167 case DKC_MD:
3168 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3169 break;
3170 default:
3171 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3174 #else
3175 static int warned;
3176 if (!warned++) FIXME( "device info not properly supported on this platform\n" );
3177 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3178 #endif
3179 info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
3181 return STATUS_SUCCESS;
3185 /******************************************************************************
3186 * NtQueryVolumeInformationFile [NTDLL.@]
3187 * ZwQueryVolumeInformationFile [NTDLL.@]
3189 * Get volume information for an open file handle.
3191 * PARAMS
3192 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3193 * io [O] Receives information about the operation on return
3194 * buffer [O] Destination for volume information
3195 * length [I] Size of FsInformation
3196 * info_class [I] Type of volume information to set
3198 * RETURNS
3199 * Success: 0. io and buffer are updated.
3200 * Failure: An NTSTATUS error code describing the error.
3202 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
3203 PVOID buffer, ULONG length,
3204 FS_INFORMATION_CLASS info_class )
3206 int fd, needs_close;
3207 struct stat st;
3208 static int once;
3210 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
3211 return io->u.Status;
3213 io->u.Status = STATUS_NOT_IMPLEMENTED;
3214 io->Information = 0;
3216 switch( info_class )
3218 case FileFsVolumeInformation:
3219 if (!once++) FIXME( "%p: volume info not supported\n", handle );
3220 break;
3221 case FileFsLabelInformation:
3222 FIXME( "%p: label info not supported\n", handle );
3223 break;
3224 case FileFsSizeInformation:
3225 if (length < sizeof(FILE_FS_SIZE_INFORMATION))
3226 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3227 else
3229 FILE_FS_SIZE_INFORMATION *info = buffer;
3231 if (fstat( fd, &st ) < 0)
3233 io->u.Status = FILE_GetNtStatus();
3234 break;
3236 if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
3238 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
3240 else
3242 ULONGLONG bsize;
3243 /* Linux's fstatvfs is buggy */
3244 #if !defined(linux) || !defined(HAVE_FSTATFS)
3245 struct statvfs stfs;
3247 if (fstatvfs( fd, &stfs ) < 0)
3249 io->u.Status = FILE_GetNtStatus();
3250 break;
3252 bsize = stfs.f_frsize;
3253 #else
3254 struct statfs stfs;
3255 if (fstatfs( fd, &stfs ) < 0)
3257 io->u.Status = FILE_GetNtStatus();
3258 break;
3260 bsize = stfs.f_bsize;
3261 #endif
3262 if (bsize == 2048) /* assume CD-ROM */
3264 info->BytesPerSector = 2048;
3265 info->SectorsPerAllocationUnit = 1;
3267 else
3269 info->BytesPerSector = 512;
3270 info->SectorsPerAllocationUnit = 8;
3272 info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3273 info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3274 io->Information = sizeof(*info);
3275 io->u.Status = STATUS_SUCCESS;
3278 break;
3279 case FileFsDeviceInformation:
3280 if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
3281 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3282 else
3284 FILE_FS_DEVICE_INFORMATION *info = buffer;
3286 if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
3287 io->Information = sizeof(*info);
3289 break;
3290 case FileFsAttributeInformation:
3291 if (length < offsetof( FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName[sizeof(ntfsW)/sizeof(WCHAR)] ))
3292 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3293 else
3295 FILE_FS_ATTRIBUTE_INFORMATION *info = buffer;
3297 FIXME( "%p: faking attribute info\n", handle );
3298 info->FileSystemAttribute = FILE_SUPPORTS_ENCRYPTION | FILE_FILE_COMPRESSION |
3299 FILE_PERSISTENT_ACLS | FILE_UNICODE_ON_DISK |
3300 FILE_CASE_PRESERVED_NAMES | FILE_CASE_SENSITIVE_SEARCH;
3301 info->MaximumComponentNameLength = MAXIMUM_FILENAME_LENGTH - 1;
3302 info->FileSystemNameLength = sizeof(ntfsW);
3303 memcpy(info->FileSystemName, ntfsW, sizeof(ntfsW));
3305 io->Information = sizeof(*info);
3306 io->u.Status = STATUS_SUCCESS;
3308 break;
3309 case FileFsControlInformation:
3310 FIXME( "%p: control info not supported\n", handle );
3311 break;
3312 case FileFsFullSizeInformation:
3313 FIXME( "%p: full size info not supported\n", handle );
3314 break;
3315 case FileFsObjectIdInformation:
3316 FIXME( "%p: object id info not supported\n", handle );
3317 break;
3318 case FileFsMaximumInformation:
3319 FIXME( "%p: maximum info not supported\n", handle );
3320 break;
3321 default:
3322 io->u.Status = STATUS_INVALID_PARAMETER;
3323 break;
3325 if (needs_close) close( fd );
3326 return io->u.Status;
3330 /******************************************************************
3331 * NtQueryEaFile (NTDLL.@)
3333 * Read extended attributes from NTFS files.
3335 * PARAMS
3336 * hFile [I] File handle, must be opened with FILE_READ_EA access
3337 * iosb [O] Receives information about the operation on return
3338 * buffer [O] Output buffer
3339 * length [I] Length of output buffer
3340 * single_entry [I] Only read and return one entry
3341 * ea_list [I] Optional list with names of EAs to return
3342 * ea_list_len [I] Length of ea_list in bytes
3343 * ea_index [I] Optional pointer to 1-based index of attribute to return
3344 * restart [I] restart EA scan
3346 * RETURNS
3347 * Success: 0. Atrributes read into buffer
3348 * Failure: An NTSTATUS error code describing the error.
3350 NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
3351 BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
3352 PULONG ea_index, BOOLEAN restart )
3354 FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
3355 hFile, iosb, buffer, length, single_entry, ea_list,
3356 ea_list_len, ea_index, restart);
3357 return STATUS_ACCESS_DENIED;
3361 /******************************************************************
3362 * NtSetEaFile (NTDLL.@)
3364 * Update extended attributes for NTFS files.
3366 * PARAMS
3367 * hFile [I] File handle, must be opened with FILE_READ_EA access
3368 * iosb [O] Receives information about the operation on return
3369 * buffer [I] Buffer with EA information
3370 * length [I] Length of buffer
3372 * RETURNS
3373 * Success: 0. Attributes are updated
3374 * Failure: An NTSTATUS error code describing the error.
3376 NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
3378 FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
3379 return STATUS_ACCESS_DENIED;
3383 /******************************************************************
3384 * NtFlushBuffersFile (NTDLL.@)
3386 * Flush any buffered data on an open file handle.
3388 * PARAMS
3389 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3390 * IoStatusBlock [O] Receives information about the operation on return
3392 * RETURNS
3393 * Success: 0. IoStatusBlock is updated.
3394 * Failure: An NTSTATUS error code describing the error.
3396 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
3398 NTSTATUS ret;
3399 HANDLE hEvent = NULL;
3400 enum server_fd_type type;
3401 int fd, needs_close;
3403 ret = server_get_unix_fd( hFile, FILE_WRITE_DATA, &fd, &needs_close, &type, NULL );
3405 if (!ret && type == FD_TYPE_SERIAL)
3407 ret = COMM_FlushBuffersFile( fd );
3409 else
3411 SERVER_START_REQ( flush )
3413 req->blocking = 1; /* always blocking */
3414 req->async.handle = wine_server_obj_handle( hFile );
3415 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3416 ret = wine_server_call( req );
3417 hEvent = wine_server_ptr_handle( reply->event );
3419 SERVER_END_REQ;
3421 if (hEvent)
3423 NtWaitForSingleObject( hEvent, FALSE, NULL );
3424 NtClose( hEvent );
3425 ret = STATUS_SUCCESS;
3429 if (needs_close) close( fd );
3430 return ret;
3433 /******************************************************************
3434 * NtLockFile (NTDLL.@)
3438 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
3439 PIO_APC_ROUTINE apc, void* apc_user,
3440 PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
3441 PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
3442 BOOLEAN exclusive )
3444 NTSTATUS ret;
3445 HANDLE handle;
3446 BOOLEAN async;
3447 static BOOLEAN warn = TRUE;
3449 if (apc || io_status || key)
3451 FIXME("Unimplemented yet parameter\n");
3452 return STATUS_NOT_IMPLEMENTED;
3455 if (apc_user && warn)
3457 FIXME("I/O completion on lock not implemented yet\n");
3458 warn = FALSE;
3461 for (;;)
3463 SERVER_START_REQ( lock_file )
3465 req->handle = wine_server_obj_handle( hFile );
3466 req->offset = offset->QuadPart;
3467 req->count = count->QuadPart;
3468 req->shared = !exclusive;
3469 req->wait = !dont_wait;
3470 ret = wine_server_call( req );
3471 handle = wine_server_ptr_handle( reply->handle );
3472 async = reply->overlapped;
3474 SERVER_END_REQ;
3475 if (ret != STATUS_PENDING)
3477 if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
3478 return ret;
3481 if (async)
3483 FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
3484 if (handle) NtClose( handle );
3485 return STATUS_PENDING;
3487 if (handle)
3489 NtWaitForSingleObject( handle, FALSE, NULL );
3490 NtClose( handle );
3492 else
3494 LARGE_INTEGER time;
3496 /* Unix lock conflict, sleep a bit and retry */
3497 time.QuadPart = 100 * (ULONGLONG)10000;
3498 time.QuadPart = -time.QuadPart;
3499 NtDelayExecution( FALSE, &time );
3505 /******************************************************************
3506 * NtUnlockFile (NTDLL.@)
3510 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
3511 PLARGE_INTEGER offset, PLARGE_INTEGER count,
3512 PULONG key )
3514 NTSTATUS status;
3516 TRACE( "%p %x%08x %x%08x\n",
3517 hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
3519 if (io_status || key)
3521 FIXME("Unimplemented yet parameter\n");
3522 return STATUS_NOT_IMPLEMENTED;
3525 SERVER_START_REQ( unlock_file )
3527 req->handle = wine_server_obj_handle( hFile );
3528 req->offset = offset->QuadPart;
3529 req->count = count->QuadPart;
3530 status = wine_server_call( req );
3532 SERVER_END_REQ;
3533 return status;
3536 /******************************************************************
3537 * NtCreateNamedPipeFile (NTDLL.@)
3541 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
3542 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
3543 ULONG sharing, ULONG dispo, ULONG options,
3544 ULONG pipe_type, ULONG read_mode,
3545 ULONG completion_mode, ULONG max_inst,
3546 ULONG inbound_quota, ULONG outbound_quota,
3547 PLARGE_INTEGER timeout)
3549 NTSTATUS status;
3550 data_size_t len;
3551 struct object_attributes *objattr;
3553 TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
3554 handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
3555 options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
3556 outbound_quota, timeout);
3558 if (!attr) return STATUS_INVALID_PARAMETER;
3560 /* assume we only get relative timeout */
3561 if (timeout->QuadPart > 0)
3562 FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
3564 if ((status = alloc_object_attributes( attr, &objattr, &len ))) return status;
3566 SERVER_START_REQ( create_named_pipe )
3568 req->access = access;
3569 req->options = options;
3570 req->sharing = sharing;
3571 req->flags =
3572 (pipe_type ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0) |
3573 (read_mode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0) |
3574 (completion_mode ? NAMED_PIPE_NONBLOCKING_MODE : 0);
3575 req->maxinstances = max_inst;
3576 req->outsize = outbound_quota;
3577 req->insize = inbound_quota;
3578 req->timeout = timeout->QuadPart;
3579 wine_server_add_data( req, objattr, len );
3580 status = wine_server_call( req );
3581 if (!status) *handle = wine_server_ptr_handle( reply->handle );
3583 SERVER_END_REQ;
3585 RtlFreeHeap( GetProcessHeap(), 0, objattr );
3586 return status;
3589 /******************************************************************
3590 * NtDeleteFile (NTDLL.@)
3594 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
3596 NTSTATUS status;
3597 HANDLE hFile;
3598 IO_STATUS_BLOCK io;
3600 TRACE("%p\n", ObjectAttributes);
3601 status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
3602 ObjectAttributes, &io, NULL, 0,
3603 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3604 FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
3605 if (status == STATUS_SUCCESS) status = NtClose(hFile);
3606 return status;
3609 /******************************************************************
3610 * NtCancelIoFileEx (NTDLL.@)
3614 NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
3616 TRACE("%p %p %p\n", hFile, iosb, io_status );
3618 SERVER_START_REQ( cancel_async )
3620 req->handle = wine_server_obj_handle( hFile );
3621 req->iosb = wine_server_client_ptr( iosb );
3622 req->only_thread = FALSE;
3623 io_status->u.Status = wine_server_call( req );
3625 SERVER_END_REQ;
3627 return io_status->u.Status;
3630 /******************************************************************
3631 * NtCancelIoFile (NTDLL.@)
3635 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
3637 TRACE("%p %p\n", hFile, io_status );
3639 SERVER_START_REQ( cancel_async )
3641 req->handle = wine_server_obj_handle( hFile );
3642 req->iosb = 0;
3643 req->only_thread = TRUE;
3644 io_status->u.Status = wine_server_call( req );
3646 SERVER_END_REQ;
3648 return io_status->u.Status;
3651 /******************************************************************************
3652 * NtCreateMailslotFile [NTDLL.@]
3653 * ZwCreateMailslotFile [NTDLL.@]
3655 * PARAMS
3656 * pHandle [O] pointer to receive the handle created
3657 * DesiredAccess [I] access mode (read, write, etc)
3658 * ObjectAttributes [I] fully qualified NT path of the mailslot
3659 * IoStatusBlock [O] receives completion status and other info
3660 * CreateOptions [I]
3661 * MailslotQuota [I]
3662 * MaxMessageSize [I]
3663 * TimeOut [I]
3665 * RETURNS
3666 * An NT status code
3668 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
3669 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
3670 ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
3671 PLARGE_INTEGER TimeOut)
3673 LARGE_INTEGER timeout;
3674 NTSTATUS ret;
3675 data_size_t len;
3676 struct object_attributes *objattr;
3678 TRACE("%p %08x %p %p %08x %08x %08x %p\n",
3679 pHandle, DesiredAccess, attr, IoStatusBlock,
3680 CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
3682 if (!pHandle) return STATUS_ACCESS_VIOLATION;
3683 if (!attr) return STATUS_INVALID_PARAMETER;
3685 if ((ret = alloc_object_attributes( attr, &objattr, &len ))) return ret;
3688 * For a NULL TimeOut pointer set the default timeout value
3690 if (!TimeOut)
3691 timeout.QuadPart = -1;
3692 else
3693 timeout.QuadPart = TimeOut->QuadPart;
3695 SERVER_START_REQ( create_mailslot )
3697 req->access = DesiredAccess;
3698 req->max_msgsize = MaxMessageSize;
3699 req->read_timeout = timeout.QuadPart;
3700 wine_server_add_data( req, objattr, len );
3701 ret = wine_server_call( req );
3702 if( ret == STATUS_SUCCESS )
3703 *pHandle = wine_server_ptr_handle( reply->handle );
3705 SERVER_END_REQ;
3707 RtlFreeHeap( GetProcessHeap(), 0, objattr );
3708 return ret;