Use a passed SecurityDescriptor in CreateFileW.
[wine.git] / files / file.c
blob18d27464ac614ab074a1bd68a1216603f5d99412
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',0};
412 WCHAR dev[5];
414 memcpy( dev, filename + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
415 dev[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
417 TRACE("opening device %s\n", debugstr_w(dev) );
419 if (!strcmpiW( dev, conW ))
421 switch (access & (GENERIC_READ|GENERIC_WRITE))
423 case GENERIC_READ:
424 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
425 goto done;
426 case GENERIC_WRITE:
427 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
428 goto done;
429 default:
430 SetLastError( ERROR_FILE_NOT_FOUND );
431 return INVALID_HANDLE_VALUE;
435 ret = VOLUME_OpenDevice( dev, access, sharing, sa, attributes );
436 goto done;
439 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
441 SetLastError( ERROR_PATH_NOT_FOUND );
442 return INVALID_HANDLE_VALUE;
445 /* now call NtCreateFile */
447 options = 0;
448 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
449 options |= FILE_OPEN_FOR_BACKUP_INTENT;
450 else
451 options |= FILE_NON_DIRECTORY_FILE;
452 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
453 options |= FILE_DELETE_ON_CLOSE;
454 if (!(attributes & FILE_FLAG_OVERLAPPED))
455 options |= FILE_SYNCHRONOUS_IO_ALERT;
456 if (attributes & FILE_FLAG_RANDOM_ACCESS)
457 options |= FILE_RANDOM_ACCESS;
458 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
460 attr.Length = sizeof(attr);
461 attr.RootDirectory = 0;
462 attr.Attributes = OBJ_CASE_INSENSITIVE;
463 attr.ObjectName = &nameW;
464 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
465 attr.SecurityQualityOfService = NULL;
467 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
469 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
470 sharing, nt_disposition[creation - CREATE_NEW],
471 options, NULL, 0 );
472 if (status)
474 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
475 ret = INVALID_HANDLE_VALUE;
477 /* In the case file creation was rejected due to CREATE_NEW flag
478 * was specified and file with that name already exists, correct
479 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
480 * Note: RtlNtStatusToDosError is not the subject to blame here.
482 if (status == STATUS_OBJECT_NAME_COLLISION)
483 SetLastError( ERROR_FILE_EXISTS );
484 else
485 SetLastError( RtlNtStatusToDosError(status) );
487 else SetLastError(0);
488 RtlFreeUnicodeString( &nameW );
490 done:
491 if (!ret) ret = INVALID_HANDLE_VALUE;
492 TRACE("returning %p\n", ret);
493 return ret;
498 /*************************************************************************
499 * CreateFileA (KERNEL32.@)
501 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
502 LPSECURITY_ATTRIBUTES sa, DWORD creation,
503 DWORD attributes, HANDLE template)
505 UNICODE_STRING filenameW;
506 HANDLE ret = INVALID_HANDLE_VALUE;
508 if (!filename)
510 SetLastError( ERROR_INVALID_PARAMETER );
511 return INVALID_HANDLE_VALUE;
514 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
516 ret = CreateFileW(filenameW.Buffer, access, sharing, sa, creation,
517 attributes, template);
518 RtlFreeUnicodeString(&filenameW);
520 else
521 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
522 return ret;
526 /***********************************************************************
527 * FILE_FillInfo
529 * Fill a file information from a struct stat.
531 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
533 if (S_ISDIR(st->st_mode))
534 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
535 else
536 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
537 if (!(st->st_mode & S_IWUSR))
538 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
540 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftCreationTime );
541 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftLastWriteTime );
542 RtlSecondsSince1970ToTime( st->st_atime, (LARGE_INTEGER *)&info->ftLastAccessTime );
544 info->dwVolumeSerialNumber = 0; /* FIXME */
545 if (S_ISDIR(st->st_mode))
547 info->nFileSizeHigh = 0;
548 info->nFileSizeLow = 0;
549 info->nNumberOfLinks = 1;
551 else
553 info->nFileSizeHigh = st->st_size >> 32;
554 info->nFileSizeLow = (DWORD)st->st_size;
555 info->nNumberOfLinks = st->st_nlink;
557 info->nFileIndexHigh = st->st_ino >> 32;
558 info->nFileIndexLow = (DWORD)st->st_ino;
562 /***********************************************************************
563 * get_show_dot_files_option
565 static BOOL get_show_dot_files_option(void)
567 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
568 'S','o','f','t','w','a','r','e','\\',
569 'W','i','n','e','\\','W','i','n','e','\\',
570 'C','o','n','f','i','g','\\','W','i','n','e',0};
571 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
573 char tmp[80];
574 HKEY hkey;
575 DWORD dummy;
576 OBJECT_ATTRIBUTES attr;
577 UNICODE_STRING nameW;
578 BOOL ret = FALSE;
580 attr.Length = sizeof(attr);
581 attr.RootDirectory = 0;
582 attr.ObjectName = &nameW;
583 attr.Attributes = 0;
584 attr.SecurityDescriptor = NULL;
585 attr.SecurityQualityOfService = NULL;
586 RtlInitUnicodeString( &nameW, WineW );
588 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
590 RtlInitUnicodeString( &nameW, ShowDotFilesW );
591 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
593 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
594 ret = IS_OPTION_TRUE( str[0] );
596 NtClose( hkey );
598 return ret;
602 /***********************************************************************
603 * FILE_Stat
605 * Stat a Unix path name. Return TRUE if OK.
607 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info, BOOL *is_symlink_ptr )
609 struct stat st;
610 int is_symlink;
611 LPCSTR p;
613 if (lstat( unixName, &st ) == -1)
615 FILE_SetDosError();
616 return FALSE;
618 is_symlink = S_ISLNK(st.st_mode);
619 if (is_symlink)
621 /* do a "real" stat to find out
622 about the type of the symlink destination */
623 if (stat( unixName, &st ) == -1)
625 FILE_SetDosError();
626 return FALSE;
630 /* fill in the information we gathered so far */
631 FILE_FillInfo( &st, info );
633 /* and now see if this is a hidden file, based on the name */
634 p = strrchr( unixName, '/');
635 p = p ? p + 1 : unixName;
636 if (*p == '.' && *(p+1) && (*(p+1) != '.' || *(p+2)))
638 static int show_dot_files = -1;
639 if (show_dot_files == -1)
640 show_dot_files = get_show_dot_files_option();
641 if (!show_dot_files)
642 info->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
644 if (is_symlink_ptr) *is_symlink_ptr = is_symlink;
645 return TRUE;
649 /***********************************************************************
650 * GetFileInformationByHandle (KERNEL32.@)
652 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
654 NTSTATUS status;
655 int fd;
656 BOOL ret = FALSE;
658 TRACE("%p,%p\n", hFile, info);
660 if (!info) return 0;
662 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
664 struct stat st;
666 if (fstat( fd, &st ) == -1)
667 FILE_SetDosError();
668 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
669 SetLastError( ERROR_INVALID_FUNCTION );
670 else
672 FILE_FillInfo( &st, info );
673 ret = TRUE;
675 wine_server_release_fd( hFile, fd );
677 else SetLastError( RtlNtStatusToDosError(status) );
679 return ret;
683 /***********************************************************************
684 * GetFileTime (KERNEL32.@)
686 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
687 FILETIME *lpLastAccessTime,
688 FILETIME *lpLastWriteTime )
690 BY_HANDLE_FILE_INFORMATION info;
691 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
692 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
693 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
694 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
695 return TRUE;
699 /***********************************************************************
700 * GetTempFileNameA (KERNEL32.@)
702 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
703 LPSTR buffer)
705 UNICODE_STRING pathW, prefixW;
706 WCHAR bufferW[MAX_PATH];
707 UINT ret;
709 if ( !path || !prefix || !buffer )
711 SetLastError( ERROR_INVALID_PARAMETER );
712 return 0;
715 RtlCreateUnicodeStringFromAsciiz(&pathW, path);
716 RtlCreateUnicodeStringFromAsciiz(&prefixW, prefix);
718 ret = GetTempFileNameW(pathW.Buffer, prefixW.Buffer, unique, bufferW);
719 if (ret)
720 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, MAX_PATH, NULL, NULL);
722 RtlFreeUnicodeString(&pathW);
723 RtlFreeUnicodeString(&prefixW);
724 return ret;
727 /***********************************************************************
728 * GetTempFileNameW (KERNEL32.@)
730 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
731 LPWSTR buffer )
733 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
735 DOS_FULL_NAME full_name;
736 int i;
737 LPWSTR p;
739 if ( !path || !prefix || !buffer )
741 SetLastError( ERROR_INVALID_PARAMETER );
742 return 0;
745 strcpyW( buffer, path );
746 p = buffer + strlenW(buffer);
748 /* add a \, if there isn't one */
749 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
751 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
753 unique &= 0xffff;
755 if (unique) sprintfW( p, formatW, unique );
756 else
758 /* get a "random" unique number and try to create the file */
759 HANDLE handle;
760 UINT num = GetTickCount() & 0xffff;
762 if (!num) num = 1;
763 unique = num;
766 sprintfW( p, formatW, unique );
767 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
768 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
769 if (handle != INVALID_HANDLE_VALUE)
770 { /* We created it */
771 TRACE("created %s\n", debugstr_w(buffer) );
772 CloseHandle( handle );
773 break;
775 if (GetLastError() != ERROR_FILE_EXISTS &&
776 GetLastError() != ERROR_SHARING_VIOLATION)
777 break; /* No need to go on */
778 if (!(++unique & 0xffff)) unique = 1;
779 } while (unique != num);
782 /* Get the full path name */
784 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
786 char *slash;
787 /* Check if we have write access in the directory */
788 if ((slash = strrchr( full_name.long_name, '/' ))) *slash = '\0';
789 if (access( full_name.long_name, W_OK ) == -1)
790 WARN("returns %s, which doesn't seem to be writeable.\n",
791 debugstr_w(buffer) );
793 TRACE("returning %s\n", debugstr_w(buffer) );
794 return unique;
798 /******************************************************************
799 * FILE_ReadWriteApc (internal)
803 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
805 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
807 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
810 /***********************************************************************
811 * ReadFileEx (KERNEL32.@)
813 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
814 LPOVERLAPPED overlapped,
815 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
817 LARGE_INTEGER offset;
818 NTSTATUS status;
819 PIO_STATUS_BLOCK io_status;
821 if (!overlapped)
823 SetLastError(ERROR_INVALID_PARAMETER);
824 return FALSE;
827 offset.u.LowPart = overlapped->Offset;
828 offset.u.HighPart = overlapped->OffsetHigh;
829 io_status = (PIO_STATUS_BLOCK)overlapped;
830 io_status->u.Status = STATUS_PENDING;
832 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
833 io_status, buffer, bytesToRead, &offset, NULL);
835 if (status)
837 SetLastError( RtlNtStatusToDosError(status) );
838 return FALSE;
840 return TRUE;
843 /***********************************************************************
844 * ReadFile (KERNEL32.@)
846 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
847 LPDWORD bytesRead, LPOVERLAPPED overlapped )
849 LARGE_INTEGER offset;
850 PLARGE_INTEGER poffset = NULL;
851 IO_STATUS_BLOCK iosb;
852 PIO_STATUS_BLOCK io_status = &iosb;
853 HANDLE hEvent = 0;
854 NTSTATUS status;
856 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
857 bytesRead, overlapped );
859 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
860 if (!bytesToRead) return TRUE;
862 if (IsBadReadPtr(buffer, bytesToRead))
864 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
865 return FALSE;
867 if (is_console_handle(hFile))
868 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
870 if (overlapped != NULL)
872 offset.u.LowPart = overlapped->Offset;
873 offset.u.HighPart = overlapped->OffsetHigh;
874 poffset = &offset;
875 hEvent = overlapped->hEvent;
876 io_status = (PIO_STATUS_BLOCK)overlapped;
878 io_status->u.Status = STATUS_PENDING;
879 io_status->Information = 0;
881 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
883 if (status != STATUS_PENDING && bytesRead)
884 *bytesRead = io_status->Information;
886 if (status && status != STATUS_END_OF_FILE)
888 SetLastError( RtlNtStatusToDosError(status) );
889 return FALSE;
891 return TRUE;
895 /***********************************************************************
896 * WriteFileEx (KERNEL32.@)
898 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
899 LPOVERLAPPED overlapped,
900 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
902 LARGE_INTEGER offset;
903 NTSTATUS status;
904 PIO_STATUS_BLOCK io_status;
906 TRACE("%p %p %ld %p %p\n",
907 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
909 if (overlapped == NULL)
911 SetLastError(ERROR_INVALID_PARAMETER);
912 return FALSE;
914 offset.u.LowPart = overlapped->Offset;
915 offset.u.HighPart = overlapped->OffsetHigh;
917 io_status = (PIO_STATUS_BLOCK)overlapped;
918 io_status->u.Status = STATUS_PENDING;
920 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
921 io_status, buffer, bytesToWrite, &offset, NULL);
923 if (status) SetLastError( RtlNtStatusToDosError(status) );
924 return !status;
927 /***********************************************************************
928 * WriteFile (KERNEL32.@)
930 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
931 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
933 HANDLE hEvent = NULL;
934 LARGE_INTEGER offset;
935 PLARGE_INTEGER poffset = NULL;
936 NTSTATUS status;
937 IO_STATUS_BLOCK iosb;
938 PIO_STATUS_BLOCK piosb = &iosb;
940 TRACE("%p %p %ld %p %p\n",
941 hFile, buffer, bytesToWrite, bytesWritten, overlapped );
943 if (is_console_handle(hFile))
944 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
946 if (IsBadReadPtr(buffer, bytesToWrite))
948 SetLastError(ERROR_READ_FAULT); /* FIXME */
949 return FALSE;
952 if (overlapped)
954 offset.u.LowPart = overlapped->Offset;
955 offset.u.HighPart = overlapped->OffsetHigh;
956 poffset = &offset;
957 hEvent = overlapped->hEvent;
958 piosb = (PIO_STATUS_BLOCK)overlapped;
960 piosb->u.Status = STATUS_PENDING;
961 piosb->Information = 0;
963 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
964 buffer, bytesToWrite, poffset, NULL);
965 if (status)
967 SetLastError( RtlNtStatusToDosError(status) );
968 return FALSE;
970 if (bytesWritten) *bytesWritten = piosb->Information;
972 return TRUE;
976 /***********************************************************************
977 * SetFilePointer (KERNEL32.@)
979 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
980 DWORD method )
982 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
983 DWORD ret = INVALID_SET_FILE_POINTER;
984 NTSTATUS status;
985 int fd;
987 TRACE("handle %p offset %ld high %ld origin %ld\n",
988 hFile, distance, highword?*highword:0, method );
990 if (method > FILE_END)
992 SetLastError( ERROR_INVALID_PARAMETER );
993 return ret;
996 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
998 off_t pos, res;
1000 if (highword) pos = ((off_t)*highword << 32) | (ULONG)distance;
1001 else pos = (off_t)distance;
1002 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
1004 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
1005 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
1006 SetLastError( ERROR_NEGATIVE_SEEK );
1007 else
1008 FILE_SetDosError();
1010 else
1012 ret = (DWORD)res;
1013 if (highword) *highword = (res >> 32);
1014 if (ret == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1016 wine_server_release_fd( hFile, fd );
1018 else SetLastError( RtlNtStatusToDosError(status) );
1020 return ret;
1024 /*************************************************************************
1025 * SetHandleCount (KERNEL32.@)
1027 UINT WINAPI SetHandleCount( UINT count )
1029 return min( 256, count );
1033 /**************************************************************************
1034 * SetEndOfFile (KERNEL32.@)
1036 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1038 BOOL ret;
1039 SERVER_START_REQ( truncate_file )
1041 req->handle = hFile;
1042 ret = !wine_server_call_err( req );
1044 SERVER_END_REQ;
1045 return ret;
1049 /***********************************************************************
1050 * GetFileType (KERNEL32.@)
1052 DWORD WINAPI GetFileType( HANDLE hFile )
1054 NTSTATUS status;
1055 int fd;
1056 DWORD ret = FILE_TYPE_UNKNOWN;
1058 if (is_console_handle( hFile ))
1059 return FILE_TYPE_CHAR;
1061 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
1063 struct stat st;
1065 if (fstat( fd, &st ) == -1)
1066 FILE_SetDosError();
1067 else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
1068 ret = FILE_TYPE_PIPE;
1069 else if (S_ISCHR(st.st_mode))
1070 ret = FILE_TYPE_CHAR;
1071 else
1072 ret = FILE_TYPE_DISK;
1073 wine_server_release_fd( hFile, fd );
1075 else SetLastError( RtlNtStatusToDosError(status) );
1077 return ret;
1081 /**************************************************************************
1082 * CopyFileW (KERNEL32.@)
1084 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1086 HANDLE h1, h2;
1087 BY_HANDLE_FILE_INFORMATION info;
1088 DWORD count;
1089 BOOL ret = FALSE;
1090 char buffer[2048];
1092 if (!source || !dest)
1094 SetLastError(ERROR_INVALID_PARAMETER);
1095 return FALSE;
1098 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
1100 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1101 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1103 WARN("Unable to open source %s\n", debugstr_w(source));
1104 return FALSE;
1107 if (!GetFileInformationByHandle( h1, &info ))
1109 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1110 CloseHandle( h1 );
1111 return FALSE;
1114 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1115 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
1116 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1118 WARN("Unable to open dest %s\n", debugstr_w(dest));
1119 CloseHandle( h1 );
1120 return FALSE;
1123 while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
1125 char *p = buffer;
1126 while (count != 0)
1128 DWORD res;
1129 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1130 p += res;
1131 count -= res;
1134 ret = TRUE;
1135 done:
1136 CloseHandle( h1 );
1137 CloseHandle( h2 );
1138 return ret;
1142 /**************************************************************************
1143 * CopyFileA (KERNEL32.@)
1145 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1147 UNICODE_STRING sourceW, destW;
1148 BOOL ret;
1150 if (!source || !dest)
1152 SetLastError(ERROR_INVALID_PARAMETER);
1153 return FALSE;
1156 RtlCreateUnicodeStringFromAsciiz(&sourceW, source);
1157 RtlCreateUnicodeStringFromAsciiz(&destW, dest);
1159 ret = CopyFileW(sourceW.Buffer, destW.Buffer, fail_if_exists);
1161 RtlFreeUnicodeString(&sourceW);
1162 RtlFreeUnicodeString(&destW);
1163 return ret;
1167 /**************************************************************************
1168 * CopyFileExW (KERNEL32.@)
1170 * This implementation ignores most of the extra parameters passed-in into
1171 * the "ex" version of the method and calls the CopyFile method.
1172 * It will have to be fixed eventually.
1174 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
1175 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1176 LPBOOL cancelFlagPointer, DWORD copyFlags)
1179 * Interpret the only flag that CopyFile can interpret.
1181 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
1185 /**************************************************************************
1186 * CopyFileExA (KERNEL32.@)
1188 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1189 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1190 LPBOOL cancelFlagPointer, DWORD copyFlags)
1192 UNICODE_STRING sourceW, destW;
1193 BOOL ret;
1195 if (!sourceFilename || !destFilename)
1197 SetLastError(ERROR_INVALID_PARAMETER);
1198 return FALSE;
1201 RtlCreateUnicodeStringFromAsciiz(&sourceW, sourceFilename);
1202 RtlCreateUnicodeStringFromAsciiz(&destW, destFilename);
1204 ret = CopyFileExW(sourceW.Buffer, destW.Buffer, progressRoutine, appData,
1205 cancelFlagPointer, copyFlags);
1207 RtlFreeUnicodeString(&sourceW);
1208 RtlFreeUnicodeString(&destW);
1209 return ret;