Reimplemented CreateDirectoryW and RemoveDirectoryW using ntdll
[wine/hacks.git] / files / file.c
blobb114ff9e7c7a147a0934c1a245ec64689f532ad2
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996 Alexandre Julliard
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 * TODO:
22 * Fix the CopyFileEx methods to implement the "extended" functionality.
23 * Right now, they simply call the CopyFile method.
26 #include "config.h"
27 #include "wine/port.h"
29 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <string.h>
37 #ifdef HAVE_SYS_ERRNO_H
38 #include <sys/errno.h>
39 #endif
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #ifdef HAVE_SYS_MMAN_H
43 #include <sys/mman.h>
44 #endif
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_POLL_H
49 # include <sys/poll.h>
50 #endif
51 #include <time.h>
52 #ifdef HAVE_UNISTD_H
53 # include <unistd.h>
54 #endif
55 #ifdef HAVE_UTIME_H
56 # include <utime.h>
57 #endif
58 #ifdef HAVE_IO_H
59 # include <io.h>
60 #endif
62 #define NONAMELESSUNION
63 #define NONAMELESSSTRUCT
64 #include "winerror.h"
65 #include "ntstatus.h"
66 #include "windef.h"
67 #include "winbase.h"
68 #include "winreg.h"
69 #include "winternl.h"
70 #include "wine/winbase16.h"
71 #include "wine/server.h"
73 #include "file.h"
74 #include "wincon.h"
75 #include "kernel_private.h"
77 #include "smb.h"
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
81 WINE_DEFAULT_DEBUG_CHANNEL(file);
83 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
84 #define MAP_ANON MAP_ANONYMOUS
85 #endif
87 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
89 #define SECSPERDAY 86400
90 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
92 /***********************************************************************
93 * FILE_ConvertOFMode
95 * Convert OF_* mode into flags for CreateFile.
97 void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
99 switch(mode & 0x03)
101 case OF_READ: *access = GENERIC_READ; break;
102 case OF_WRITE: *access = GENERIC_WRITE; break;
103 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
104 default: *access = 0; break;
106 switch(mode & 0x70)
108 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
109 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
110 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
111 case OF_SHARE_DENY_NONE:
112 case OF_SHARE_COMPAT:
113 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
118 /***********************************************************************
119 * FILE_SetDosError
121 * Set the DOS error code from errno.
123 void FILE_SetDosError(void)
125 int save_errno = errno; /* errno gets overwritten by printf */
127 TRACE("errno = %d %s\n", errno, strerror(errno));
128 switch (save_errno)
130 case EAGAIN:
131 SetLastError( ERROR_SHARING_VIOLATION );
132 break;
133 case EBADF:
134 SetLastError( ERROR_INVALID_HANDLE );
135 break;
136 case ENOSPC:
137 SetLastError( ERROR_HANDLE_DISK_FULL );
138 break;
139 case EACCES:
140 case EPERM:
141 case EROFS:
142 SetLastError( ERROR_ACCESS_DENIED );
143 break;
144 case EBUSY:
145 SetLastError( ERROR_LOCK_VIOLATION );
146 break;
147 case ENOENT:
148 SetLastError( ERROR_FILE_NOT_FOUND );
149 break;
150 case EISDIR:
151 SetLastError( ERROR_CANNOT_MAKE );
152 break;
153 case ENFILE:
154 case EMFILE:
155 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
156 break;
157 case EEXIST:
158 SetLastError( ERROR_FILE_EXISTS );
159 break;
160 case EINVAL:
161 case ESPIPE:
162 SetLastError( ERROR_SEEK );
163 break;
164 case ENOTEMPTY:
165 SetLastError( ERROR_DIR_NOT_EMPTY );
166 break;
167 case ENOEXEC:
168 SetLastError( ERROR_BAD_FORMAT );
169 break;
170 case ENOTDIR:
171 SetLastError( ERROR_PATH_NOT_FOUND );
172 break;
173 case EXDEV:
174 SetLastError( ERROR_NOT_SAME_DEVICE );
175 break;
176 default:
177 WARN("unknown file error: %s\n", strerror(save_errno) );
178 SetLastError( ERROR_GEN_FAILURE );
179 break;
181 errno = save_errno;
185 /***********************************************************************
186 * FILE_CreateFile
188 * Implementation of CreateFile. Takes a Unix path name.
189 * Returns 0 on failure.
191 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
192 LPSECURITY_ATTRIBUTES sa, DWORD creation,
193 DWORD attributes, HANDLE template )
195 unsigned int err;
196 UINT disp, options;
197 HANDLE ret;
199 switch (creation)
201 case CREATE_ALWAYS: disp = FILE_OVERWRITE_IF; break;
202 case CREATE_NEW: disp = FILE_CREATE; break;
203 case OPEN_ALWAYS: disp = FILE_OPEN_IF; break;
204 case OPEN_EXISTING: disp = FILE_OPEN; break;
205 case TRUNCATE_EXISTING: disp = FILE_OVERWRITE; break;
206 default:
207 SetLastError( ERROR_INVALID_PARAMETER );
208 return 0;
211 options = 0;
212 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
213 options |= FILE_OPEN_FOR_BACKUP_INTENT;
214 else
215 options |= FILE_NON_DIRECTORY_FILE;
216 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
217 options |= FILE_DELETE_ON_CLOSE;
218 if (!(attributes & FILE_FLAG_OVERLAPPED))
219 options |= FILE_SYNCHRONOUS_IO_ALERT;
220 if (attributes & FILE_FLAG_RANDOM_ACCESS)
221 options |= FILE_RANDOM_ACCESS;
222 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
224 SERVER_START_REQ( create_file )
226 req->access = access;
227 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
228 req->sharing = sharing;
229 req->create = disp;
230 req->options = options;
231 req->attrs = attributes;
232 wine_server_add_data( req, filename, strlen(filename) );
233 SetLastError(0);
234 err = wine_server_call( req );
235 ret = reply->handle;
237 SERVER_END_REQ;
239 if (err)
241 /* In the case file creation was rejected due to CREATE_NEW flag
242 * was specified and file with that name already exists, correct
243 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
244 * Note: RtlNtStatusToDosError is not the subject to blame here.
246 if (err == STATUS_OBJECT_NAME_COLLISION)
247 SetLastError( ERROR_FILE_EXISTS );
248 else
249 SetLastError( RtlNtStatusToDosError(err) );
252 if (!ret) WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
253 return ret;
257 static HANDLE FILE_OpenPipe(LPCWSTR name, DWORD access, LPSECURITY_ATTRIBUTES sa )
259 HANDLE ret;
260 DWORD len = 0;
262 if (name && (len = strlenW(name)) > MAX_PATH)
264 SetLastError( ERROR_FILENAME_EXCED_RANGE );
265 return 0;
267 SERVER_START_REQ( open_named_pipe )
269 req->access = access;
270 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
271 SetLastError(0);
272 wine_server_add_data( req, name, len * sizeof(WCHAR) );
273 wine_server_call_err( req );
274 ret = reply->handle;
276 SERVER_END_REQ;
277 TRACE("Returned %p\n",ret);
278 return ret;
281 /*************************************************************************
282 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
284 * Creates or opens an object, and returns a handle that can be used to
285 * access that object.
287 * PARAMS
289 * filename [in] pointer to filename to be accessed
290 * access [in] access mode requested
291 * sharing [in] share mode
292 * sa [in] pointer to security attributes
293 * creation [in] how to create the file
294 * attributes [in] attributes for newly created file
295 * template [in] handle to file with extended attributes to copy
297 * RETURNS
298 * Success: Open handle to specified file
299 * Failure: INVALID_HANDLE_VALUE
301 * NOTES
302 * Should call SetLastError() on failure.
304 * BUGS
306 * Doesn't support character devices, template files, or a
307 * lot of the 'attributes' flags yet.
309 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
310 LPSECURITY_ATTRIBUTES sa, DWORD creation,
311 DWORD attributes, HANDLE template )
313 NTSTATUS status;
314 UINT options;
315 OBJECT_ATTRIBUTES attr;
316 UNICODE_STRING nameW;
317 IO_STATUS_BLOCK io;
318 HANDLE ret;
319 DWORD dosdev;
320 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
321 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
322 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
324 static const char * const creation_name[5] =
325 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
327 static const UINT nt_disposition[5] =
329 FILE_CREATE, /* CREATE_NEW */
330 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
331 FILE_OPEN, /* OPEN_EXISTING */
332 FILE_OPEN_IF, /* OPEN_ALWAYS */
333 FILE_OVERWRITE /* TRUNCATE_EXISTING */
337 /* sanity checks */
339 if (!filename || !filename[0])
341 SetLastError( ERROR_PATH_NOT_FOUND );
342 return INVALID_HANDLE_VALUE;
345 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
347 SetLastError( ERROR_INVALID_PARAMETER );
348 return INVALID_HANDLE_VALUE;
351 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
352 (access & GENERIC_READ)?"GENERIC_READ ":"",
353 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
354 (!access)?"QUERY_ACCESS ":"",
355 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
356 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
357 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
358 creation_name[creation - CREATE_NEW], attributes);
360 /* Open a console for CONIN$ or CONOUT$ */
362 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
364 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
365 goto done;
368 if (!strncmpW(filename, bkslashes_with_dotW, 4))
370 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
371 if(!strncmpiW(filename + 4, pipeW, 5))
373 TRACE("Opening a pipe: %s\n", debugstr_w(filename));
374 ret = FILE_OpenPipe( filename, access, sa );
375 goto done;
377 else if (isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0')
379 const char *device = DRIVE_GetDevice( toupperW(filename[4]) - 'A' );
380 if (device)
382 ret = FILE_CreateFile( device, access, sharing, sa, creation,
383 attributes, template );
385 else
387 SetLastError( ERROR_ACCESS_DENIED );
388 return INVALID_HANDLE_VALUE;
390 goto done;
392 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
394 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
396 else if (filename[4])
398 ret = VXD_Open( filename+4, access, sa );
399 goto done;
401 else
403 SetLastError( ERROR_INVALID_NAME );
404 return INVALID_HANDLE_VALUE;
407 else dosdev = RtlIsDosDeviceName_U( filename );
409 if (dosdev)
411 static const WCHAR conW[] = {'C','O','N'};
413 if (LOWORD(dosdev) == sizeof(conW) &&
414 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
416 switch (access & (GENERIC_READ|GENERIC_WRITE))
418 case GENERIC_READ:
419 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
420 goto done;
421 case GENERIC_WRITE:
422 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
423 goto done;
424 default:
425 SetLastError( ERROR_FILE_NOT_FOUND );
426 return INVALID_HANDLE_VALUE;
431 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
433 SetLastError( ERROR_PATH_NOT_FOUND );
434 return INVALID_HANDLE_VALUE;
437 /* now call NtCreateFile */
439 options = 0;
440 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
441 options |= FILE_OPEN_FOR_BACKUP_INTENT;
442 else
443 options |= FILE_NON_DIRECTORY_FILE;
444 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
445 options |= FILE_DELETE_ON_CLOSE;
446 if (!(attributes & FILE_FLAG_OVERLAPPED))
447 options |= FILE_SYNCHRONOUS_IO_ALERT;
448 if (attributes & FILE_FLAG_RANDOM_ACCESS)
449 options |= FILE_RANDOM_ACCESS;
450 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
452 attr.Length = sizeof(attr);
453 attr.RootDirectory = 0;
454 attr.Attributes = OBJ_CASE_INSENSITIVE;
455 attr.ObjectName = &nameW;
456 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
457 attr.SecurityQualityOfService = NULL;
459 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
461 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
462 sharing, nt_disposition[creation - CREATE_NEW],
463 options, NULL, 0 );
464 if (status)
466 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
467 ret = INVALID_HANDLE_VALUE;
469 /* In the case file creation was rejected due to CREATE_NEW flag
470 * was specified and file with that name already exists, correct
471 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
472 * Note: RtlNtStatusToDosError is not the subject to blame here.
474 if (status == STATUS_OBJECT_NAME_COLLISION)
475 SetLastError( ERROR_FILE_EXISTS );
476 else
477 SetLastError( RtlNtStatusToDosError(status) );
479 else SetLastError(0);
480 RtlFreeUnicodeString( &nameW );
482 done:
483 if (!ret) ret = INVALID_HANDLE_VALUE;
484 TRACE("returning %p\n", ret);
485 return ret;
490 /*************************************************************************
491 * CreateFileA (KERNEL32.@)
493 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
494 LPSECURITY_ATTRIBUTES sa, DWORD creation,
495 DWORD attributes, HANDLE template)
497 UNICODE_STRING filenameW;
498 HANDLE ret = INVALID_HANDLE_VALUE;
500 if (!filename)
502 SetLastError( ERROR_INVALID_PARAMETER );
503 return INVALID_HANDLE_VALUE;
506 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
508 ret = CreateFileW(filenameW.Buffer, access, sharing, sa, creation,
509 attributes, template);
510 RtlFreeUnicodeString(&filenameW);
512 else
513 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
514 return ret;
518 /***********************************************************************
519 * FILE_FillInfo
521 * Fill a file information from a struct stat.
523 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
525 if (S_ISDIR(st->st_mode))
526 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
527 else
528 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
529 if (!(st->st_mode & S_IWUSR))
530 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
532 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftCreationTime );
533 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftLastWriteTime );
534 RtlSecondsSince1970ToTime( st->st_atime, (LARGE_INTEGER *)&info->ftLastAccessTime );
536 info->dwVolumeSerialNumber = 0; /* FIXME */
537 if (S_ISDIR(st->st_mode))
539 info->nFileSizeHigh = 0;
540 info->nFileSizeLow = 0;
541 info->nNumberOfLinks = 1;
543 else
545 info->nFileSizeHigh = st->st_size >> 32;
546 info->nFileSizeLow = (DWORD)st->st_size;
547 info->nNumberOfLinks = st->st_nlink;
549 info->nFileIndexHigh = st->st_ino >> 32;
550 info->nFileIndexLow = (DWORD)st->st_ino;
554 /***********************************************************************
555 * get_show_dot_files_option
557 static BOOL get_show_dot_files_option(void)
559 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
560 'S','o','f','t','w','a','r','e','\\',
561 'W','i','n','e','\\','W','i','n','e','\\',
562 'C','o','n','f','i','g','\\','W','i','n','e',0};
563 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
565 char tmp[80];
566 HKEY hkey;
567 DWORD dummy;
568 OBJECT_ATTRIBUTES attr;
569 UNICODE_STRING nameW;
570 BOOL ret = FALSE;
572 attr.Length = sizeof(attr);
573 attr.RootDirectory = 0;
574 attr.ObjectName = &nameW;
575 attr.Attributes = 0;
576 attr.SecurityDescriptor = NULL;
577 attr.SecurityQualityOfService = NULL;
578 RtlInitUnicodeString( &nameW, WineW );
580 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
582 RtlInitUnicodeString( &nameW, ShowDotFilesW );
583 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
585 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
586 ret = IS_OPTION_TRUE( str[0] );
588 NtClose( hkey );
590 return ret;
594 /***********************************************************************
595 * FILE_Stat
597 * Stat a Unix path name. Return TRUE if OK.
599 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info, BOOL *is_symlink_ptr )
601 struct stat st;
602 int is_symlink;
603 LPCSTR p;
605 if (lstat( unixName, &st ) == -1)
607 FILE_SetDosError();
608 return FALSE;
610 is_symlink = S_ISLNK(st.st_mode);
611 if (is_symlink)
613 /* do a "real" stat to find out
614 about the type of the symlink destination */
615 if (stat( unixName, &st ) == -1)
617 FILE_SetDosError();
618 return FALSE;
622 /* fill in the information we gathered so far */
623 FILE_FillInfo( &st, info );
625 /* and now see if this is a hidden file, based on the name */
626 p = strrchr( unixName, '/');
627 p = p ? p + 1 : unixName;
628 if (*p == '.' && *(p+1) && (*(p+1) != '.' || *(p+2)))
630 static int show_dot_files = -1;
631 if (show_dot_files == -1)
632 show_dot_files = get_show_dot_files_option();
633 if (!show_dot_files)
634 info->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
636 if (is_symlink_ptr) *is_symlink_ptr = is_symlink;
637 return TRUE;
641 /***********************************************************************
642 * GetFileInformationByHandle (KERNEL32.@)
644 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
646 NTSTATUS status;
647 int fd;
648 BOOL ret = FALSE;
650 TRACE("%p,%p\n", hFile, info);
652 if (!info) return 0;
654 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
656 struct stat st;
658 if (fstat( fd, &st ) == -1)
659 FILE_SetDosError();
660 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
661 SetLastError( ERROR_INVALID_FUNCTION );
662 else
664 FILE_FillInfo( &st, info );
665 ret = TRUE;
667 wine_server_release_fd( hFile, fd );
669 else SetLastError( RtlNtStatusToDosError(status) );
671 return ret;
675 /***********************************************************************
676 * GetFileTime (KERNEL32.@)
678 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
679 FILETIME *lpLastAccessTime,
680 FILETIME *lpLastWriteTime )
682 BY_HANDLE_FILE_INFORMATION info;
683 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
684 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
685 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
686 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
687 return TRUE;
691 /***********************************************************************
692 * GetTempFileNameA (KERNEL32.@)
694 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
695 LPSTR buffer)
697 UNICODE_STRING pathW, prefixW;
698 WCHAR bufferW[MAX_PATH];
699 UINT ret;
701 if ( !path || !prefix || !buffer )
703 SetLastError( ERROR_INVALID_PARAMETER );
704 return 0;
707 RtlCreateUnicodeStringFromAsciiz(&pathW, path);
708 RtlCreateUnicodeStringFromAsciiz(&prefixW, prefix);
710 ret = GetTempFileNameW(pathW.Buffer, prefixW.Buffer, unique, bufferW);
711 if (ret)
712 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, MAX_PATH, NULL, NULL);
714 RtlFreeUnicodeString(&pathW);
715 RtlFreeUnicodeString(&prefixW);
716 return ret;
719 /***********************************************************************
720 * GetTempFileNameW (KERNEL32.@)
722 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
723 LPWSTR buffer )
725 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
727 int i;
728 LPWSTR p;
730 if ( !path || !prefix || !buffer )
732 SetLastError( ERROR_INVALID_PARAMETER );
733 return 0;
736 strcpyW( buffer, path );
737 p = buffer + strlenW(buffer);
739 /* add a \, if there isn't one */
740 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
742 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
744 unique &= 0xffff;
746 if (unique) sprintfW( p, formatW, unique );
747 else
749 /* get a "random" unique number and try to create the file */
750 HANDLE handle;
751 UINT num = GetTickCount() & 0xffff;
753 if (!num) num = 1;
754 unique = num;
757 sprintfW( p, formatW, unique );
758 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
759 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
760 if (handle != INVALID_HANDLE_VALUE)
761 { /* We created it */
762 TRACE("created %s\n", debugstr_w(buffer) );
763 CloseHandle( handle );
764 break;
766 if (GetLastError() != ERROR_FILE_EXISTS &&
767 GetLastError() != ERROR_SHARING_VIOLATION)
768 break; /* No need to go on */
769 if (!(++unique & 0xffff)) unique = 1;
770 } while (unique != num);
773 TRACE("returning %s\n", debugstr_w(buffer) );
774 return unique;
778 /******************************************************************
779 * FILE_ReadWriteApc (internal)
783 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
785 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
787 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
790 /***********************************************************************
791 * ReadFileEx (KERNEL32.@)
793 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
794 LPOVERLAPPED overlapped,
795 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
797 LARGE_INTEGER offset;
798 NTSTATUS status;
799 PIO_STATUS_BLOCK io_status;
801 if (!overlapped)
803 SetLastError(ERROR_INVALID_PARAMETER);
804 return FALSE;
807 offset.u.LowPart = overlapped->Offset;
808 offset.u.HighPart = overlapped->OffsetHigh;
809 io_status = (PIO_STATUS_BLOCK)overlapped;
810 io_status->u.Status = STATUS_PENDING;
812 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
813 io_status, buffer, bytesToRead, &offset, NULL);
815 if (status)
817 SetLastError( RtlNtStatusToDosError(status) );
818 return FALSE;
820 return TRUE;
823 /***********************************************************************
824 * ReadFile (KERNEL32.@)
826 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
827 LPDWORD bytesRead, LPOVERLAPPED overlapped )
829 LARGE_INTEGER offset;
830 PLARGE_INTEGER poffset = NULL;
831 IO_STATUS_BLOCK iosb;
832 PIO_STATUS_BLOCK io_status = &iosb;
833 HANDLE hEvent = 0;
834 NTSTATUS status;
836 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
837 bytesRead, overlapped );
839 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
840 if (!bytesToRead) return TRUE;
842 if (IsBadReadPtr(buffer, bytesToRead))
844 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
845 return FALSE;
847 if (is_console_handle(hFile))
848 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
850 if (overlapped != NULL)
852 offset.u.LowPart = overlapped->Offset;
853 offset.u.HighPart = overlapped->OffsetHigh;
854 poffset = &offset;
855 hEvent = overlapped->hEvent;
856 io_status = (PIO_STATUS_BLOCK)overlapped;
858 io_status->u.Status = STATUS_PENDING;
859 io_status->Information = 0;
861 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
863 if (status != STATUS_PENDING && bytesRead)
864 *bytesRead = io_status->Information;
866 if (status && status != STATUS_END_OF_FILE)
868 SetLastError( RtlNtStatusToDosError(status) );
869 return FALSE;
871 return TRUE;
875 /***********************************************************************
876 * WriteFileEx (KERNEL32.@)
878 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
879 LPOVERLAPPED overlapped,
880 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
882 LARGE_INTEGER offset;
883 NTSTATUS status;
884 PIO_STATUS_BLOCK io_status;
886 TRACE("%p %p %ld %p %p\n",
887 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
889 if (overlapped == NULL)
891 SetLastError(ERROR_INVALID_PARAMETER);
892 return FALSE;
894 offset.u.LowPart = overlapped->Offset;
895 offset.u.HighPart = overlapped->OffsetHigh;
897 io_status = (PIO_STATUS_BLOCK)overlapped;
898 io_status->u.Status = STATUS_PENDING;
900 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
901 io_status, buffer, bytesToWrite, &offset, NULL);
903 if (status) SetLastError( RtlNtStatusToDosError(status) );
904 return !status;
907 /***********************************************************************
908 * WriteFile (KERNEL32.@)
910 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
911 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
913 HANDLE hEvent = NULL;
914 LARGE_INTEGER offset;
915 PLARGE_INTEGER poffset = NULL;
916 NTSTATUS status;
917 IO_STATUS_BLOCK iosb;
918 PIO_STATUS_BLOCK piosb = &iosb;
920 TRACE("%p %p %ld %p %p\n",
921 hFile, buffer, bytesToWrite, bytesWritten, overlapped );
923 if (is_console_handle(hFile))
924 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
926 if (IsBadReadPtr(buffer, bytesToWrite))
928 SetLastError(ERROR_READ_FAULT); /* FIXME */
929 return FALSE;
932 if (overlapped)
934 offset.u.LowPart = overlapped->Offset;
935 offset.u.HighPart = overlapped->OffsetHigh;
936 poffset = &offset;
937 hEvent = overlapped->hEvent;
938 piosb = (PIO_STATUS_BLOCK)overlapped;
940 piosb->u.Status = STATUS_PENDING;
941 piosb->Information = 0;
943 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
944 buffer, bytesToWrite, poffset, NULL);
945 if (status)
947 SetLastError( RtlNtStatusToDosError(status) );
948 return FALSE;
950 if (bytesWritten) *bytesWritten = piosb->Information;
952 return TRUE;
956 /***********************************************************************
957 * SetFilePointer (KERNEL32.@)
959 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
960 DWORD method )
962 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
963 DWORD ret = INVALID_SET_FILE_POINTER;
964 NTSTATUS status;
965 int fd;
967 TRACE("handle %p offset %ld high %ld origin %ld\n",
968 hFile, distance, highword?*highword:0, method );
970 if (method > FILE_END)
972 SetLastError( ERROR_INVALID_PARAMETER );
973 return ret;
976 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
978 off_t pos, res;
980 if (highword) pos = ((off_t)*highword << 32) | (ULONG)distance;
981 else pos = (off_t)distance;
982 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
984 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
985 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
986 SetLastError( ERROR_NEGATIVE_SEEK );
987 else
988 FILE_SetDosError();
990 else
992 ret = (DWORD)res;
993 if (highword) *highword = (res >> 32);
994 if (ret == INVALID_SET_FILE_POINTER) SetLastError( 0 );
996 wine_server_release_fd( hFile, fd );
998 else SetLastError( RtlNtStatusToDosError(status) );
1000 return ret;
1004 /*************************************************************************
1005 * SetHandleCount (KERNEL32.@)
1007 UINT WINAPI SetHandleCount( UINT count )
1009 return min( 256, count );
1013 /**************************************************************************
1014 * SetEndOfFile (KERNEL32.@)
1016 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1018 BOOL ret;
1019 SERVER_START_REQ( truncate_file )
1021 req->handle = hFile;
1022 ret = !wine_server_call_err( req );
1024 SERVER_END_REQ;
1025 return ret;
1029 /***********************************************************************
1030 * GetFileType (KERNEL32.@)
1032 DWORD WINAPI GetFileType( HANDLE hFile )
1034 NTSTATUS status;
1035 int fd;
1036 DWORD ret = FILE_TYPE_UNKNOWN;
1038 if (is_console_handle( hFile ))
1039 return FILE_TYPE_CHAR;
1041 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
1043 struct stat st;
1045 if (fstat( fd, &st ) == -1)
1046 FILE_SetDosError();
1047 else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
1048 ret = FILE_TYPE_PIPE;
1049 else if (S_ISCHR(st.st_mode))
1050 ret = FILE_TYPE_CHAR;
1051 else
1052 ret = FILE_TYPE_DISK;
1053 wine_server_release_fd( hFile, fd );
1055 else SetLastError( RtlNtStatusToDosError(status) );
1057 return ret;
1061 /**************************************************************************
1062 * CopyFileW (KERNEL32.@)
1064 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1066 HANDLE h1, h2;
1067 BY_HANDLE_FILE_INFORMATION info;
1068 DWORD count;
1069 BOOL ret = FALSE;
1070 char buffer[2048];
1072 if (!source || !dest)
1074 SetLastError(ERROR_INVALID_PARAMETER);
1075 return FALSE;
1078 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
1080 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1081 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1083 WARN("Unable to open source %s\n", debugstr_w(source));
1084 return FALSE;
1087 if (!GetFileInformationByHandle( h1, &info ))
1089 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1090 CloseHandle( h1 );
1091 return FALSE;
1094 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1095 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
1096 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1098 WARN("Unable to open dest %s\n", debugstr_w(dest));
1099 CloseHandle( h1 );
1100 return FALSE;
1103 while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
1105 char *p = buffer;
1106 while (count != 0)
1108 DWORD res;
1109 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1110 p += res;
1111 count -= res;
1114 ret = TRUE;
1115 done:
1116 CloseHandle( h1 );
1117 CloseHandle( h2 );
1118 return ret;
1122 /**************************************************************************
1123 * CopyFileA (KERNEL32.@)
1125 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1127 UNICODE_STRING sourceW, destW;
1128 BOOL ret;
1130 if (!source || !dest)
1132 SetLastError(ERROR_INVALID_PARAMETER);
1133 return FALSE;
1136 RtlCreateUnicodeStringFromAsciiz(&sourceW, source);
1137 RtlCreateUnicodeStringFromAsciiz(&destW, dest);
1139 ret = CopyFileW(sourceW.Buffer, destW.Buffer, fail_if_exists);
1141 RtlFreeUnicodeString(&sourceW);
1142 RtlFreeUnicodeString(&destW);
1143 return ret;
1147 /**************************************************************************
1148 * CopyFileExW (KERNEL32.@)
1150 * This implementation ignores most of the extra parameters passed-in into
1151 * the "ex" version of the method and calls the CopyFile method.
1152 * It will have to be fixed eventually.
1154 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
1155 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1156 LPBOOL cancelFlagPointer, DWORD copyFlags)
1159 * Interpret the only flag that CopyFile can interpret.
1161 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
1165 /**************************************************************************
1166 * CopyFileExA (KERNEL32.@)
1168 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1169 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1170 LPBOOL cancelFlagPointer, DWORD copyFlags)
1172 UNICODE_STRING sourceW, destW;
1173 BOOL ret;
1175 if (!sourceFilename || !destFilename)
1177 SetLastError(ERROR_INVALID_PARAMETER);
1178 return FALSE;
1181 RtlCreateUnicodeStringFromAsciiz(&sourceW, sourceFilename);
1182 RtlCreateUnicodeStringFromAsciiz(&destW, destFilename);
1184 ret = CopyFileExW(sourceW.Buffer, destW.Buffer, progressRoutine, appData,
1185 cancelFlagPointer, copyFlags);
1187 RtlFreeUnicodeString(&sourceW);
1188 RtlFreeUnicodeString(&destW);
1189 return ret;