shell32: Update for simplified Chinese translation.
[wine] / dlls / kernel32 / path.c
1 /*
2  * File handling functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 1996, 2004 Alexandre Julliard
6  * Copyright 2003 Eric Pouech
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  *
22  */
23
24 #include "config.h"
25 #include "wine/port.h"
26
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdarg.h>
30
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
33 #include "winerror.h"
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winbase.h"
38 #include "winternl.h"
39
40 #include "kernel_private.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(file);
45
46 #define MAX_PATHNAME_LEN        1024
47
48
49 /* check if a file name is for an executable file (.exe or .com) */
50 static inline BOOL is_executable( const WCHAR *name )
51 {
52     static const WCHAR exeW[] = {'.','e','x','e',0};
53     static const WCHAR comW[] = {'.','c','o','m',0};
54     int len = strlenW(name);
55
56     if (len < 4) return FALSE;
57     return (!strcmpiW( name + len - 4, exeW ) || !strcmpiW( name + len - 4, comW ));
58 }
59
60 /***********************************************************************
61  *           copy_filename_WtoA
62  *
63  * copy a file name back to OEM/Ansi, but only if the buffer is large enough
64  */
65 static DWORD copy_filename_WtoA( LPCWSTR nameW, LPSTR buffer, DWORD len )
66 {
67     UNICODE_STRING strW;
68     DWORD ret;
69     BOOL is_ansi = AreFileApisANSI();
70
71     RtlInitUnicodeString( &strW, nameW );
72
73     ret = is_ansi ? RtlUnicodeStringToAnsiSize(&strW) : RtlUnicodeStringToOemSize(&strW);
74     if (buffer && ret <= len)
75     {
76         ANSI_STRING str;
77
78         str.Buffer = buffer;
79         str.MaximumLength = min( len, UNICODE_STRING_MAX_CHARS );
80         if (is_ansi)
81             RtlUnicodeStringToAnsiString( &str, &strW, FALSE );
82         else
83             RtlUnicodeStringToOemString( &str, &strW, FALSE );
84         ret = str.Length;  /* length without terminating 0 */
85     }
86     return ret;
87 }
88
89 /***********************************************************************
90  *           add_boot_rename_entry
91  *
92  * Adds an entry to the registry that is loaded when windows boots and
93  * checks if there are some files to be removed or renamed/moved.
94  * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
95  * non-NULL then the file is moved, otherwise it is deleted.  The
96  * entry of the registrykey is always appended with two zero
97  * terminated strings. If <fn2> is NULL then the second entry is
98  * simply a single 0-byte. Otherwise the second filename goes
99  * there. The entries are prepended with \??\ before the path and the
100  * second filename gets also a '!' as the first character if
101  * MOVEFILE_REPLACE_EXISTING is set. After the final string another
102  * 0-byte follows to indicate the end of the strings.
103  * i.e.:
104  * \??\D:\test\file1[0]
105  * !\??\D:\test\file1_renamed[0]
106  * \??\D:\Test|delete[0]
107  * [0]                        <- file is to be deleted, second string empty
108  * \??\D:\test\file2[0]
109  * !\??\D:\test\file2_renamed[0]
110  * [0]                        <- indicates end of strings
111  *
112  * or:
113  * \??\D:\test\file1[0]
114  * !\??\D:\test\file1_renamed[0]
115  * \??\D:\Test|delete[0]
116  * [0]                        <- file is to be deleted, second string empty
117  * [0]                        <- indicates end of strings
118  *
119  */
120 static BOOL add_boot_rename_entry( LPCWSTR source, LPCWSTR dest, DWORD flags )
121 {
122     static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
123                                       'F','i','l','e','R','e','n','a','m','e',
124                                       'O','p','e','r','a','t','i','o','n','s',0};
125     static const WCHAR SessionW[] = {'M','a','c','h','i','n','e','\\',
126                                      'S','y','s','t','e','m','\\',
127                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
128                                      'C','o','n','t','r','o','l','\\',
129                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
130     static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
131
132     OBJECT_ATTRIBUTES attr;
133     UNICODE_STRING nameW, source_name, dest_name;
134     KEY_VALUE_PARTIAL_INFORMATION *info;
135     BOOL rc = FALSE;
136     HANDLE Reboot = 0;
137     DWORD len1, len2;
138     DWORD DataSize = 0;
139     BYTE *Buffer = NULL;
140     WCHAR *p;
141
142     if (!RtlDosPathNameToNtPathName_U( source, &source_name, NULL, NULL ))
143     {
144         SetLastError( ERROR_PATH_NOT_FOUND );
145         return FALSE;
146     }
147     dest_name.Buffer = NULL;
148     if (dest && !RtlDosPathNameToNtPathName_U( dest, &dest_name, NULL, NULL ))
149     {
150         RtlFreeUnicodeString( &source_name );
151         SetLastError( ERROR_PATH_NOT_FOUND );
152         return FALSE;
153     }
154
155     attr.Length = sizeof(attr);
156     attr.RootDirectory = 0;
157     attr.ObjectName = &nameW;
158     attr.Attributes = 0;
159     attr.SecurityDescriptor = NULL;
160     attr.SecurityQualityOfService = NULL;
161     RtlInitUnicodeString( &nameW, SessionW );
162
163     if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
164     {
165         WARN("Error creating key for reboot managment [%s]\n",
166              "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
167         RtlFreeUnicodeString( &source_name );
168         RtlFreeUnicodeString( &dest_name );
169         return FALSE;
170     }
171
172     len1 = source_name.Length + sizeof(WCHAR);
173     if (dest)
174     {
175         len2 = dest_name.Length + sizeof(WCHAR);
176         if (flags & MOVEFILE_REPLACE_EXISTING)
177             len2 += sizeof(WCHAR); /* Plus 1 because of the leading '!' */
178     }
179     else len2 = sizeof(WCHAR); /* minimum is the 0 characters for the empty second string */
180
181     RtlInitUnicodeString( &nameW, ValueName );
182
183     /* First we check if the key exists and if so how many bytes it already contains. */
184     if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
185                          NULL, 0, &DataSize ) == STATUS_BUFFER_TOO_SMALL)
186     {
187         if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
188             goto Quit;
189         if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
190                              Buffer, DataSize, &DataSize )) goto Quit;
191         info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
192         if (info->Type != REG_MULTI_SZ) goto Quit;
193         if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR);  /* remove terminating null (will be added back later) */
194     }
195     else
196     {
197         DataSize = info_size;
198         if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
199             goto Quit;
200     }
201
202     memcpy( Buffer + DataSize, source_name.Buffer, len1 );
203     DataSize += len1;
204     p = (WCHAR *)(Buffer + DataSize);
205     if (dest)
206     {
207         if (flags & MOVEFILE_REPLACE_EXISTING)
208             *p++ = '!';
209         memcpy( p, dest_name.Buffer, len2 );
210         DataSize += len2;
211     }
212     else
213     {
214         *p = 0;
215         DataSize += sizeof(WCHAR);
216     }
217
218     /* add final null */
219     p = (WCHAR *)(Buffer + DataSize);
220     *p = 0;
221     DataSize += sizeof(WCHAR);
222
223     rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
224
225  Quit:
226     RtlFreeUnicodeString( &source_name );
227     RtlFreeUnicodeString( &dest_name );
228     if (Reboot) NtClose(Reboot);
229     HeapFree( GetProcessHeap(), 0, Buffer );
230     return(rc);
231 }
232
233
234 /***********************************************************************
235  *           GetFullPathNameW   (KERNEL32.@)
236  * NOTES
237  *   if the path closed with '\', *lastpart is 0
238  */
239 DWORD WINAPI GetFullPathNameW( LPCWSTR name, DWORD len, LPWSTR buffer,
240                                LPWSTR *lastpart )
241 {
242     return RtlGetFullPathName_U(name, len * sizeof(WCHAR), buffer, lastpart) / sizeof(WCHAR);
243 }
244
245 /***********************************************************************
246  *           GetFullPathNameA   (KERNEL32.@)
247  * NOTES
248  *   if the path closed with '\', *lastpart is 0
249  */
250 DWORD WINAPI GetFullPathNameA( LPCSTR name, DWORD len, LPSTR buffer,
251                                LPSTR *lastpart )
252 {
253     WCHAR *nameW;
254     WCHAR bufferW[MAX_PATH];
255     DWORD ret;
256
257     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
258
259     ret = GetFullPathNameW( nameW, MAX_PATH, bufferW, NULL);
260
261     if (!ret) return 0;
262     if (ret > MAX_PATH)
263     {
264         SetLastError(ERROR_FILENAME_EXCED_RANGE);
265         return 0;
266     }
267     ret = copy_filename_WtoA( bufferW, buffer, len );
268     if (ret < len && lastpart)
269     {
270         LPSTR p = buffer + strlen(buffer) - 1;
271
272         if (*p != '\\')
273         {
274             while ((p > buffer + 2) && (*p != '\\')) p--;
275             *lastpart = p + 1;
276         }
277         else *lastpart = NULL;
278     }
279     return ret;
280 }
281
282
283 /***********************************************************************
284  *           GetLongPathNameW   (KERNEL32.@)
285  *
286  * NOTES
287  *  observed (Win2000):
288  *  shortpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
289  *  shortpath="":   LastError=ERROR_PATH_NOT_FOUND, ret=0
290  */
291 DWORD WINAPI GetLongPathNameW( LPCWSTR shortpath, LPWSTR longpath, DWORD longlen )
292 {
293     WCHAR               tmplongpath[MAX_PATHNAME_LEN];
294     LPCWSTR             p;
295     DWORD               sp = 0, lp = 0;
296     DWORD               tmplen;
297     BOOL                unixabsolute;
298     WIN32_FIND_DATAW    wfd;
299     HANDLE              goit;
300
301     if (!shortpath)
302     {
303         SetLastError(ERROR_INVALID_PARAMETER);
304         return 0;
305     }
306     if (!shortpath[0])
307     {
308         SetLastError(ERROR_PATH_NOT_FOUND);
309         return 0;
310     }
311
312     TRACE("%s,%p,%d\n", debugstr_w(shortpath), longpath, longlen);
313
314     if (shortpath[0] == '\\' && shortpath[1] == '\\')
315     {
316         FIXME("UNC pathname %s\n", debugstr_w(shortpath));
317
318         tmplen = strlenW(shortpath);
319         if (tmplen < longlen)
320         {
321             if (longpath != shortpath) strcpyW( longpath, shortpath );
322             return tmplen;
323         }
324         return tmplen + 1;
325     }
326
327     unixabsolute = (shortpath[0] == '/');
328
329     /* check for drive letter */
330     if (!unixabsolute && shortpath[1] == ':' )
331     {
332         tmplongpath[0] = shortpath[0];
333         tmplongpath[1] = ':';
334         lp = sp = 2;
335     }
336
337     while (shortpath[sp])
338     {
339         /* check for path delimiters and reproduce them */
340         if (shortpath[sp] == '\\' || shortpath[sp] == '/')
341         {
342             if (!lp || tmplongpath[lp-1] != '\\')
343             {
344                 /* strip double "\\" */
345                 tmplongpath[lp++] = '\\';
346             }
347             tmplongpath[lp] = 0; /* terminate string */
348             sp++;
349             continue;
350         }
351
352         p = shortpath + sp;
353         if (sp == 0 && p[0] == '.' && (p[1] == '/' || p[1] == '\\'))
354         {
355             tmplongpath[lp++] = *p++;
356             tmplongpath[lp++] = *p++;
357         }
358         for (; *p && *p != '/' && *p != '\\'; p++);
359         tmplen = p - (shortpath + sp);
360         lstrcpynW(tmplongpath + lp, shortpath + sp, tmplen + 1);
361         /* Check if the file exists and use the existing file name */
362         goit = FindFirstFileW(tmplongpath, &wfd);
363         if (goit == INVALID_HANDLE_VALUE)
364         {
365             TRACE("not found %s!\n", debugstr_w(tmplongpath));
366             SetLastError ( ERROR_FILE_NOT_FOUND );
367             return 0;
368         }
369         FindClose(goit);
370         strcpyW(tmplongpath + lp, wfd.cFileName);
371         lp += strlenW(tmplongpath + lp);
372         sp += tmplen;
373     }
374     tmplen = strlenW(shortpath) - 1;
375     if ((shortpath[tmplen] == '/' || shortpath[tmplen] == '\\') &&
376         (tmplongpath[lp - 1] != '/' && tmplongpath[lp - 1] != '\\'))
377         tmplongpath[lp++] = shortpath[tmplen];
378     tmplongpath[lp] = 0;
379
380     tmplen = strlenW(tmplongpath) + 1;
381     if (tmplen <= longlen)
382     {
383         strcpyW(longpath, tmplongpath);
384         TRACE("returning %s\n", debugstr_w(longpath));
385         tmplen--; /* length without 0 */
386     }
387
388     return tmplen;
389 }
390
391 /***********************************************************************
392  *           GetLongPathNameA   (KERNEL32.@)
393  */
394 DWORD WINAPI GetLongPathNameA( LPCSTR shortpath, LPSTR longpath, DWORD longlen )
395 {
396     WCHAR *shortpathW;
397     WCHAR longpathW[MAX_PATH];
398     DWORD ret;
399
400     TRACE("%s\n", debugstr_a(shortpath));
401
402     if (!(shortpathW = FILE_name_AtoW( shortpath, FALSE ))) return 0;
403
404     ret = GetLongPathNameW(shortpathW, longpathW, MAX_PATH);
405
406     if (!ret) return 0;
407     if (ret > MAX_PATH)
408     {
409         SetLastError(ERROR_FILENAME_EXCED_RANGE);
410         return 0;
411     }
412     return copy_filename_WtoA( longpathW, longpath, longlen );
413 }
414
415
416 /***********************************************************************
417  *           GetShortPathNameW   (KERNEL32.@)
418  *
419  * NOTES
420  *  observed:
421  *  longpath=NULL: LastError=ERROR_INVALID_PARAMETER, ret=0
422  *  longpath="" or invalid: LastError=ERROR_BAD_PATHNAME, ret=0
423  *
424  * more observations ( with NT 3.51 (WinDD) ):
425  * longpath <= 8.3 -> just copy longpath to shortpath
426  * longpath > 8.3  ->
427  *             a) file does not exist -> return 0, LastError = ERROR_FILE_NOT_FOUND
428  *             b) file does exist     -> set the short filename.
429  * - trailing slashes are reproduced in the short name, even if the
430  *   file is not a directory
431  * - the absolute/relative path of the short name is reproduced like found
432  *   in the long name
433  * - longpath and shortpath may have the same address
434  * Peter Ganten, 1999
435  */
436 DWORD WINAPI GetShortPathNameW( LPCWSTR longpath, LPWSTR shortpath, DWORD shortlen )
437 {
438     WCHAR               tmpshortpath[MAX_PATHNAME_LEN];
439     LPCWSTR             p;
440     DWORD               sp = 0, lp = 0;
441     DWORD               tmplen;
442     WIN32_FIND_DATAW    wfd;
443     HANDLE              goit;
444     UNICODE_STRING      ustr;
445     WCHAR               ustr_buf[8+1+3+1];
446
447     TRACE("%s\n", debugstr_w(longpath));
448
449     if (!longpath)
450     {
451         SetLastError(ERROR_INVALID_PARAMETER);
452         return 0;
453     }
454     if (!longpath[0])
455     {
456         SetLastError(ERROR_BAD_PATHNAME);
457         return 0;
458     }
459
460     /* check for drive letter */
461     if (longpath[0] != '/' && longpath[1] == ':' )
462     {
463         tmpshortpath[0] = longpath[0];
464         tmpshortpath[1] = ':';
465         sp = lp = 2;
466     }
467
468     ustr.Buffer = ustr_buf;
469     ustr.Length = 0;
470     ustr.MaximumLength = sizeof(ustr_buf);
471
472     while (longpath[lp])
473     {
474         /* check for path delimiters and reproduce them */
475         if (longpath[lp] == '\\' || longpath[lp] == '/')
476         {
477             if (!sp || tmpshortpath[sp-1] != '\\')
478             {
479                 /* strip double "\\" */
480                 tmpshortpath[sp] = '\\';
481                 sp++;
482             }
483             tmpshortpath[sp] = 0; /* terminate string */
484             lp++;
485             continue;
486         }
487
488         for (p = longpath + lp; *p && *p != '/' && *p != '\\'; p++);
489         tmplen = p - (longpath + lp);
490         lstrcpynW(tmpshortpath + sp, longpath + lp, tmplen + 1);
491         /* Check, if the current element is a valid dos name */
492         if (tmplen <= 8+1+3)
493         {
494             BOOLEAN spaces;
495             memcpy(ustr_buf, longpath + lp, tmplen * sizeof(WCHAR));
496             ustr_buf[tmplen] = '\0';
497             ustr.Length = tmplen * sizeof(WCHAR);
498             if (RtlIsNameLegalDOS8Dot3(&ustr, NULL, &spaces) && !spaces)
499             {
500                 sp += tmplen;
501                 lp += tmplen;
502                 continue;
503             }
504         }
505
506         /* Check if the file exists and use the existing short file name */
507         goit = FindFirstFileW(tmpshortpath, &wfd);
508         if (goit == INVALID_HANDLE_VALUE) goto notfound;
509         FindClose(goit);
510         strcpyW(tmpshortpath + sp, wfd.cAlternateFileName);
511         sp += strlenW(tmpshortpath + sp);
512         lp += tmplen;
513     }
514     tmpshortpath[sp] = 0;
515
516     tmplen = strlenW(tmpshortpath) + 1;
517     if (tmplen <= shortlen)
518     {
519         strcpyW(shortpath, tmpshortpath);
520         TRACE("returning %s\n", debugstr_w(shortpath));
521         tmplen--; /* length without 0 */
522     }
523
524     return tmplen;
525
526  notfound:
527     TRACE("not found!\n" );
528     SetLastError ( ERROR_FILE_NOT_FOUND );
529     return 0;
530 }
531
532 /***********************************************************************
533  *           GetShortPathNameA   (KERNEL32.@)
534  */
535 DWORD WINAPI GetShortPathNameA( LPCSTR longpath, LPSTR shortpath, DWORD shortlen )
536 {
537     WCHAR *longpathW;
538     WCHAR shortpathW[MAX_PATH];
539     DWORD ret;
540
541     TRACE("%s\n", debugstr_a(longpath));
542
543     if (!(longpathW = FILE_name_AtoW( longpath, FALSE ))) return 0;
544
545     ret = GetShortPathNameW(longpathW, shortpathW, MAX_PATH);
546
547     if (!ret) return 0;
548     if (ret > MAX_PATH)
549     {
550         SetLastError(ERROR_FILENAME_EXCED_RANGE);
551         return 0;
552     }
553     return copy_filename_WtoA( shortpathW, shortpath, shortlen );
554 }
555
556
557 /***********************************************************************
558  *           GetTempPathA   (KERNEL32.@)
559  */
560 DWORD WINAPI GetTempPathA( DWORD count, LPSTR path )
561 {
562     WCHAR pathW[MAX_PATH];
563     UINT ret;
564
565     ret = GetTempPathW(MAX_PATH, pathW);
566
567     if (!ret)
568         return 0;
569
570     if (ret > MAX_PATH)
571     {
572         SetLastError(ERROR_FILENAME_EXCED_RANGE);
573         return 0;
574     }
575     return copy_filename_WtoA( pathW, path, count );
576 }
577
578
579 /***********************************************************************
580  *           GetTempPathW   (KERNEL32.@)
581  */
582 DWORD WINAPI GetTempPathW( DWORD count, LPWSTR path )
583 {
584     static const WCHAR tmp[]  = { 'T', 'M', 'P', 0 };
585     static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
586     static const WCHAR userprofile[] = { 'U','S','E','R','P','R','O','F','I','L','E',0 };
587     WCHAR tmp_path[MAX_PATH];
588     UINT ret;
589
590     TRACE("%u,%p\n", count, path);
591
592     if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )) &&
593         !(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )) &&
594         !(ret = GetEnvironmentVariableW( userprofile, tmp_path, MAX_PATH )) &&
595         !(ret = GetWindowsDirectoryW( tmp_path, MAX_PATH )))
596         return 0;
597
598     if (ret > MAX_PATH)
599     {
600         SetLastError(ERROR_FILENAME_EXCED_RANGE);
601         return 0;
602     }
603
604     ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
605     if (!ret) return 0;
606
607     if (ret > MAX_PATH - 2)
608     {
609         SetLastError(ERROR_FILENAME_EXCED_RANGE);
610         return 0;
611     }
612
613     if (tmp_path[ret-1] != '\\')
614     {
615         tmp_path[ret++] = '\\';
616         tmp_path[ret]   = '\0';
617     }
618
619     ret++; /* add space for terminating 0 */
620
621     if (count)
622     {
623         lstrcpynW(path, tmp_path, count);
624         if (count >= ret)
625             ret--; /* return length without 0 */
626         else if (count < 4)
627             path[0] = 0; /* avoid returning ambiguous "X:" */
628     }
629
630     TRACE("returning %u, %s\n", ret, debugstr_w(path));
631     return ret;
632 }
633
634
635 /***********************************************************************
636  *           GetTempFileNameA   (KERNEL32.@)
637  */
638 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique, LPSTR buffer)
639 {
640     WCHAR *pathW, *prefixW = NULL;
641     WCHAR bufferW[MAX_PATH];
642     UINT ret;
643
644     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return 0;
645     if (prefix && !(prefixW = FILE_name_AtoW( prefix, TRUE ))) return 0;
646
647     ret = GetTempFileNameW(pathW, prefixW, unique, bufferW);
648     if (ret) FILE_name_WtoA( bufferW, -1, buffer, MAX_PATH );
649
650     HeapFree( GetProcessHeap(), 0, prefixW );
651     return ret;
652 }
653
654 /***********************************************************************
655  *           GetTempFileNameW   (KERNEL32.@)
656  */
657 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique, LPWSTR buffer )
658 {
659     static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
660
661     int i;
662     LPWSTR p;
663
664     if ( !path || !buffer )
665     {
666         SetLastError( ERROR_INVALID_PARAMETER );
667         return 0;
668     }
669
670     strcpyW( buffer, path );
671     p = buffer + strlenW(buffer);
672
673     /* add a \, if there isn't one  */
674     if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
675
676     if (prefix)
677         for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
678
679     unique &= 0xffff;
680
681     if (unique) sprintfW( p, formatW, unique );
682     else
683     {
684         /* get a "random" unique number and try to create the file */
685         HANDLE handle;
686         UINT num = GetTickCount() & 0xffff;
687         static UINT last;
688
689         /* avoid using the same name twice in a short interval */
690         if (last - num < 10) num = last + 1;
691         if (!num) num = 1;
692         unique = num;
693         do
694         {
695             sprintfW( p, formatW, unique );
696             handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
697                                   CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
698             if (handle != INVALID_HANDLE_VALUE)
699             {  /* We created it */
700                 TRACE("created %s\n", debugstr_w(buffer) );
701                 CloseHandle( handle );
702                 last = unique;
703                 break;
704             }
705             if (GetLastError() != ERROR_FILE_EXISTS &&
706                 GetLastError() != ERROR_SHARING_VIOLATION)
707                 break;  /* No need to go on */
708             if (!(++unique & 0xffff)) unique = 1;
709         } while (unique != num);
710     }
711
712     TRACE("returning %s\n", debugstr_w(buffer) );
713     return unique;
714 }
715
716
717 /***********************************************************************
718  *           contains_pathW
719  *
720  * Check if the file name contains a path; helper for SearchPathW.
721  * A relative path is not considered a path unless it starts with ./ or ../
722  */
723 static inline BOOL contains_pathW (LPCWSTR name)
724 {
725     if (RtlDetermineDosPathNameType_U( name ) != RELATIVE_PATH) return TRUE;
726     if (name[0] != '.') return FALSE;
727     if (name[1] == '/' || name[1] == '\\') return TRUE;
728     return (name[1] == '.' && (name[2] == '/' || name[2] == '\\'));
729 }
730
731
732 /***********************************************************************
733  * SearchPathW [KERNEL32.@]
734  *
735  * Searches for a specified file in the search path.
736  *
737  * PARAMS
738  *    path      [I] Path to search (NULL means default)
739  *    name      [I] Filename to search for.
740  *    ext       [I] File extension to append to file name. The first
741  *                  character must be a period. This parameter is
742  *                  specified only if the filename given does not
743  *                  contain an extension.
744  *    buflen    [I] size of buffer, in characters
745  *    buffer    [O] buffer for found filename
746  *    lastpart  [O] address of pointer to last used character in
747  *                  buffer (the final '\')
748  *
749  * RETURNS
750  *    Success: length of string copied into buffer, not including
751  *             terminating null character. If the filename found is
752  *             longer than the length of the buffer, the length of the
753  *             filename is returned.
754  *    Failure: Zero
755  *
756  * NOTES
757  *    If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
758  *    (tested on NT 4.0)
759  */
760 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
761                           LPWSTR buffer, LPWSTR *lastpart )
762 {
763     DWORD ret = 0;
764
765     if (!name || !name[0])
766     {
767         SetLastError(ERROR_INVALID_PARAMETER);
768         return 0;
769     }
770
771     /* If the name contains an explicit path, ignore the path */
772
773     if (contains_pathW(name))
774     {
775         /* try first without extension */
776         if (RtlDoesFileExists_U( name ))
777             return GetFullPathNameW( name, buflen, buffer, lastpart );
778
779         if (ext)
780         {
781             LPCWSTR p = strrchrW( name, '.' );
782             if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
783                 ext = NULL;  /* Ignore the specified extension */
784         }
785
786         /* Allocate a buffer for the file name and extension */
787         if (ext)
788         {
789             LPWSTR tmp;
790             DWORD len = strlenW(name) + strlenW(ext);
791
792             if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
793             {
794                 SetLastError( ERROR_OUTOFMEMORY );
795                 return 0;
796             }
797             strcpyW( tmp, name );
798             strcatW( tmp, ext );
799             if (RtlDoesFileExists_U( tmp ))
800                 ret = GetFullPathNameW( tmp, buflen, buffer, lastpart );
801             HeapFree( GetProcessHeap(), 0, tmp );
802         }
803     }
804     else if (path && path[0])  /* search in the specified path */
805     {
806         ret = RtlDosSearchPath_U( path, name, ext, buflen * sizeof(WCHAR),
807                                   buffer, lastpart ) / sizeof(WCHAR);
808     }
809     else  /* search in the default path */
810     {
811         WCHAR *dll_path = MODULE_get_dll_load_path( NULL );
812
813         if (dll_path)
814         {
815             ret = RtlDosSearchPath_U( dll_path, name, ext, buflen * sizeof(WCHAR),
816                                       buffer, lastpart ) / sizeof(WCHAR);
817             HeapFree( GetProcessHeap(), 0, dll_path );
818         }
819         else
820         {
821             SetLastError( ERROR_OUTOFMEMORY );
822             return 0;
823         }
824     }
825
826     if (!ret) SetLastError( ERROR_FILE_NOT_FOUND );
827     else TRACE( "found %s\n", debugstr_w(buffer) );
828     return ret;
829 }
830
831
832 /***********************************************************************
833  *           SearchPathA   (KERNEL32.@)
834  *
835  * See SearchPathW.
836  */
837 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
838                           DWORD buflen, LPSTR buffer, LPSTR *lastpart )
839 {
840     WCHAR *pathW = NULL, *nameW, *extW = NULL;
841     WCHAR bufferW[MAX_PATH];
842     DWORD ret;
843
844     if (!name)
845     {
846         SetLastError(ERROR_INVALID_PARAMETER);
847         return 0;
848     }
849
850     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return 0;
851     if (path && !(pathW = FILE_name_AtoW( path, TRUE ))) return 0;
852     
853     if (ext && !(extW = FILE_name_AtoW( ext, TRUE )))
854     {
855         HeapFree( GetProcessHeap(), 0, pathW );
856         return 0;
857     }
858
859     ret = SearchPathW(pathW, nameW, extW, MAX_PATH, bufferW, NULL);
860
861     HeapFree( GetProcessHeap(), 0, pathW );
862     HeapFree( GetProcessHeap(), 0, extW );
863
864     if (!ret) return 0;
865     if (ret > MAX_PATH)
866     {
867         SetLastError(ERROR_FILENAME_EXCED_RANGE);
868         return 0;
869     }
870     ret = copy_filename_WtoA( bufferW, buffer, buflen );
871     if (buflen > ret && lastpart)
872         *lastpart = strrchr(buffer, '\\') + 1;
873     return ret;
874 }
875
876 static BOOL is_same_file(HANDLE h1, HANDLE h2)
877 {
878     int fd1;
879     BOOL ret = FALSE;
880     if (wine_server_handle_to_fd(h1, 0, &fd1, NULL) == STATUS_SUCCESS)
881     {
882         int fd2;
883         if (wine_server_handle_to_fd(h2, 0, &fd2, NULL) == STATUS_SUCCESS)
884         {
885             struct stat stat1, stat2;
886             if (fstat(fd1, &stat1) == 0 && fstat(fd2, &stat2) == 0)
887                 ret = (stat1.st_dev == stat2.st_dev && stat1.st_ino == stat2.st_ino);
888             wine_server_release_fd(h2, fd2);
889         }
890         wine_server_release_fd(h1, fd1);
891     }
892     return ret;
893 }
894
895 /**************************************************************************
896  *           CopyFileW   (KERNEL32.@)
897  */
898 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
899 {
900     static const int buffer_size = 65536;
901     HANDLE h1, h2;
902     BY_HANDLE_FILE_INFORMATION info;
903     DWORD count;
904     BOOL ret = FALSE;
905     char *buffer;
906
907     if (!source || !dest)
908     {
909         SetLastError(ERROR_INVALID_PARAMETER);
910         return FALSE;
911     }
912     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, buffer_size )))
913     {
914         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
915         return FALSE;
916     }
917
918     TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
919
920     if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
921                      NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
922     {
923         WARN("Unable to open source %s\n", debugstr_w(source));
924         HeapFree( GetProcessHeap(), 0, buffer );
925         return FALSE;
926     }
927
928     if (!GetFileInformationByHandle( h1, &info ))
929     {
930         WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
931         HeapFree( GetProcessHeap(), 0, buffer );
932         CloseHandle( h1 );
933         return FALSE;
934     }
935
936     if (!fail_if_exists)
937     {
938         BOOL same_file = FALSE;
939         h2 = CreateFileW( dest, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
940                          OPEN_EXISTING, 0, 0);
941         if (h2 != INVALID_HANDLE_VALUE)
942         {
943             same_file = is_same_file( h1, h2 );
944             CloseHandle( h2 );
945         }
946         if (same_file)
947         {
948             HeapFree( GetProcessHeap(), 0, buffer );
949             CloseHandle( h1 );
950             SetLastError( ERROR_SHARING_VIOLATION );
951             return FALSE;
952         }
953     }
954
955     if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
956                              fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
957                              info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
958     {
959         WARN("Unable to open dest %s\n", debugstr_w(dest));
960         HeapFree( GetProcessHeap(), 0, buffer );
961         CloseHandle( h1 );
962         return FALSE;
963     }
964
965     while (ReadFile( h1, buffer, buffer_size, &count, NULL ) && count)
966     {
967         char *p = buffer;
968         while (count != 0)
969         {
970             DWORD res;
971             if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
972             p += res;
973             count -= res;
974         }
975     }
976     ret =  TRUE;
977 done:
978     /* Maintain the timestamp of source file to destination file */
979     SetFileTime(h2, NULL, NULL, &info.ftLastWriteTime);
980     HeapFree( GetProcessHeap(), 0, buffer );
981     CloseHandle( h1 );
982     CloseHandle( h2 );
983     return ret;
984 }
985
986
987 /**************************************************************************
988  *           CopyFileA   (KERNEL32.@)
989  */
990 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
991 {
992     WCHAR *sourceW, *destW;
993     BOOL ret;
994
995     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
996     if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
997
998     ret = CopyFileW( sourceW, destW, fail_if_exists );
999
1000     HeapFree( GetProcessHeap(), 0, destW );
1001     return ret;
1002 }
1003
1004
1005 /**************************************************************************
1006  *           CopyFileExW   (KERNEL32.@)
1007  *
1008  * This implementation ignores most of the extra parameters passed-in into
1009  * the "ex" version of the method and calls the CopyFile method.
1010  * It will have to be fixed eventually.
1011  */
1012 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
1013                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1014                         LPBOOL cancelFlagPointer, DWORD copyFlags)
1015 {
1016     /*
1017      * Interpret the only flag that CopyFile can interpret.
1018      */
1019     return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
1020 }
1021
1022
1023 /**************************************************************************
1024  *           CopyFileExA   (KERNEL32.@)
1025  */
1026 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1027                         LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1028                         LPBOOL cancelFlagPointer, DWORD copyFlags)
1029 {
1030     WCHAR *sourceW, *destW;
1031     BOOL ret;
1032
1033     /* can't use the TEB buffer since we may have a callback routine */
1034     if (!(sourceW = FILE_name_AtoW( sourceFilename, TRUE ))) return FALSE;
1035     if (!(destW = FILE_name_AtoW( destFilename, TRUE )))
1036     {
1037         HeapFree( GetProcessHeap(), 0, sourceW );
1038         return FALSE;
1039     }
1040     ret = CopyFileExW(sourceW, destW, progressRoutine, appData,
1041                       cancelFlagPointer, copyFlags);
1042     HeapFree( GetProcessHeap(), 0, sourceW );
1043     HeapFree( GetProcessHeap(), 0, destW );
1044     return ret;
1045 }
1046
1047
1048 /**************************************************************************
1049  *           MoveFileWithProgressW   (KERNEL32.@)
1050  */
1051 BOOL WINAPI MoveFileWithProgressW( LPCWSTR source, LPCWSTR dest,
1052                                    LPPROGRESS_ROUTINE fnProgress,
1053                                    LPVOID param, DWORD flag )
1054 {
1055     FILE_BASIC_INFORMATION info;
1056     UNICODE_STRING nt_name;
1057     OBJECT_ATTRIBUTES attr;
1058     IO_STATUS_BLOCK io;
1059     NTSTATUS status;
1060     HANDLE source_handle = 0, dest_handle;
1061     ANSI_STRING source_unix, dest_unix;
1062
1063     TRACE("(%s,%s,%p,%p,%04x)\n",
1064           debugstr_w(source), debugstr_w(dest), fnProgress, param, flag );
1065
1066     if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1067         return add_boot_rename_entry( source, dest, flag );
1068
1069     if (!dest)
1070         return DeleteFileW( source );
1071
1072     if (flag & MOVEFILE_WRITE_THROUGH)
1073         FIXME("MOVEFILE_WRITE_THROUGH unimplemented\n");
1074
1075     /* check if we are allowed to rename the source */
1076
1077     if (!RtlDosPathNameToNtPathName_U( source, &nt_name, NULL, NULL ))
1078     {
1079         SetLastError( ERROR_PATH_NOT_FOUND );
1080         return FALSE;
1081     }
1082     source_unix.Buffer = NULL;
1083     dest_unix.Buffer = NULL;
1084     attr.Length = sizeof(attr);
1085     attr.RootDirectory = 0;
1086     attr.Attributes = OBJ_CASE_INSENSITIVE;
1087     attr.ObjectName = &nt_name;
1088     attr.SecurityDescriptor = NULL;
1089     attr.SecurityQualityOfService = NULL;
1090
1091     status = NtOpenFile( &source_handle, 0, &attr, &io, 0, FILE_SYNCHRONOUS_IO_NONALERT );
1092     if (status == STATUS_SUCCESS)
1093         status = wine_nt_to_unix_file_name( &nt_name, &source_unix, FILE_OPEN, FALSE );
1094     RtlFreeUnicodeString( &nt_name );
1095     if (status != STATUS_SUCCESS)
1096     {
1097         SetLastError( RtlNtStatusToDosError(status) );
1098         goto error;
1099     }
1100     status = NtQueryInformationFile( source_handle, &io, &info, sizeof(info), FileBasicInformation );
1101     if (status != STATUS_SUCCESS)
1102     {
1103         SetLastError( RtlNtStatusToDosError(status) );
1104         goto error;
1105     }
1106
1107     /* we must have write access to the destination, and it must */
1108     /* not exist except if MOVEFILE_REPLACE_EXISTING is set */
1109
1110     if (!RtlDosPathNameToNtPathName_U( dest, &nt_name, NULL, NULL ))
1111     {
1112         SetLastError( ERROR_PATH_NOT_FOUND );
1113         goto error;
1114     }
1115     status = NtOpenFile( &dest_handle, GENERIC_READ | GENERIC_WRITE, &attr, &io, 0,
1116                          FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1117     if (status == STATUS_SUCCESS)  /* destination exists */
1118     {
1119         NtClose( dest_handle );
1120         if (!(flag & MOVEFILE_REPLACE_EXISTING))
1121         {
1122             SetLastError( ERROR_ALREADY_EXISTS );
1123             RtlFreeUnicodeString( &nt_name );
1124             goto error;
1125         }
1126         else if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) /* cannot replace directory */
1127         {
1128             SetLastError( ERROR_ACCESS_DENIED );
1129             goto error;
1130         }
1131     }
1132     else if (status != STATUS_OBJECT_NAME_NOT_FOUND)
1133     {
1134         SetLastError( RtlNtStatusToDosError(status) );
1135         RtlFreeUnicodeString( &nt_name );
1136         goto error;
1137     }
1138
1139     status = wine_nt_to_unix_file_name( &nt_name, &dest_unix, FILE_OPEN_IF, FALSE );
1140     RtlFreeUnicodeString( &nt_name );
1141     if (status != STATUS_SUCCESS && status != STATUS_NO_SUCH_FILE)
1142     {
1143         SetLastError( RtlNtStatusToDosError(status) );
1144         goto error;
1145     }
1146
1147     /* now perform the rename */
1148
1149     if (rename( source_unix.Buffer, dest_unix.Buffer ) == -1)
1150     {
1151         if (errno == EXDEV && (flag & MOVEFILE_COPY_ALLOWED))
1152         {
1153             NtClose( source_handle );
1154             RtlFreeAnsiString( &source_unix );
1155             RtlFreeAnsiString( &dest_unix );
1156             if (!CopyFileExW( source, dest, fnProgress,
1157                               param, NULL, COPY_FILE_FAIL_IF_EXISTS ))
1158                 return FALSE;
1159             return DeleteFileW( source );
1160         }
1161         FILE_SetDosError();
1162         /* if we created the destination, remove it */
1163         if (io.Information == FILE_CREATED) unlink( dest_unix.Buffer );
1164         goto error;
1165     }
1166
1167     /* fixup executable permissions */
1168
1169     if (is_executable( source ) != is_executable( dest ))
1170     {
1171         struct stat fstat;
1172         if (stat( dest_unix.Buffer, &fstat ) != -1)
1173         {
1174             if (is_executable( dest ))
1175                 /* set executable bit where read bit is set */
1176                 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
1177             else
1178                 fstat.st_mode &= ~0111;
1179             chmod( dest_unix.Buffer, fstat.st_mode );
1180         }
1181     }
1182
1183     NtClose( source_handle );
1184     RtlFreeAnsiString( &source_unix );
1185     RtlFreeAnsiString( &dest_unix );
1186     return TRUE;
1187
1188 error:
1189     if (source_handle) NtClose( source_handle );
1190     RtlFreeAnsiString( &source_unix );
1191     RtlFreeAnsiString( &dest_unix );
1192     return FALSE;
1193 }
1194
1195 /**************************************************************************
1196  *           MoveFileWithProgressA   (KERNEL32.@)
1197  */
1198 BOOL WINAPI MoveFileWithProgressA( LPCSTR source, LPCSTR dest,
1199                                    LPPROGRESS_ROUTINE fnProgress,
1200                                    LPVOID param, DWORD flag )
1201 {
1202     WCHAR *sourceW, *destW;
1203     BOOL ret;
1204
1205     if (!(sourceW = FILE_name_AtoW( source, FALSE ))) return FALSE;
1206     if (dest)
1207     {
1208         if (!(destW = FILE_name_AtoW( dest, TRUE ))) return FALSE;
1209     }
1210     else
1211         destW = NULL;
1212
1213     ret = MoveFileWithProgressW( sourceW, destW, fnProgress, param, flag );
1214     HeapFree( GetProcessHeap(), 0, destW );
1215     return ret;
1216 }
1217
1218 /**************************************************************************
1219  *           MoveFileExW   (KERNEL32.@)
1220  */
1221 BOOL WINAPI MoveFileExW( LPCWSTR source, LPCWSTR dest, DWORD flag )
1222 {
1223     return MoveFileWithProgressW( source, dest, NULL, NULL, flag );
1224 }
1225
1226 /**************************************************************************
1227  *           MoveFileExA   (KERNEL32.@)
1228  */
1229 BOOL WINAPI MoveFileExA( LPCSTR source, LPCSTR dest, DWORD flag )
1230 {
1231     return MoveFileWithProgressA( source, dest, NULL, NULL, flag );
1232 }
1233
1234
1235 /**************************************************************************
1236  *           MoveFileW   (KERNEL32.@)
1237  *
1238  *  Move file or directory
1239  */
1240 BOOL WINAPI MoveFileW( LPCWSTR source, LPCWSTR dest )
1241 {
1242     return MoveFileExW( source, dest, MOVEFILE_COPY_ALLOWED );
1243 }
1244
1245
1246 /**************************************************************************
1247  *           MoveFileA   (KERNEL32.@)
1248  */
1249 BOOL WINAPI MoveFileA( LPCSTR source, LPCSTR dest )
1250 {
1251     return MoveFileExA( source, dest, MOVEFILE_COPY_ALLOWED );
1252 }
1253
1254
1255 /*************************************************************************
1256  *           CreateHardLinkW   (KERNEL32.@)
1257  */
1258 BOOL WINAPI CreateHardLinkW(LPCWSTR lpFileName, LPCWSTR lpExistingFileName,
1259     LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1260 {
1261     NTSTATUS status;
1262     UNICODE_STRING ntDest, ntSource;
1263     ANSI_STRING unixDest, unixSource;
1264     BOOL ret = FALSE;
1265
1266     TRACE("(%s, %s, %p)\n", debugstr_w(lpFileName),
1267         debugstr_w(lpExistingFileName), lpSecurityAttributes);
1268
1269     ntDest.Buffer = ntSource.Buffer = NULL;
1270     if (!RtlDosPathNameToNtPathName_U( lpFileName, &ntDest, NULL, NULL ) ||
1271         !RtlDosPathNameToNtPathName_U( lpExistingFileName, &ntSource, NULL, NULL ))
1272     {
1273         SetLastError( ERROR_PATH_NOT_FOUND );
1274         goto err;
1275     }
1276
1277     unixSource.Buffer = unixDest.Buffer = NULL;
1278     status = wine_nt_to_unix_file_name( &ntSource, &unixSource, FILE_OPEN, FALSE );
1279     if (!status)
1280     {
1281         status = wine_nt_to_unix_file_name( &ntDest, &unixDest, FILE_CREATE, FALSE );
1282         if (!status) /* destination must not exist */
1283         {
1284             status = STATUS_OBJECT_NAME_EXISTS;
1285         } else if (status == STATUS_NO_SUCH_FILE)
1286         {
1287             status = STATUS_SUCCESS;
1288         }
1289     }
1290
1291     if (status)
1292          SetLastError( RtlNtStatusToDosError(status) );
1293     else if (!link( unixSource.Buffer, unixDest.Buffer ))
1294     {
1295         TRACE("Hardlinked '%s' to '%s'\n", debugstr_a( unixDest.Buffer ),
1296                 debugstr_a( unixSource.Buffer ));
1297         ret = TRUE;
1298     }
1299     else
1300         FILE_SetDosError();
1301
1302     RtlFreeAnsiString( &unixSource );
1303     RtlFreeAnsiString( &unixDest );
1304
1305 err:
1306     RtlFreeUnicodeString( &ntSource );
1307     RtlFreeUnicodeString( &ntDest );
1308     return ret;
1309 }
1310
1311
1312 /*************************************************************************
1313  *           CreateHardLinkA   (KERNEL32.@)
1314  */
1315 BOOL WINAPI CreateHardLinkA(LPCSTR lpFileName, LPCSTR lpExistingFileName,
1316     LPSECURITY_ATTRIBUTES lpSecurityAttributes)
1317 {
1318     WCHAR *sourceW, *destW;
1319     BOOL res;
1320
1321     if (!(sourceW = FILE_name_AtoW( lpExistingFileName, TRUE )))
1322     {
1323         return FALSE;
1324     }
1325     if (!(destW = FILE_name_AtoW( lpFileName, TRUE )))
1326     {
1327         HeapFree( GetProcessHeap(), 0, sourceW );
1328         return FALSE;
1329     }
1330
1331     res = CreateHardLinkW( destW, sourceW, lpSecurityAttributes );
1332
1333     HeapFree( GetProcessHeap(), 0, sourceW );
1334     HeapFree( GetProcessHeap(), 0, destW );
1335
1336     return res;
1337 }
1338
1339
1340 /***********************************************************************
1341  *           CreateDirectoryW   (KERNEL32.@)
1342  * RETURNS:
1343  *      TRUE : success
1344  *      FALSE : failure
1345  *              ERROR_DISK_FULL:        on full disk
1346  *              ERROR_ALREADY_EXISTS:   if directory name exists (even as file)
1347  *              ERROR_ACCESS_DENIED:    on permission problems
1348  *              ERROR_FILENAME_EXCED_RANGE: too long filename(s)
1349  */
1350 BOOL WINAPI CreateDirectoryW( LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1351 {
1352     OBJECT_ATTRIBUTES attr;
1353     UNICODE_STRING nt_name;
1354     IO_STATUS_BLOCK io;
1355     NTSTATUS status;
1356     HANDLE handle;
1357     BOOL ret = FALSE;
1358
1359     TRACE( "%s\n", debugstr_w(path) );
1360
1361     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1362     {
1363         SetLastError( ERROR_PATH_NOT_FOUND );
1364         return FALSE;
1365     }
1366     attr.Length = sizeof(attr);
1367     attr.RootDirectory = 0;
1368     attr.Attributes = OBJ_CASE_INSENSITIVE;
1369     attr.ObjectName = &nt_name;
1370     attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
1371     attr.SecurityQualityOfService = NULL;
1372
1373     status = NtCreateFile( &handle, GENERIC_READ, &attr, &io, NULL,
1374                            FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ, FILE_CREATE,
1375                            FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 );
1376
1377     if (status == STATUS_SUCCESS)
1378     {
1379         NtClose( handle );
1380         ret = TRUE;
1381     }
1382     else SetLastError( RtlNtStatusToDosError(status) );
1383
1384     RtlFreeUnicodeString( &nt_name );
1385     return ret;
1386 }
1387
1388
1389 /***********************************************************************
1390  *           CreateDirectoryA   (KERNEL32.@)
1391  */
1392 BOOL WINAPI CreateDirectoryA( LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1393 {
1394     WCHAR *pathW;
1395
1396     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1397     return CreateDirectoryW( pathW, sa );
1398 }
1399
1400
1401 /***********************************************************************
1402  *           CreateDirectoryExA   (KERNEL32.@)
1403  */
1404 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path, LPSECURITY_ATTRIBUTES sa )
1405 {
1406     WCHAR *pathW, *templateW = NULL;
1407     BOOL ret;
1408
1409     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1410     if (template && !(templateW = FILE_name_AtoW( template, TRUE ))) return FALSE;
1411
1412     ret = CreateDirectoryExW( templateW, pathW, sa );
1413     HeapFree( GetProcessHeap(), 0, templateW );
1414     return ret;
1415 }
1416
1417
1418 /***********************************************************************
1419  *           CreateDirectoryExW   (KERNEL32.@)
1420  */
1421 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path, LPSECURITY_ATTRIBUTES sa )
1422 {
1423     return CreateDirectoryW( path, sa );
1424 }
1425
1426
1427 /***********************************************************************
1428  *           RemoveDirectoryW   (KERNEL32.@)
1429  */
1430 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
1431 {
1432     OBJECT_ATTRIBUTES attr;
1433     UNICODE_STRING nt_name;
1434     ANSI_STRING unix_name;
1435     IO_STATUS_BLOCK io;
1436     NTSTATUS status;
1437     HANDLE handle;
1438     BOOL ret = FALSE;
1439
1440     TRACE( "%s\n", debugstr_w(path) );
1441
1442     if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1443     {
1444         SetLastError( ERROR_PATH_NOT_FOUND );
1445         return FALSE;
1446     }
1447     attr.Length = sizeof(attr);
1448     attr.RootDirectory = 0;
1449     attr.Attributes = OBJ_CASE_INSENSITIVE;
1450     attr.ObjectName = &nt_name;
1451     attr.SecurityDescriptor = NULL;
1452     attr.SecurityQualityOfService = NULL;
1453
1454     status = NtOpenFile( &handle, DELETE, &attr, &io,
1455                          FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1456                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1457     if (status == STATUS_SUCCESS)
1458         status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE );
1459     RtlFreeUnicodeString( &nt_name );
1460
1461     if (status != STATUS_SUCCESS)
1462     {
1463         SetLastError( RtlNtStatusToDosError(status) );
1464         return FALSE;
1465     }
1466
1467     if (!(ret = (rmdir( unix_name.Buffer ) != -1))) FILE_SetDosError();
1468     RtlFreeAnsiString( &unix_name );
1469     NtClose( handle );
1470     return ret;
1471 }
1472
1473
1474 /***********************************************************************
1475  *           RemoveDirectoryA   (KERNEL32.@)
1476  */
1477 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
1478 {
1479     WCHAR *pathW;
1480
1481     if (!(pathW = FILE_name_AtoW( path, FALSE ))) return FALSE;
1482     return RemoveDirectoryW( pathW );
1483 }
1484
1485
1486 /***********************************************************************
1487  *           GetCurrentDirectoryW   (KERNEL32.@)
1488  */
1489 UINT WINAPI GetCurrentDirectoryW( UINT buflen, LPWSTR buf )
1490 {
1491     return RtlGetCurrentDirectory_U( buflen * sizeof(WCHAR), buf ) / sizeof(WCHAR);
1492 }
1493
1494
1495 /***********************************************************************
1496  *           GetCurrentDirectoryA   (KERNEL32.@)
1497  */
1498 UINT WINAPI GetCurrentDirectoryA( UINT buflen, LPSTR buf )
1499 {
1500     WCHAR bufferW[MAX_PATH];
1501     DWORD ret;
1502
1503     if (buflen && buf && ((ULONG_PTR)buf >> 16) == 0)
1504     {
1505         /* Win9x catches access violations here, returning zero.
1506          * This behaviour resulted in some people not noticing
1507          * that they got the argument order wrong. So let's be
1508          * nice and fail gracefully if buf is invalid and looks
1509          * more like a buflen. */
1510         SetLastError(ERROR_INVALID_PARAMETER);
1511         return 0;
1512     }
1513
1514     ret = GetCurrentDirectoryW(MAX_PATH, bufferW);
1515
1516     if (!ret) return 0;
1517     if (ret > MAX_PATH)
1518     {
1519         SetLastError(ERROR_FILENAME_EXCED_RANGE);
1520         return 0;
1521     }
1522     return copy_filename_WtoA( bufferW, buf, buflen );
1523 }
1524
1525
1526 /***********************************************************************
1527  *           SetCurrentDirectoryW   (KERNEL32.@)
1528  */
1529 BOOL WINAPI SetCurrentDirectoryW( LPCWSTR dir )
1530 {
1531     UNICODE_STRING dirW;
1532     NTSTATUS status;
1533
1534     RtlInitUnicodeString( &dirW, dir );
1535     status = RtlSetCurrentDirectory_U( &dirW );
1536     if (status != STATUS_SUCCESS)
1537     {
1538         SetLastError( RtlNtStatusToDosError(status) );
1539         return FALSE;
1540     }
1541     return TRUE;
1542 }
1543
1544
1545 /***********************************************************************
1546  *           SetCurrentDirectoryA   (KERNEL32.@)
1547  */
1548 BOOL WINAPI SetCurrentDirectoryA( LPCSTR dir )
1549 {
1550     WCHAR *dirW;
1551
1552     if (!(dirW = FILE_name_AtoW( dir, FALSE ))) return FALSE;
1553     return SetCurrentDirectoryW( dirW );
1554 }
1555
1556
1557 /***********************************************************************
1558  *           GetWindowsDirectoryW   (KERNEL32.@)
1559  *
1560  * See comment for GetWindowsDirectoryA.
1561  */
1562 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
1563 {
1564     UINT len = strlenW( DIR_Windows ) + 1;
1565     if (path && count >= len)
1566     {
1567         strcpyW( path, DIR_Windows );
1568         len--;
1569     }
1570     return len;
1571 }
1572
1573
1574 /***********************************************************************
1575  *           GetWindowsDirectoryA   (KERNEL32.@)
1576  *
1577  * Return value:
1578  * If buffer is large enough to hold full path and terminating '\0' character
1579  * function copies path to buffer and returns length of the path without '\0'.
1580  * Otherwise function returns required size including '\0' character and
1581  * does not touch the buffer.
1582  */
1583 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
1584 {
1585     return copy_filename_WtoA( DIR_Windows, path, count );
1586 }
1587
1588
1589 /***********************************************************************
1590  *           GetSystemWindowsDirectoryA   (KERNEL32.@) W2K, TS4.0SP4
1591  */
1592 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
1593 {
1594     return GetWindowsDirectoryA( path, count );
1595 }
1596
1597
1598 /***********************************************************************
1599  *           GetSystemWindowsDirectoryW   (KERNEL32.@) W2K, TS4.0SP4
1600  */
1601 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
1602 {
1603     return GetWindowsDirectoryW( path, count );
1604 }
1605
1606
1607 /***********************************************************************
1608  *           GetSystemDirectoryW   (KERNEL32.@)
1609  *
1610  * See comment for GetWindowsDirectoryA.
1611  */
1612 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
1613 {
1614     UINT len = strlenW( DIR_System ) + 1;
1615     if (path && count >= len)
1616     {
1617         strcpyW( path, DIR_System );
1618         len--;
1619     }
1620     return len;
1621 }
1622
1623
1624 /***********************************************************************
1625  *           GetSystemDirectoryA   (KERNEL32.@)
1626  *
1627  * See comment for GetWindowsDirectoryA.
1628  */
1629 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
1630 {
1631     return copy_filename_WtoA( DIR_System, path, count );
1632 }
1633
1634
1635 /***********************************************************************
1636  *           GetSystemWow64DirectoryW   (KERNEL32.@)
1637  *
1638  * As seen on MSDN
1639  * - On Win32 we should returns ERROR_CALL_NOT_IMPLEMENTED
1640  * - On Win64 we should returns the SysWow64 (system64) directory
1641  */
1642 UINT WINAPI GetSystemWow64DirectoryW( LPWSTR path, UINT count )
1643 {
1644     UINT len;
1645
1646     if (!DIR_SysWow64)
1647     {
1648         SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1649         return 0;
1650     }
1651     len = strlenW( DIR_SysWow64 ) + 1;
1652     if (path && count >= len)
1653     {
1654         strcpyW( path, DIR_SysWow64 );
1655         len--;
1656     }
1657     return len;
1658 }
1659
1660
1661 /***********************************************************************
1662  *           GetSystemWow64DirectoryA   (KERNEL32.@)
1663  *
1664  * See comment for GetWindowsWow64DirectoryW.
1665  */
1666 UINT WINAPI GetSystemWow64DirectoryA( LPSTR path, UINT count )
1667 {
1668     if (!DIR_SysWow64)
1669     {
1670         SetLastError( ERROR_CALL_NOT_IMPLEMENTED );
1671         return 0;
1672     }
1673     return copy_filename_WtoA( DIR_SysWow64, path, count );
1674 }
1675
1676
1677 /***********************************************************************
1678  *           Wow64EnableWow64FsRedirection   (KERNEL32.@)
1679  */
1680 BOOLEAN WINAPI Wow64EnableWow64FsRedirection( BOOLEAN enable )
1681 {
1682     NTSTATUS status = RtlWow64EnableFsRedirection( enable );
1683     if (status) SetLastError( RtlNtStatusToDosError(status) );
1684     return !status;
1685 }
1686
1687
1688 /***********************************************************************
1689  *           Wow64DisableWow64FsRedirection   (KERNEL32.@)
1690  */
1691 BOOL WINAPI Wow64DisableWow64FsRedirection( PVOID *old_value )
1692 {
1693     NTSTATUS status = RtlWow64EnableFsRedirectionEx( TRUE, (ULONG *)old_value );
1694     if (status) SetLastError( RtlNtStatusToDosError(status) );
1695     return !status;
1696 }
1697
1698
1699 /***********************************************************************
1700  *           Wow64RevertWow64FsRedirection   (KERNEL32.@)
1701  */
1702 BOOL WINAPI Wow64RevertWow64FsRedirection( PVOID old_value )
1703 {
1704     NTSTATUS status = RtlWow64EnableFsRedirection( !old_value );
1705     if (status) SetLastError( RtlNtStatusToDosError(status) );
1706     return !status;
1707 }
1708
1709
1710 /***********************************************************************
1711  *           NeedCurrentDirectoryForExePathW   (KERNEL32.@)
1712  */
1713 BOOL WINAPI NeedCurrentDirectoryForExePathW( LPCWSTR name )
1714 {
1715     static const WCHAR env_name[] = {'N','o','D','e','f','a','u','l','t',
1716                                      'C','u','r','r','e','n','t',
1717                                      'D','i','r','e','c','t','o','r','y',
1718                                      'I','n','E','x','e','P','a','t','h',0};
1719     WCHAR env_val;
1720
1721     /* MSDN mentions some 'registry location'. We do not use registry. */
1722     FIXME("(%s): partial stub\n", debugstr_w(name));
1723
1724     if (strchrW(name, '\\'))
1725         return TRUE;
1726
1727     /* Check the existence of the variable, not value */
1728     if (!GetEnvironmentVariableW( env_name, &env_val, 1 ))
1729         return TRUE;
1730
1731     return FALSE;
1732 }
1733
1734
1735 /***********************************************************************
1736  *           NeedCurrentDirectoryForExePathA   (KERNEL32.@)
1737  */
1738 BOOL WINAPI NeedCurrentDirectoryForExePathA( LPCSTR name )
1739 {
1740     WCHAR *nameW;
1741
1742     if (!(nameW = FILE_name_AtoW( name, FALSE ))) return TRUE;
1743     return NeedCurrentDirectoryForExePathW( nameW );
1744 }
1745
1746
1747 /***********************************************************************
1748  *           wine_get_unix_file_name (KERNEL32.@) Not a Windows API
1749  *
1750  * Return the full Unix file name for a given path.
1751  * Returned buffer must be freed by caller.
1752  */
1753 char * CDECL wine_get_unix_file_name( LPCWSTR dosW )
1754 {
1755     UNICODE_STRING nt_name;
1756     ANSI_STRING unix_name;
1757     NTSTATUS status;
1758
1759     if (!RtlDosPathNameToNtPathName_U( dosW, &nt_name, NULL, NULL )) return NULL;
1760     status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
1761     RtlFreeUnicodeString( &nt_name );
1762     if (status && status != STATUS_NO_SUCH_FILE)
1763     {
1764         SetLastError( RtlNtStatusToDosError( status ) );
1765         return NULL;
1766     }
1767     return unix_name.Buffer;
1768 }
1769
1770
1771 /***********************************************************************
1772  *           wine_get_dos_file_name (KERNEL32.@) Not a Windows API
1773  *
1774  * Return the full DOS file name for a given Unix path.
1775  * Returned buffer must be freed by caller.
1776  */
1777 WCHAR * CDECL wine_get_dos_file_name( LPCSTR str )
1778 {
1779     UNICODE_STRING nt_name;
1780     ANSI_STRING unix_name;
1781     NTSTATUS status;
1782     DWORD len;
1783
1784     RtlInitAnsiString( &unix_name, str );
1785     status = wine_unix_to_nt_file_name( &unix_name, &nt_name );
1786     if (status)
1787     {
1788         SetLastError( RtlNtStatusToDosError( status ) );
1789         return NULL;
1790     }
1791     /* get rid of the \??\ prefix */
1792     /* FIXME: should implement RtlNtPathNameToDosPathName and use that instead */
1793     len = nt_name.Length - 4 * sizeof(WCHAR);
1794     memmove( nt_name.Buffer, nt_name.Buffer + 4, len );
1795     nt_name.Buffer[len / sizeof(WCHAR)] = 0;
1796     return nt_name.Buffer;
1797 }