- more FIXME -> TRACE
[wine.git] / files / file.c
blob56aed44a424329cc742c9d35b03093153693269b
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
59 #define NONAMELESSUNION
60 #define NONAMELESSSTRUCT
61 #include "winerror.h"
62 #include "ntstatus.h"
63 #include "windef.h"
64 #include "winbase.h"
65 #include "winreg.h"
66 #include "winternl.h"
67 #include "wine/winbase16.h"
68 #include "wine/server.h"
70 #include "file.h"
71 #include "wincon.h"
72 #include "kernel_private.h"
74 #include "smb.h"
75 #include "wine/unicode.h"
76 #include "wine/debug.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(file);
80 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
81 #define MAP_ANON MAP_ANONYMOUS
82 #endif
84 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
86 #define SECSPERDAY 86400
87 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
89 /***********************************************************************
90 * FILE_ConvertOFMode
92 * Convert OF_* mode into flags for CreateFile.
94 void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
96 switch(mode & 0x03)
98 case OF_READ: *access = GENERIC_READ; break;
99 case OF_WRITE: *access = GENERIC_WRITE; break;
100 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
101 default: *access = 0; break;
103 switch(mode & 0x70)
105 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
106 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
107 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
108 case OF_SHARE_DENY_NONE:
109 case OF_SHARE_COMPAT:
110 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
115 /***********************************************************************
116 * FILE_SetDosError
118 * Set the DOS error code from errno.
120 void FILE_SetDosError(void)
122 int save_errno = errno; /* errno gets overwritten by printf */
124 TRACE("errno = %d %s\n", errno, strerror(errno));
125 switch (save_errno)
127 case EAGAIN:
128 SetLastError( ERROR_SHARING_VIOLATION );
129 break;
130 case EBADF:
131 SetLastError( ERROR_INVALID_HANDLE );
132 break;
133 case ENOSPC:
134 SetLastError( ERROR_HANDLE_DISK_FULL );
135 break;
136 case EACCES:
137 case EPERM:
138 case EROFS:
139 SetLastError( ERROR_ACCESS_DENIED );
140 break;
141 case EBUSY:
142 SetLastError( ERROR_LOCK_VIOLATION );
143 break;
144 case ENOENT:
145 SetLastError( ERROR_FILE_NOT_FOUND );
146 break;
147 case EISDIR:
148 SetLastError( ERROR_CANNOT_MAKE );
149 break;
150 case ENFILE:
151 case EMFILE:
152 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
153 break;
154 case EEXIST:
155 SetLastError( ERROR_FILE_EXISTS );
156 break;
157 case EINVAL:
158 case ESPIPE:
159 SetLastError( ERROR_SEEK );
160 break;
161 case ENOTEMPTY:
162 SetLastError( ERROR_DIR_NOT_EMPTY );
163 break;
164 case ENOEXEC:
165 SetLastError( ERROR_BAD_FORMAT );
166 break;
167 case ENOTDIR:
168 SetLastError( ERROR_PATH_NOT_FOUND );
169 break;
170 case EXDEV:
171 SetLastError( ERROR_NOT_SAME_DEVICE );
172 break;
173 default:
174 WARN("unknown file error: %s\n", strerror(save_errno) );
175 SetLastError( ERROR_GEN_FAILURE );
176 break;
178 errno = save_errno;
182 /***********************************************************************
183 * FILE_CreateFile
185 * Implementation of CreateFile. Takes a Unix path name.
186 * Returns 0 on failure.
188 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
189 LPSECURITY_ATTRIBUTES sa, DWORD creation,
190 DWORD attributes, HANDLE template )
192 unsigned int err;
193 UINT disp, options;
194 HANDLE ret;
196 switch (creation)
198 case CREATE_ALWAYS: disp = FILE_OVERWRITE_IF; break;
199 case CREATE_NEW: disp = FILE_CREATE; break;
200 case OPEN_ALWAYS: disp = FILE_OPEN_IF; break;
201 case OPEN_EXISTING: disp = FILE_OPEN; break;
202 case TRUNCATE_EXISTING: disp = FILE_OVERWRITE; break;
203 default:
204 SetLastError( ERROR_INVALID_PARAMETER );
205 return 0;
208 options = 0;
209 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
210 options |= FILE_OPEN_FOR_BACKUP_INTENT;
211 else
212 options |= FILE_NON_DIRECTORY_FILE;
213 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
214 options |= FILE_DELETE_ON_CLOSE;
215 if (!(attributes & FILE_FLAG_OVERLAPPED))
216 options |= FILE_SYNCHRONOUS_IO_ALERT;
217 if (attributes & FILE_FLAG_RANDOM_ACCESS)
218 options |= FILE_RANDOM_ACCESS;
219 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
221 SERVER_START_REQ( create_file )
223 req->access = access;
224 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
225 req->sharing = sharing;
226 req->create = disp;
227 req->options = options;
228 req->attrs = attributes;
229 wine_server_add_data( req, filename, strlen(filename) );
230 SetLastError(0);
231 err = wine_server_call( req );
232 ret = reply->handle;
234 SERVER_END_REQ;
236 if (err)
238 /* In the case file creation was rejected due to CREATE_NEW flag
239 * was specified and file with that name already exists, correct
240 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
241 * Note: RtlNtStatusToDosError is not the subject to blame here.
243 if (err == STATUS_OBJECT_NAME_COLLISION)
244 SetLastError( ERROR_FILE_EXISTS );
245 else
246 SetLastError( RtlNtStatusToDosError(err) );
249 if (!ret) WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
250 return ret;
254 static HANDLE FILE_OpenPipe(LPCWSTR name, DWORD access, LPSECURITY_ATTRIBUTES sa )
256 HANDLE ret;
257 DWORD len = 0;
259 if (name && (len = strlenW(name)) > MAX_PATH)
261 SetLastError( ERROR_FILENAME_EXCED_RANGE );
262 return 0;
264 SERVER_START_REQ( open_named_pipe )
266 req->access = access;
267 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
268 SetLastError(0);
269 wine_server_add_data( req, name, len * sizeof(WCHAR) );
270 wine_server_call_err( req );
271 ret = reply->handle;
273 SERVER_END_REQ;
274 TRACE("Returned %p\n",ret);
275 return ret;
278 /*************************************************************************
279 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
281 * Creates or opens an object, and returns a handle that can be used to
282 * access that object.
284 * PARAMS
286 * filename [in] pointer to filename to be accessed
287 * access [in] access mode requested
288 * sharing [in] share mode
289 * sa [in] pointer to security attributes
290 * creation [in] how to create the file
291 * attributes [in] attributes for newly created file
292 * template [in] handle to file with extended attributes to copy
294 * RETURNS
295 * Success: Open handle to specified file
296 * Failure: INVALID_HANDLE_VALUE
298 * NOTES
299 * Should call SetLastError() on failure.
301 * BUGS
303 * Doesn't support character devices, template files, or a
304 * lot of the 'attributes' flags yet.
306 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
307 LPSECURITY_ATTRIBUTES sa, DWORD creation,
308 DWORD attributes, HANDLE template )
310 NTSTATUS status;
311 UINT options;
312 OBJECT_ATTRIBUTES attr;
313 UNICODE_STRING nameW;
314 IO_STATUS_BLOCK io;
315 HANDLE ret;
316 DWORD dosdev;
317 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
318 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
319 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
321 static const char * const creation_name[5] =
322 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
324 static const UINT nt_disposition[5] =
326 FILE_CREATE, /* CREATE_NEW */
327 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
328 FILE_OPEN, /* OPEN_EXISTING */
329 FILE_OPEN_IF, /* OPEN_ALWAYS */
330 FILE_OVERWRITE /* TRUNCATE_EXISTING */
334 /* sanity checks */
336 if (!filename || !filename[0])
338 SetLastError( ERROR_PATH_NOT_FOUND );
339 return INVALID_HANDLE_VALUE;
342 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
344 SetLastError( ERROR_INVALID_PARAMETER );
345 return INVALID_HANDLE_VALUE;
348 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
349 (access & GENERIC_READ)?"GENERIC_READ ":"",
350 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
351 (!access)?"QUERY_ACCESS ":"",
352 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
353 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
354 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
355 creation_name[creation - CREATE_NEW], attributes);
357 /* Open a console for CONIN$ or CONOUT$ */
359 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
361 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
362 goto done;
365 if (!strncmpW(filename, bkslashes_with_dotW, 4))
367 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
368 if(!strncmpiW(filename + 4, pipeW, 5))
370 TRACE("Opening a pipe: %s\n", debugstr_w(filename));
371 ret = FILE_OpenPipe( filename, access, sa );
372 goto done;
374 else if (isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0')
376 const char *device = DRIVE_GetDevice( toupperW(filename[4]) - 'A' );
377 if (device)
379 ret = FILE_CreateFile( device, access, sharing, sa, creation,
380 attributes, template );
382 else
384 SetLastError( ERROR_ACCESS_DENIED );
385 return INVALID_HANDLE_VALUE;
387 goto done;
389 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
391 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
393 else if (filename[4])
395 ret = VXD_Open( filename+4, access, sa );
396 goto done;
398 else
400 SetLastError( ERROR_INVALID_NAME );
401 return INVALID_HANDLE_VALUE;
404 else dosdev = RtlIsDosDeviceName_U( filename );
406 if (dosdev)
408 static const WCHAR conW[] = {'C','O','N',0};
409 WCHAR dev[5];
411 memcpy( dev, filename + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
412 dev[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
414 TRACE("opening device %s\n", debugstr_w(dev) );
416 if (!strcmpiW( dev, conW ))
418 switch (access & (GENERIC_READ|GENERIC_WRITE))
420 case GENERIC_READ:
421 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
422 goto done;
423 case GENERIC_WRITE:
424 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
425 goto done;
426 default:
427 SetLastError( ERROR_FILE_NOT_FOUND );
428 return INVALID_HANDLE_VALUE;
432 ret = VOLUME_OpenDevice( dev, access, sharing, sa, attributes );
433 goto done;
436 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
438 SetLastError( ERROR_PATH_NOT_FOUND );
439 return INVALID_HANDLE_VALUE;
442 /* now call NtCreateFile */
444 options = 0;
445 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
446 options |= FILE_OPEN_FOR_BACKUP_INTENT;
447 else
448 options |= FILE_NON_DIRECTORY_FILE;
449 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
450 options |= FILE_DELETE_ON_CLOSE;
451 if (!(attributes & FILE_FLAG_OVERLAPPED))
452 options |= FILE_SYNCHRONOUS_IO_ALERT;
453 if (attributes & FILE_FLAG_RANDOM_ACCESS)
454 options |= FILE_RANDOM_ACCESS;
455 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
457 attr.Length = sizeof(attr);
458 attr.RootDirectory = 0;
459 attr.Attributes = OBJ_CASE_INSENSITIVE;
460 attr.ObjectName = &nameW;
461 attr.SecurityDescriptor = NULL;
462 attr.SecurityQualityOfService = NULL;
464 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
466 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
467 sharing, nt_disposition[creation - CREATE_NEW],
468 options, NULL, 0 );
469 if (status)
471 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
472 ret = INVALID_HANDLE_VALUE;
474 /* In the case file creation was rejected due to CREATE_NEW flag
475 * was specified and file with that name already exists, correct
476 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
477 * Note: RtlNtStatusToDosError is not the subject to blame here.
479 if (status == STATUS_OBJECT_NAME_COLLISION)
480 SetLastError( ERROR_FILE_EXISTS );
481 else
482 SetLastError( RtlNtStatusToDosError(status) );
484 else SetLastError(0);
485 RtlFreeUnicodeString( &nameW );
487 done:
488 if (!ret) ret = INVALID_HANDLE_VALUE;
489 TRACE("returning %p\n", ret);
490 return ret;
495 /*************************************************************************
496 * CreateFileA (KERNEL32.@)
498 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
499 LPSECURITY_ATTRIBUTES sa, DWORD creation,
500 DWORD attributes, HANDLE template)
502 UNICODE_STRING filenameW;
503 HANDLE ret = INVALID_HANDLE_VALUE;
505 if (!filename)
507 SetLastError( ERROR_INVALID_PARAMETER );
508 return INVALID_HANDLE_VALUE;
511 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
513 ret = CreateFileW(filenameW.Buffer, access, sharing, sa, creation,
514 attributes, template);
515 RtlFreeUnicodeString(&filenameW);
517 else
518 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
519 return ret;
523 /***********************************************************************
524 * FILE_FillInfo
526 * Fill a file information from a struct stat.
528 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
530 if (S_ISDIR(st->st_mode))
531 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
532 else
533 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
534 if (!(st->st_mode & S_IWUSR))
535 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
537 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftCreationTime );
538 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftLastWriteTime );
539 RtlSecondsSince1970ToTime( st->st_atime, (LARGE_INTEGER *)&info->ftLastAccessTime );
541 info->dwVolumeSerialNumber = 0; /* FIXME */
542 if (S_ISDIR(st->st_mode))
544 info->nFileSizeHigh = 0;
545 info->nFileSizeLow = 0;
546 info->nNumberOfLinks = 1;
548 else
550 info->nFileSizeHigh = st->st_size >> 32;
551 info->nFileSizeLow = (DWORD)st->st_size;
552 info->nNumberOfLinks = st->st_nlink;
554 info->nFileIndexHigh = st->st_ino >> 32;
555 info->nFileIndexLow = (DWORD)st->st_ino;
559 /***********************************************************************
560 * get_show_dot_files_option
562 static BOOL get_show_dot_files_option(void)
564 static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
565 'S','o','f','t','w','a','r','e','\\',
566 'W','i','n','e','\\','W','i','n','e','\\',
567 'C','o','n','f','i','g','\\','W','i','n','e',0};
568 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
570 char tmp[80];
571 HKEY hkey;
572 DWORD dummy;
573 OBJECT_ATTRIBUTES attr;
574 UNICODE_STRING nameW;
575 BOOL ret = FALSE;
577 attr.Length = sizeof(attr);
578 attr.RootDirectory = 0;
579 attr.ObjectName = &nameW;
580 attr.Attributes = 0;
581 attr.SecurityDescriptor = NULL;
582 attr.SecurityQualityOfService = NULL;
583 RtlInitUnicodeString( &nameW, WineW );
585 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
587 RtlInitUnicodeString( &nameW, ShowDotFilesW );
588 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
590 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
591 ret = IS_OPTION_TRUE( str[0] );
593 NtClose( hkey );
595 return ret;
599 /***********************************************************************
600 * FILE_Stat
602 * Stat a Unix path name. Return TRUE if OK.
604 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info, BOOL *is_symlink_ptr )
606 struct stat st;
607 int is_symlink;
608 LPCSTR p;
610 if (lstat( unixName, &st ) == -1)
612 FILE_SetDosError();
613 return FALSE;
615 is_symlink = S_ISLNK(st.st_mode);
616 if (is_symlink)
618 /* do a "real" stat to find out
619 about the type of the symlink destination */
620 if (stat( unixName, &st ) == -1)
622 FILE_SetDosError();
623 return FALSE;
627 /* fill in the information we gathered so far */
628 FILE_FillInfo( &st, info );
630 /* and now see if this is a hidden file, based on the name */
631 p = strrchr( unixName, '/');
632 p = p ? p + 1 : unixName;
633 if (*p == '.' && *(p+1) && (*(p+1) != '.' || *(p+2)))
635 static int show_dot_files = -1;
636 if (show_dot_files == -1)
637 show_dot_files = get_show_dot_files_option();
638 if (!show_dot_files)
639 info->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
641 if (is_symlink_ptr) *is_symlink_ptr = is_symlink;
642 return TRUE;
646 /***********************************************************************
647 * GetFileInformationByHandle (KERNEL32.@)
649 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
651 NTSTATUS status;
652 int fd;
653 BOOL ret = FALSE;
655 TRACE("%p,%p\n", hFile, info);
657 if (!info) return 0;
659 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
661 struct stat st;
663 if (fstat( fd, &st ) == -1)
664 FILE_SetDosError();
665 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
666 SetLastError( ERROR_INVALID_FUNCTION );
667 else
669 FILE_FillInfo( &st, info );
670 ret = TRUE;
672 wine_server_release_fd( hFile, fd );
674 else SetLastError( RtlNtStatusToDosError(status) );
676 return ret;
680 /***********************************************************************
681 * GetFileTime (KERNEL32.@)
683 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
684 FILETIME *lpLastAccessTime,
685 FILETIME *lpLastWriteTime )
687 BY_HANDLE_FILE_INFORMATION info;
688 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
689 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
690 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
691 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
692 return TRUE;
696 /***********************************************************************
697 * GetTempFileNameA (KERNEL32.@)
699 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
700 LPSTR buffer)
702 UNICODE_STRING pathW, prefixW;
703 WCHAR bufferW[MAX_PATH];
704 UINT ret;
706 if ( !path || !prefix || !buffer )
708 SetLastError( ERROR_INVALID_PARAMETER );
709 return 0;
712 RtlCreateUnicodeStringFromAsciiz(&pathW, path);
713 RtlCreateUnicodeStringFromAsciiz(&prefixW, prefix);
715 ret = GetTempFileNameW(pathW.Buffer, prefixW.Buffer, unique, bufferW);
716 if (ret)
717 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, MAX_PATH, NULL, NULL);
719 RtlFreeUnicodeString(&pathW);
720 RtlFreeUnicodeString(&prefixW);
721 return ret;
724 /***********************************************************************
725 * GetTempFileNameW (KERNEL32.@)
727 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
728 LPWSTR buffer )
730 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
732 DOS_FULL_NAME full_name;
733 int i;
734 LPWSTR p;
736 if ( !path || !prefix || !buffer )
738 SetLastError( ERROR_INVALID_PARAMETER );
739 return 0;
742 strcpyW( buffer, path );
743 p = buffer + strlenW(buffer);
745 /* add a \, if there isn't one */
746 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
748 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
750 unique &= 0xffff;
752 if (unique) sprintfW( p, formatW, unique );
753 else
755 /* get a "random" unique number and try to create the file */
756 HANDLE handle;
757 UINT num = GetTickCount() & 0xffff;
759 if (!num) num = 1;
760 unique = num;
763 sprintfW( p, formatW, unique );
764 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
765 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
766 if (handle != INVALID_HANDLE_VALUE)
767 { /* We created it */
768 TRACE("created %s\n", debugstr_w(buffer) );
769 CloseHandle( handle );
770 break;
772 if (GetLastError() != ERROR_FILE_EXISTS &&
773 GetLastError() != ERROR_SHARING_VIOLATION)
774 break; /* No need to go on */
775 if (!(++unique & 0xffff)) unique = 1;
776 } while (unique != num);
779 /* Get the full path name */
781 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
783 char *slash;
784 /* Check if we have write access in the directory */
785 if ((slash = strrchr( full_name.long_name, '/' ))) *slash = '\0';
786 if (access( full_name.long_name, W_OK ) == -1)
787 WARN("returns %s, which doesn't seem to be writeable.\n",
788 debugstr_w(buffer) );
790 TRACE("returning %s\n", debugstr_w(buffer) );
791 return unique;
795 /******************************************************************
796 * FILE_ReadWriteApc (internal)
800 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
802 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
804 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
807 /***********************************************************************
808 * ReadFileEx (KERNEL32.@)
810 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
811 LPOVERLAPPED overlapped,
812 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
814 LARGE_INTEGER offset;
815 NTSTATUS status;
816 PIO_STATUS_BLOCK io_status;
818 if (!overlapped)
820 SetLastError(ERROR_INVALID_PARAMETER);
821 return FALSE;
824 offset.u.LowPart = overlapped->Offset;
825 offset.u.HighPart = overlapped->OffsetHigh;
826 io_status = (PIO_STATUS_BLOCK)overlapped;
827 io_status->u.Status = STATUS_PENDING;
829 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
830 io_status, buffer, bytesToRead, &offset, NULL);
832 if (status)
834 SetLastError( RtlNtStatusToDosError(status) );
835 return FALSE;
837 return TRUE;
840 /***********************************************************************
841 * ReadFile (KERNEL32.@)
843 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
844 LPDWORD bytesRead, LPOVERLAPPED overlapped )
846 LARGE_INTEGER offset;
847 PLARGE_INTEGER poffset = NULL;
848 IO_STATUS_BLOCK iosb;
849 PIO_STATUS_BLOCK io_status = &iosb;
850 HANDLE hEvent = 0;
851 NTSTATUS status;
853 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
854 bytesRead, overlapped );
856 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
857 if (!bytesToRead) return TRUE;
859 if (IsBadReadPtr(buffer, bytesToRead))
861 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
862 return FALSE;
864 if (is_console_handle(hFile))
865 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
867 if (overlapped != NULL)
869 offset.u.LowPart = overlapped->Offset;
870 offset.u.HighPart = overlapped->OffsetHigh;
871 poffset = &offset;
872 hEvent = overlapped->hEvent;
873 io_status = (PIO_STATUS_BLOCK)overlapped;
875 io_status->u.Status = STATUS_PENDING;
876 io_status->Information = 0;
878 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
880 if (status != STATUS_PENDING && bytesRead)
881 *bytesRead = io_status->Information;
883 if (status && status != STATUS_END_OF_FILE)
885 SetLastError( RtlNtStatusToDosError(status) );
886 return FALSE;
888 return TRUE;
892 /***********************************************************************
893 * WriteFileEx (KERNEL32.@)
895 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
896 LPOVERLAPPED overlapped,
897 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
899 LARGE_INTEGER offset;
900 NTSTATUS status;
901 PIO_STATUS_BLOCK io_status;
903 TRACE("%p %p %ld %p %p\n",
904 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
906 if (overlapped == NULL)
908 SetLastError(ERROR_INVALID_PARAMETER);
909 return FALSE;
911 offset.u.LowPart = overlapped->Offset;
912 offset.u.HighPart = overlapped->OffsetHigh;
914 io_status = (PIO_STATUS_BLOCK)overlapped;
915 io_status->u.Status = STATUS_PENDING;
917 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
918 io_status, buffer, bytesToWrite, &offset, NULL);
920 if (status) SetLastError( RtlNtStatusToDosError(status) );
921 return !status;
924 /***********************************************************************
925 * WriteFile (KERNEL32.@)
927 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
928 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
930 HANDLE hEvent = NULL;
931 LARGE_INTEGER offset;
932 PLARGE_INTEGER poffset = NULL;
933 NTSTATUS status;
934 IO_STATUS_BLOCK iosb;
935 PIO_STATUS_BLOCK piosb = &iosb;
937 TRACE("%p %p %ld %p %p\n",
938 hFile, buffer, bytesToWrite, bytesWritten, overlapped );
940 if (is_console_handle(hFile))
941 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
943 if (IsBadReadPtr(buffer, bytesToWrite))
945 SetLastError(ERROR_READ_FAULT); /* FIXME */
946 return FALSE;
949 if (overlapped)
951 offset.u.LowPart = overlapped->Offset;
952 offset.u.HighPart = overlapped->OffsetHigh;
953 poffset = &offset;
954 hEvent = overlapped->hEvent;
955 piosb = (PIO_STATUS_BLOCK)overlapped;
957 piosb->u.Status = STATUS_PENDING;
958 piosb->Information = 0;
960 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
961 buffer, bytesToWrite, poffset, NULL);
962 if (status)
964 SetLastError( RtlNtStatusToDosError(status) );
965 return FALSE;
967 if (bytesWritten) *bytesWritten = piosb->Information;
969 return TRUE;
973 /***********************************************************************
974 * SetFilePointer (KERNEL32.@)
976 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
977 DWORD method )
979 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
980 DWORD ret = INVALID_SET_FILE_POINTER;
981 NTSTATUS status;
982 int fd;
984 TRACE("handle %p offset %ld high %ld origin %ld\n",
985 hFile, distance, highword?*highword:0, method );
987 if (method > FILE_END)
989 SetLastError( ERROR_INVALID_PARAMETER );
990 return ret;
993 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
995 off_t pos, res;
997 if (highword) pos = ((off_t)*highword << 32) | (ULONG)distance;
998 else pos = (off_t)distance;
999 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
1001 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
1002 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
1003 SetLastError( ERROR_NEGATIVE_SEEK );
1004 else
1005 FILE_SetDosError();
1007 else
1009 ret = (DWORD)res;
1010 if (highword) *highword = (res >> 32);
1011 if (ret == INVALID_SET_FILE_POINTER) SetLastError( 0 );
1013 wine_server_release_fd( hFile, fd );
1015 else SetLastError( RtlNtStatusToDosError(status) );
1017 return ret;
1021 /*************************************************************************
1022 * SetHandleCount (KERNEL32.@)
1024 UINT WINAPI SetHandleCount( UINT count )
1026 return min( 256, count );
1030 /**************************************************************************
1031 * SetEndOfFile (KERNEL32.@)
1033 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1035 BOOL ret;
1036 SERVER_START_REQ( truncate_file )
1038 req->handle = hFile;
1039 ret = !wine_server_call_err( req );
1041 SERVER_END_REQ;
1042 return ret;
1046 /***********************************************************************
1047 * GetFileType (KERNEL32.@)
1049 DWORD WINAPI GetFileType( HANDLE hFile )
1051 NTSTATUS status;
1052 int fd;
1053 DWORD ret = FILE_TYPE_UNKNOWN;
1055 if (is_console_handle( hFile ))
1056 return FILE_TYPE_CHAR;
1058 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
1060 struct stat st;
1062 if (fstat( fd, &st ) == -1)
1063 FILE_SetDosError();
1064 else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
1065 ret = FILE_TYPE_PIPE;
1066 else if (S_ISCHR(st.st_mode))
1067 ret = FILE_TYPE_CHAR;
1068 else
1069 ret = FILE_TYPE_DISK;
1070 wine_server_release_fd( hFile, fd );
1072 else SetLastError( RtlNtStatusToDosError(status) );
1074 return ret;
1078 /**************************************************************************
1079 * CopyFileW (KERNEL32.@)
1081 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
1083 HANDLE h1, h2;
1084 BY_HANDLE_FILE_INFORMATION info;
1085 DWORD count;
1086 BOOL ret = FALSE;
1087 char buffer[2048];
1089 if (!source || !dest)
1091 SetLastError(ERROR_INVALID_PARAMETER);
1092 return FALSE;
1095 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
1097 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
1098 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
1100 WARN("Unable to open source %s\n", debugstr_w(source));
1101 return FALSE;
1104 if (!GetFileInformationByHandle( h1, &info ))
1106 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
1107 CloseHandle( h1 );
1108 return FALSE;
1111 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1112 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
1113 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1115 WARN("Unable to open dest %s\n", debugstr_w(dest));
1116 CloseHandle( h1 );
1117 return FALSE;
1120 while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
1122 char *p = buffer;
1123 while (count != 0)
1125 DWORD res;
1126 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1127 p += res;
1128 count -= res;
1131 ret = TRUE;
1132 done:
1133 CloseHandle( h1 );
1134 CloseHandle( h2 );
1135 return ret;
1139 /**************************************************************************
1140 * CopyFileA (KERNEL32.@)
1142 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1144 UNICODE_STRING sourceW, destW;
1145 BOOL ret;
1147 if (!source || !dest)
1149 SetLastError(ERROR_INVALID_PARAMETER);
1150 return FALSE;
1153 RtlCreateUnicodeStringFromAsciiz(&sourceW, source);
1154 RtlCreateUnicodeStringFromAsciiz(&destW, dest);
1156 ret = CopyFileW(sourceW.Buffer, destW.Buffer, fail_if_exists);
1158 RtlFreeUnicodeString(&sourceW);
1159 RtlFreeUnicodeString(&destW);
1160 return ret;
1164 /**************************************************************************
1165 * CopyFileExW (KERNEL32.@)
1167 * This implementation ignores most of the extra parameters passed-in into
1168 * the "ex" version of the method and calls the CopyFile method.
1169 * It will have to be fixed eventually.
1171 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
1172 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1173 LPBOOL cancelFlagPointer, DWORD copyFlags)
1176 * Interpret the only flag that CopyFile can interpret.
1178 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
1182 /**************************************************************************
1183 * CopyFileExA (KERNEL32.@)
1185 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1186 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1187 LPBOOL cancelFlagPointer, DWORD copyFlags)
1189 UNICODE_STRING sourceW, destW;
1190 BOOL ret;
1192 if (!sourceFilename || !destFilename)
1194 SetLastError(ERROR_INVALID_PARAMETER);
1195 return FALSE;
1198 RtlCreateUnicodeStringFromAsciiz(&sourceW, sourceFilename);
1199 RtlCreateUnicodeStringFromAsciiz(&destW, destFilename);
1201 ret = CopyFileExW(sourceW.Buffer, destW.Buffer, progressRoutine, appData,
1202 cancelFlagPointer, copyFlags);
1204 RtlFreeUnicodeString(&sourceW);
1205 RtlFreeUnicodeString(&destW);
1206 return ret;