ntdll/tests: Use '%u' to print GetLastError().
[wine] / dlls / ntdll / path.c
1 /*
2  * Ntdll path functions
3  *
4  * Copyright 2002, 2003, 2004 Alexandre Julliard
5  * Copyright 2003 Eric Pouech
6  *
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.
11  *
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.
16  *
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <sys/types.h>
27 #include <errno.h>
28 #ifdef HAVE_SYS_STAT_H
29 # include <sys/stat.h>
30 #endif
31 #ifdef HAVE_UNISTD_H
32 # include <unistd.h>
33 #endif
34
35 #include "ntstatus.h"
36 #define WIN32_NO_STATUS
37 #include "windef.h"
38 #include "winioctl.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/library.h"
42 #include "thread.h"
43 #include "ntdll_misc.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(file);
46
47 static const WCHAR DeviceRootW[] = {'\\','\\','.','\\',0};
48 static const WCHAR NTDosPrefixW[] = {'\\','?','?','\\',0};
49 static const WCHAR UncPfxW[] = {'U','N','C','\\',0};
50
51 #define IS_SEPARATOR(ch)  ((ch) == '\\' || (ch) == '/')
52
53 #define MAX_DOS_DRIVES 26
54
55 struct drive_info
56 {
57     dev_t dev;
58     ino_t ino;
59 };
60
61 /***********************************************************************
62  *           get_drives_info
63  *
64  * Retrieve device/inode number for all the drives. Helper for find_drive_root.
65  */
66 static inline int get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
67 {
68     const char *config_dir = wine_get_config_dir();
69     char *buffer, *p;
70     struct stat st;
71     int i, ret;
72
73     buffer = RtlAllocateHeap( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") );
74     if (!buffer) return 0;
75     strcpy( buffer, config_dir );
76     strcat( buffer, "/dosdevices/a:" );
77     p = buffer + strlen(buffer) - 2;
78
79     for (i = ret = 0; i < MAX_DOS_DRIVES; i++)
80     {
81         *p = 'a' + i;
82         if (!stat( buffer, &st ))
83         {
84             info[i].dev = st.st_dev;
85             info[i].ino = st.st_ino;
86             ret++;
87         }
88         else
89         {
90             info[i].dev = 0;
91             info[i].ino = 0;
92         }
93     }
94     RtlFreeHeap( GetProcessHeap(), 0, buffer );
95     return ret;
96 }
97
98
99 /***********************************************************************
100  *           remove_last_componentA
101  *
102  * Remove the last component of the path. Helper for find_drive_rootA.
103  */
104 static inline unsigned int remove_last_componentA( const char *path, unsigned int len )
105 {
106     int level = 0;
107
108     while (level < 1)
109     {
110         /* find start of the last path component */
111         unsigned int prev = len;
112         if (prev <= 1) break;  /* reached root */
113         while (prev > 1 && path[prev - 1] != '/') prev--;
114         /* does removing it take us up a level? */
115         if (len - prev != 1 || path[prev] != '.')  /* not '.' */
116         {
117             if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
118                 level--;
119             else
120                 level++;
121         }
122         /* strip off trailing slashes */
123         while (prev > 1 && path[prev - 1] == '/') prev--;
124         len = prev;
125     }
126     return len;
127 }
128
129
130 /***********************************************************************
131  *           find_drive_rootA
132  *
133  * Find a drive for which the root matches the beginning of the given path.
134  * This can be used to translate a Unix path into a drive + DOS path.
135  * Return value is the drive, or -1 on error. On success, ppath is modified
136  * to point to the beginning of the DOS path.
137  */
138 static NTSTATUS find_drive_rootA( LPCSTR *ppath, unsigned int len, int *drive_ret )
139 {
140     /* Starting with the full path, check if the device and inode match any of
141      * the wine 'drives'. If not then remove the last path component and try
142      * again. If the last component was a '..' then skip a normal component
143      * since it's a directory that's ascended back out of.
144      */
145     int drive;
146     char *buffer;
147     const char *path = *ppath;
148     struct stat st;
149     struct drive_info info[MAX_DOS_DRIVES];
150
151     /* get device and inode of all drives */
152     if (!get_drives_info( info )) return STATUS_OBJECT_PATH_NOT_FOUND;
153
154     /* strip off trailing slashes */
155     while (len > 1 && path[len - 1] == '/') len--;
156
157     /* make a copy of the path */
158     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, len + 1 ))) return STATUS_NO_MEMORY;
159     memcpy( buffer, path, len );
160     buffer[len] = 0;
161
162     for (;;)
163     {
164         if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
165         {
166             /* Find the drive */
167             for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
168             {
169                 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
170                 {
171                     if (len == 1) len = 0;  /* preserve root slash in returned path */
172                     TRACE( "%s -> drive %c:, root=%s, name=%s\n",
173                            debugstr_a(path), 'A' + drive, debugstr_a(buffer), debugstr_a(path + len));
174                     *ppath += len;
175                     *drive_ret = drive;
176                     RtlFreeHeap( GetProcessHeap(), 0, buffer );
177                     return STATUS_SUCCESS;
178                 }
179             }
180         }
181         if (len <= 1) break;  /* reached root */
182         len = remove_last_componentA( buffer, len );
183         buffer[len] = 0;
184     }
185     RtlFreeHeap( GetProcessHeap(), 0, buffer );
186     return STATUS_OBJECT_PATH_NOT_FOUND;
187 }
188
189
190 /***********************************************************************
191  *           remove_last_componentW
192  *
193  * Remove the last component of the path. Helper for find_drive_rootW.
194  */
195 static inline int remove_last_componentW( const WCHAR *path, int len )
196 {
197     int level = 0;
198
199     while (level < 1)
200     {
201         /* find start of the last path component */
202         int prev = len;
203         if (prev <= 1) break;  /* reached root */
204         while (prev > 1 && !IS_SEPARATOR(path[prev - 1])) prev--;
205         /* does removing it take us up a level? */
206         if (len - prev != 1 || path[prev] != '.')  /* not '.' */
207         {
208             if (len - prev == 2 && path[prev] == '.' && path[prev+1] == '.')  /* is it '..'? */
209                 level--;
210             else
211                 level++;
212         }
213         /* strip off trailing slashes */
214         while (prev > 1 && IS_SEPARATOR(path[prev - 1])) prev--;
215         len = prev;
216     }
217     return len;
218 }
219
220
221 /***********************************************************************
222  *           find_drive_rootW
223  *
224  * Find a drive for which the root matches the beginning of the given path.
225  * This can be used to translate a Unix path into a drive + DOS path.
226  * Return value is the drive, or -1 on error. On success, ppath is modified
227  * to point to the beginning of the DOS path.
228  */
229 static int find_drive_rootW( LPCWSTR *ppath )
230 {
231     /* Starting with the full path, check if the device and inode match any of
232      * the wine 'drives'. If not then remove the last path component and try
233      * again. If the last component was a '..' then skip a normal component
234      * since it's a directory that's ascended back out of.
235      */
236     int drive, lenA, lenW;
237     char *buffer, *p;
238     const WCHAR *path = *ppath;
239     struct stat st;
240     struct drive_info info[MAX_DOS_DRIVES];
241
242     /* get device and inode of all drives */
243     if (!get_drives_info( info )) return -1;
244
245     /* strip off trailing slashes */
246     lenW = strlenW(path);
247     while (lenW > 1 && IS_SEPARATOR(path[lenW - 1])) lenW--;
248
249     /* convert path to Unix encoding */
250     lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
251     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, lenA + 1 ))) return -1;
252     lenA = ntdll_wcstoumbs( 0, path, lenW, buffer, lenA, NULL, NULL );
253     buffer[lenA] = 0;
254     for (p = buffer; *p; p++) if (*p == '\\') *p = '/';
255
256     for (;;)
257     {
258         if (!stat( buffer, &st ) && S_ISDIR( st.st_mode ))
259         {
260             /* Find the drive */
261             for (drive = 0; drive < MAX_DOS_DRIVES; drive++)
262             {
263                 if ((info[drive].dev == st.st_dev) && (info[drive].ino == st.st_ino))
264                 {
265                     if (lenW == 1) lenW = 0;  /* preserve root slash in returned path */
266                     TRACE( "%s -> drive %c:, root=%s, name=%s\n",
267                            debugstr_w(path), 'A' + drive, debugstr_a(buffer), debugstr_w(path + lenW));
268                     *ppath += lenW;
269                     RtlFreeHeap( GetProcessHeap(), 0, buffer );
270                     return drive;
271                 }
272             }
273         }
274         if (lenW <= 1) break;  /* reached root */
275         lenW = remove_last_componentW( path, lenW );
276
277         /* we only need the new length, buffer already contains the converted string */
278         lenA = ntdll_wcstoumbs( 0, path, lenW, NULL, 0, NULL, NULL );
279         buffer[lenA] = 0;
280     }
281     RtlFreeHeap( GetProcessHeap(), 0, buffer );
282     return -1;
283 }
284
285
286 /***********************************************************************
287  *             RtlDetermineDosPathNameType_U   (NTDLL.@)
288  */
289 DOS_PATHNAME_TYPE WINAPI RtlDetermineDosPathNameType_U( PCWSTR path )
290 {
291     if (IS_SEPARATOR(path[0]))
292     {
293         if (!IS_SEPARATOR(path[1])) return ABSOLUTE_PATH;       /* "/foo" */
294         if (path[2] != '.') return UNC_PATH;                    /* "//foo" */
295         if (IS_SEPARATOR(path[3])) return DEVICE_PATH;          /* "//./foo" */
296         if (path[3]) return UNC_PATH;                           /* "//.foo" */
297         return UNC_DOT_PATH;                                    /* "//." */
298     }
299     else
300     {
301         if (!path[0] || path[1] != ':') return RELATIVE_PATH;   /* "foo" */
302         if (IS_SEPARATOR(path[2])) return ABSOLUTE_DRIVE_PATH;  /* "c:/foo" */
303         return RELATIVE_DRIVE_PATH;                             /* "c:foo" */
304     }
305 }
306
307 /***********************************************************************
308  *             RtlIsDosDeviceName_U   (NTDLL.@)
309  *
310  * Check if the given DOS path contains a DOS device name.
311  *
312  * Returns the length of the device name in the low word and its
313  * position in the high word (both in bytes, not WCHARs), or 0 if no
314  * device name is found.
315  */
316 ULONG WINAPI RtlIsDosDeviceName_U( PCWSTR dos_name )
317 {
318     static const WCHAR consoleW[] = {'\\','\\','.','\\','C','O','N',0};
319     static const WCHAR auxW[3] = {'A','U','X'};
320     static const WCHAR comW[3] = {'C','O','M'};
321     static const WCHAR conW[3] = {'C','O','N'};
322     static const WCHAR lptW[3] = {'L','P','T'};
323     static const WCHAR nulW[3] = {'N','U','L'};
324     static const WCHAR prnW[3] = {'P','R','N'};
325
326     const WCHAR *start, *end, *p;
327
328     switch(RtlDetermineDosPathNameType_U( dos_name ))
329     {
330     case INVALID_PATH:
331     case UNC_PATH:
332         return 0;
333     case DEVICE_PATH:
334         if (!strcmpiW( dos_name, consoleW ))
335             return MAKELONG( sizeof(conW), 4 * sizeof(WCHAR) );  /* 4 is length of \\.\ prefix */
336         return 0;
337     default:
338         break;
339     }
340
341     end = dos_name + strlenW(dos_name) - 1;
342     while (end >= dos_name && *end == ':') end--;  /* remove all trailing ':' */
343
344     /* find start of file name */
345     for (start = end; start >= dos_name; start--)
346     {
347         if (IS_SEPARATOR(start[0])) break;
348         /* check for ':' but ignore if before extension (for things like NUL:.txt) */
349         if (start[0] == ':' && start[1] != '.') break;
350     }
351     start++;
352
353     /* remove extension */
354     if ((p = strchrW( start, '.' )))
355     {
356         end = p - 1;
357         if (end >= dos_name && *end == ':') end--;  /* remove trailing ':' before extension */
358     }
359     /* remove trailing spaces */
360     while (end >= dos_name && *end == ' ') end--;
361
362     /* now we have a potential device name between start and end, check it */
363     switch(end - start + 1)
364     {
365     case 3:
366         if (strncmpiW( start, auxW, 3 ) &&
367             strncmpiW( start, conW, 3 ) &&
368             strncmpiW( start, nulW, 3 ) &&
369             strncmpiW( start, prnW, 3 )) break;
370         return MAKELONG( 3 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
371     case 4:
372         if (strncmpiW( start, comW, 3 ) && strncmpiW( start, lptW, 3 )) break;
373         if (*end <= '0' || *end > '9') break;
374         return MAKELONG( 4 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
375     default:  /* can't match anything */
376         break;
377     }
378     return 0;
379 }
380
381
382 /**************************************************************************
383  *                 RtlDosPathNameToNtPathName_U         [NTDLL.@]
384  *
385  * dos_path: a DOS path name (fully qualified or not)
386  * ntpath:   pointer to a UNICODE_STRING to hold the converted
387  *           path name
388  * file_part:will point (in ntpath) to the file part in the path
389  * cd:       directory reference (optional)
390  *
391  * FIXME:
392  *      + fill the cd structure
393  */
394 BOOLEAN  WINAPI RtlDosPathNameToNtPathName_U(PCWSTR dos_path,
395                                              PUNICODE_STRING ntpath,
396                                              PWSTR* file_part,
397                                              CURDIR* cd)
398 {
399     static const WCHAR LongFileNamePfxW[4] = {'\\','\\','?','\\'};
400     ULONG sz, offset;
401     WCHAR local[MAX_PATH];
402     LPWSTR ptr;
403
404     TRACE("(%s,%p,%p,%p)\n",
405           debugstr_w(dos_path), ntpath, file_part, cd);
406
407     if (cd)
408     {
409         FIXME("Unsupported parameter\n");
410         memset(cd, 0, sizeof(*cd));
411     }
412
413     if (!dos_path || !*dos_path) return FALSE;
414
415     if (!strncmpW(dos_path, LongFileNamePfxW, 4))
416     {
417         ntpath->Length = strlenW(dos_path) * sizeof(WCHAR);
418         ntpath->MaximumLength = ntpath->Length + sizeof(WCHAR);
419         ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
420         if (!ntpath->Buffer) return FALSE;
421         memcpy( ntpath->Buffer, dos_path, ntpath->MaximumLength );
422         ntpath->Buffer[1] = '?';  /* change \\?\ to \??\ */
423         if (file_part)
424         {
425             if ((ptr = strrchrW( ntpath->Buffer, '\\' )) && ptr[1]) *file_part = ptr + 1;
426             else *file_part = NULL;
427         }
428         return TRUE;
429     }
430
431     ptr = local;
432     sz = RtlGetFullPathName_U(dos_path, sizeof(local), ptr, file_part);
433     if (sz == 0) return FALSE;
434     if (sz > sizeof(local))
435     {
436         if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, sz))) return FALSE;
437         sz = RtlGetFullPathName_U(dos_path, sz, ptr, file_part);
438     }
439
440     ntpath->MaximumLength = sz + (4 /* unc\ */ + 4 /* \??\ */) * sizeof(WCHAR);
441     ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
442     if (!ntpath->Buffer)
443     {
444         if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
445         return FALSE;
446     }
447
448     strcpyW(ntpath->Buffer, NTDosPrefixW);
449     switch (RtlDetermineDosPathNameType_U(ptr))
450     {
451     case UNC_PATH: /* \\foo */
452         offset = 2;
453         strcatW(ntpath->Buffer, UncPfxW);
454         break;
455     case DEVICE_PATH: /* \\.\foo */
456         offset = 4;
457         break;
458     default:
459         offset = 0;
460         break;
461     }
462
463     strcatW(ntpath->Buffer, ptr + offset);
464     ntpath->Length = strlenW(ntpath->Buffer) * sizeof(WCHAR);
465
466     if (file_part && *file_part)
467         *file_part = ntpath->Buffer + ntpath->Length / sizeof(WCHAR) - strlenW(*file_part);
468
469     /* FIXME: cd filling */
470
471     if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
472     return TRUE;
473 }
474
475 /******************************************************************
476  *              RtlDosSearchPath_U
477  *
478  * Searchs a file of name 'name' into a ';' separated list of paths
479  * (stored in paths)
480  * Doesn't seem to search elsewhere than the paths list
481  * Stores the result in buffer (file_part will point to the position
482  * of the file name in the buffer)
483  * FIXME:
484  * - how long shall the paths be ??? (MAX_PATH or larger with \\?\ constructs ???)
485  */
486 ULONG WINAPI RtlDosSearchPath_U(LPCWSTR paths, LPCWSTR search, LPCWSTR ext, 
487                                 ULONG buffer_size, LPWSTR buffer, 
488                                 LPWSTR* file_part)
489 {
490     DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U(search);
491     ULONG len = 0;
492
493     if (type == RELATIVE_PATH)
494     {
495         ULONG allocated = 0, needed, filelen;
496         WCHAR *name = NULL;
497
498         filelen = 1 /* for \ */ + strlenW(search) + 1 /* \0 */;
499
500         /* Windows only checks for '.' without worrying about path components */
501         if (strchrW( search, '.' )) ext = NULL;
502         if (ext != NULL) filelen += strlenW(ext);
503
504         while (*paths)
505         {
506             LPCWSTR ptr;
507
508             for (needed = 0, ptr = paths; *ptr != 0 && *ptr++ != ';'; needed++);
509             if (needed + filelen > allocated)
510             {
511                 if (!name) name = RtlAllocateHeap(GetProcessHeap(), 0,
512                                                   (needed + filelen) * sizeof(WCHAR));
513                 else
514                 {
515                     WCHAR *newname = RtlReAllocateHeap(GetProcessHeap(), 0, name,
516                                                        (needed + filelen) * sizeof(WCHAR));
517                     if (!newname) RtlFreeHeap(GetProcessHeap(), 0, name);
518                     name = newname;
519                 }
520                 if (!name) return 0;
521                 allocated = needed + filelen;
522             }
523             memmove(name, paths, needed * sizeof(WCHAR));
524             /* append '\\' if none is present */
525             if (needed > 0 && name[needed - 1] != '\\') name[needed++] = '\\';
526             strcpyW(&name[needed], search);
527             if (ext) strcatW(&name[needed], ext);
528             if (RtlDoesFileExists_U(name))
529             {
530                 len = RtlGetFullPathName_U(name, buffer_size, buffer, file_part);
531                 break;
532             }
533             paths = ptr;
534         }
535         RtlFreeHeap(GetProcessHeap(), 0, name);
536     }
537     else if (RtlDoesFileExists_U(search))
538     {
539         len = RtlGetFullPathName_U(search, buffer_size, buffer, file_part);
540     }
541
542     return len;
543 }
544
545
546 /******************************************************************
547  *              collapse_path
548  *
549  * Helper for RtlGetFullPathName_U.
550  * Get rid of . and .. components in the path.
551  */
552 static inline void collapse_path( WCHAR *path, UINT mark )
553 {
554     WCHAR *p, *next;
555
556     /* convert every / into a \ */
557     for (p = path; *p; p++) if (*p == '/') *p = '\\';
558
559     /* collapse duplicate backslashes */
560     next = path + max( 1, mark );
561     for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
562     *next = 0;
563
564     p = path + mark;
565     while (*p)
566     {
567         if (*p == '.')
568         {
569             switch(p[1])
570             {
571             case '\\': /* .\ component */
572                 next = p + 2;
573                 memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
574                 continue;
575             case 0:  /* final . */
576                 if (p > path + mark) p--;
577                 *p = 0;
578                 continue;
579             case '.':
580                 if (p[2] == '\\')  /* ..\ component */
581                 {
582                     next = p + 3;
583                     if (p > path + mark)
584                     {
585                         p--;
586                         while (p > path + mark && p[-1] != '\\') p--;
587                     }
588                     memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
589                     continue;
590                 }
591                 else if (!p[2])  /* final .. */
592                 {
593                     if (p > path + mark)
594                     {
595                         p--;
596                         while (p > path + mark && p[-1] != '\\') p--;
597                         if (p > path + mark) p--;
598                     }
599                     *p = 0;
600                     continue;
601                 }
602                 break;
603             }
604         }
605         /* skip to the next component */
606         while (*p && *p != '\\') p++;
607         if (*p == '\\')
608         {
609             /* remove last dot in previous dir name */
610             if (p > path + mark && p[-1] == '.') memmove( p-1, p, (strlenW(p) + 1) * sizeof(WCHAR) );
611             else p++;
612         }
613     }
614
615     /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
616     while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
617     *p = 0;
618 }
619
620
621 /******************************************************************
622  *              skip_unc_prefix
623  *
624  * Skip the \\share\dir\ part of a file name. Helper for RtlGetFullPathName_U.
625  */
626 static const WCHAR *skip_unc_prefix( const WCHAR *ptr )
627 {
628     ptr += 2;
629     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* share name */
630     while (IS_SEPARATOR(*ptr)) ptr++;
631     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* dir name */
632     while (IS_SEPARATOR(*ptr)) ptr++;
633     return ptr;
634 }
635
636
637 /******************************************************************
638  *              get_full_path_helper
639  *
640  * Helper for RtlGetFullPathName_U
641  * Note: name and buffer are allowed to point to the same memory spot
642  */
643 static ULONG get_full_path_helper(LPCWSTR name, LPWSTR buffer, ULONG size)
644 {
645     ULONG                       reqsize = 0, mark = 0, dep = 0, deplen;
646     DOS_PATHNAME_TYPE           type;
647     LPWSTR                      ins_str = NULL;
648     LPCWSTR                     ptr;
649     const UNICODE_STRING*       cd;
650     WCHAR                       tmp[4];
651
652     /* return error if name only consists of spaces */
653     for (ptr = name; *ptr; ptr++) if (*ptr != ' ') break;
654     if (!*ptr) return 0;
655
656     RtlAcquirePebLock();
657
658     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
659         cd = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
660     else
661         cd = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
662
663     switch (type = RtlDetermineDosPathNameType_U(name))
664     {
665     case UNC_PATH:              /* \\foo   */
666         ptr = skip_unc_prefix( name );
667         mark = (ptr - name);
668         break;
669
670     case DEVICE_PATH:           /* \\.\foo */
671         mark = 4;
672         break;
673
674     case ABSOLUTE_DRIVE_PATH:   /* c:\foo  */
675         reqsize = sizeof(WCHAR);
676         tmp[0] = toupperW(name[0]);
677         ins_str = tmp;
678         dep = 1;
679         mark = 3;
680         break;
681
682     case RELATIVE_DRIVE_PATH:   /* c:foo   */
683         dep = 2;
684         if (toupperW(name[0]) != toupperW(cd->Buffer[0]) || cd->Buffer[1] != ':')
685         {
686             UNICODE_STRING      var, val;
687
688             tmp[0] = '=';
689             tmp[1] = name[0];
690             tmp[2] = ':';
691             tmp[3] = '\0';
692             var.Length = 3 * sizeof(WCHAR);
693             var.MaximumLength = 4 * sizeof(WCHAR);
694             var.Buffer = tmp;
695             val.Length = 0;
696             val.MaximumLength = size;
697             val.Buffer = RtlAllocateHeap(GetProcessHeap(), 0, size);
698
699             switch (RtlQueryEnvironmentVariable_U(NULL, &var, &val))
700             {
701             case STATUS_SUCCESS:
702                 /* FIXME: Win2k seems to check that the environment variable actually points 
703                  * to an existing directory. If not, root of the drive is used
704                  * (this seems also to be the only spot in RtlGetFullPathName that the 
705                  * existence of a part of a path is checked)
706                  */
707                 /* fall thru */
708             case STATUS_BUFFER_TOO_SMALL:
709                 reqsize = val.Length + sizeof(WCHAR); /* append trailing '\\' */
710                 val.Buffer[val.Length / sizeof(WCHAR)] = '\\';
711                 ins_str = val.Buffer;
712                 break;
713             case STATUS_VARIABLE_NOT_FOUND:
714                 reqsize = 3 * sizeof(WCHAR);
715                 tmp[0] = name[0];
716                 tmp[1] = ':';
717                 tmp[2] = '\\';
718                 ins_str = tmp;
719                 break;
720             default:
721                 ERR("Unsupported status code\n");
722                 break;
723             }
724             mark = 3;
725             break;
726         }
727         /* fall through */
728
729     case RELATIVE_PATH:         /* foo     */
730         reqsize = cd->Length;
731         ins_str = cd->Buffer;
732         if (cd->Buffer[1] != ':')
733         {
734             ptr = skip_unc_prefix( cd->Buffer );
735             mark = ptr - cd->Buffer;
736         }
737         else mark = 3;
738         break;
739
740     case ABSOLUTE_PATH:         /* \xxx    */
741         if (name[0] == '/')  /* may be a Unix path */
742         {
743             const WCHAR *ptr = name;
744             int drive = find_drive_rootW( &ptr );
745             if (drive != -1)
746             {
747                 reqsize = 3 * sizeof(WCHAR);
748                 tmp[0] = 'A' + drive;
749                 tmp[1] = ':';
750                 tmp[2] = '\\';
751                 ins_str = tmp;
752                 mark = 3;
753                 dep = ptr - name;
754                 break;
755             }
756         }
757         if (cd->Buffer[1] == ':')
758         {
759             reqsize = 2 * sizeof(WCHAR);
760             tmp[0] = cd->Buffer[0];
761             tmp[1] = ':';
762             ins_str = tmp;
763             mark = 3;
764         }
765         else
766         {
767             ptr = skip_unc_prefix( cd->Buffer );
768             reqsize = (ptr - cd->Buffer) * sizeof(WCHAR);
769             mark = reqsize / sizeof(WCHAR);
770             ins_str = cd->Buffer;
771         }
772         break;
773
774     case UNC_DOT_PATH:         /* \\.     */
775         reqsize = 4 * sizeof(WCHAR);
776         dep = 3;
777         tmp[0] = '\\';
778         tmp[1] = '\\';
779         tmp[2] = '.';
780         tmp[3] = '\\';
781         ins_str = tmp;
782         mark = 4;
783         break;
784
785     case INVALID_PATH:
786         goto done;
787     }
788
789     /* enough space ? */
790     deplen = strlenW(name + dep) * sizeof(WCHAR);
791     if (reqsize + deplen + sizeof(WCHAR) > size)
792     {
793         /* not enough space, return need size (including terminating '\0') */
794         reqsize += deplen + sizeof(WCHAR);
795         goto done;
796     }
797
798     memmove(buffer + reqsize / sizeof(WCHAR), name + dep, deplen + sizeof(WCHAR));
799     if (reqsize) memcpy(buffer, ins_str, reqsize);
800     reqsize += deplen;
801
802     if (ins_str != tmp && ins_str != cd->Buffer)
803         RtlFreeHeap(GetProcessHeap(), 0, ins_str);
804
805     collapse_path( buffer, mark );
806     reqsize = strlenW(buffer) * sizeof(WCHAR);
807
808 done:
809     RtlReleasePebLock();
810     return reqsize;
811 }
812
813 /******************************************************************
814  *              RtlGetFullPathName_U  (NTDLL.@)
815  *
816  * Returns the number of bytes written to buffer (not including the
817  * terminating NULL) if the function succeeds, or the required number of bytes
818  * (including the terminating NULL) if the buffer is too small.
819  *
820  * file_part will point to the filename part inside buffer (except if we use
821  * DOS device name, in which case file_in_buf is NULL)
822  *
823  */
824 DWORD WINAPI RtlGetFullPathName_U(const WCHAR* name, ULONG size, WCHAR* buffer,
825                                   WCHAR** file_part)
826 {
827     WCHAR*      ptr;
828     DWORD       dosdev;
829     DWORD       reqsize;
830
831     TRACE("(%s %u %p %p)\n", debugstr_w(name), size, buffer, file_part);
832
833     if (!name || !*name) return 0;
834
835     if (file_part) *file_part = NULL;
836
837     /* check for DOS device name */
838     dosdev = RtlIsDosDeviceName_U(name);
839     if (dosdev)
840     {
841         DWORD   offset = HIWORD(dosdev) / sizeof(WCHAR); /* get it in WCHARs, not bytes */
842         DWORD   sz = LOWORD(dosdev); /* in bytes */
843
844         if (8 + sz + 2 > size) return sz + 10;
845         strcpyW(buffer, DeviceRootW);
846         memmove(buffer + 4, name + offset, sz);
847         buffer[4 + sz / sizeof(WCHAR)] = '\0';
848         /* file_part isn't set in this case */
849         return sz + 8;
850     }
851
852     reqsize = get_full_path_helper(name, buffer, size);
853     if (!reqsize) return 0;
854     if (reqsize > size)
855     {
856         LPWSTR tmp = RtlAllocateHeap(GetProcessHeap(), 0, reqsize);
857         reqsize = get_full_path_helper(name, tmp, reqsize);
858         if (reqsize > size)  /* it may have worked the second time */
859         {
860             RtlFreeHeap(GetProcessHeap(), 0, tmp);
861             return reqsize + sizeof(WCHAR);
862         }
863         memcpy( buffer, tmp, reqsize + sizeof(WCHAR) );
864         RtlFreeHeap(GetProcessHeap(), 0, tmp);
865     }
866
867     /* find file part */
868     if (file_part && (ptr = strrchrW(buffer, '\\')) != NULL && ptr >= buffer + 2 && *++ptr)
869         *file_part = ptr;
870     return reqsize;
871 }
872
873 /*************************************************************************
874  * RtlGetLongestNtPathLength    [NTDLL.@]
875  *
876  * Get the longest allowed path length
877  *
878  * PARAMS
879  *  None.
880  *
881  * RETURNS
882  *  The longest allowed path length (277 characters under Win2k).
883  */
884 DWORD WINAPI RtlGetLongestNtPathLength(void)
885 {
886     return MAX_NT_PATH_LENGTH;
887 }
888
889 /******************************************************************
890  *             RtlIsNameLegalDOS8Dot3   (NTDLL.@)
891  *
892  * Returns TRUE iff unicode is a valid DOS (8+3) name.
893  * If the name is valid, oem gets filled with the corresponding OEM string
894  * spaces is set to TRUE if unicode contains spaces
895  */
896 BOOLEAN WINAPI RtlIsNameLegalDOS8Dot3( const UNICODE_STRING *unicode,
897                                        OEM_STRING *oem, BOOLEAN *spaces )
898 {
899     static const char illegal[] = "*?<>|\"+=,;[]:/\\\345";
900     int dot = -1;
901     int i;
902     char buffer[12];
903     OEM_STRING oem_str;
904     BOOLEAN got_space = FALSE;
905
906     if (!oem)
907     {
908         oem_str.Length = sizeof(buffer);
909         oem_str.MaximumLength = sizeof(buffer);
910         oem_str.Buffer = buffer;
911         oem = &oem_str;
912     }
913     if (RtlUpcaseUnicodeStringToCountedOemString( oem, unicode, FALSE ) != STATUS_SUCCESS)
914         return FALSE;
915
916     if (oem->Length > 12) return FALSE;
917
918     /* a starting . is invalid, except for . and .. */
919     if (oem->Buffer[0] == '.')
920     {
921         if (oem->Length != 1 && (oem->Length != 2 || oem->Buffer[1] != '.')) return FALSE;
922         if (spaces) *spaces = FALSE;
923         return TRUE;
924     }
925
926     for (i = 0; i < oem->Length; i++)
927     {
928         switch (oem->Buffer[i])
929         {
930         case ' ':
931             /* leading/trailing spaces not allowed */
932             if (!i || i == oem->Length-1 || oem->Buffer[i+1] == '.') return FALSE;
933             got_space = TRUE;
934             break;
935         case '.':
936             if (dot != -1) return FALSE;
937             dot = i;
938             break;
939         default:
940             if (strchr(illegal, oem->Buffer[i])) return FALSE;
941             break;
942         }
943     }
944     /* check file part is shorter than 8, extension shorter than 3
945      * dot cannot be last in string
946      */
947     if (dot == -1)
948     {
949         if (oem->Length > 8) return FALSE;
950     }
951     else
952     {
953         if (dot > 8 || (oem->Length - dot > 4) || dot == oem->Length - 1) return FALSE;
954     }
955     if (spaces) *spaces = got_space;
956     return TRUE;
957 }
958
959 /******************************************************************
960  *              RtlGetCurrentDirectory_U (NTDLL.@)
961  *
962  */
963 NTSTATUS WINAPI RtlGetCurrentDirectory_U(ULONG buflen, LPWSTR buf)
964 {
965     UNICODE_STRING*     us;
966     ULONG               len;
967
968     TRACE("(%u %p)\n", buflen, buf);
969
970     RtlAcquirePebLock();
971
972     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
973         us = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
974     else
975         us = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
976
977     len = us->Length / sizeof(WCHAR);
978     if (us->Buffer[len - 1] == '\\' && us->Buffer[len - 2] != ':')
979         len--;
980
981     if (buflen / sizeof(WCHAR) > len)
982     {
983         memcpy(buf, us->Buffer, len * sizeof(WCHAR));
984         buf[len] = '\0';
985     }
986     else
987     {
988         len++;
989     }
990
991     RtlReleasePebLock();
992
993     return len * sizeof(WCHAR);
994 }
995
996 /******************************************************************
997  *              RtlSetCurrentDirectory_U (NTDLL.@)
998  *
999  */
1000 NTSTATUS WINAPI RtlSetCurrentDirectory_U(const UNICODE_STRING* dir)
1001 {
1002     FILE_FS_DEVICE_INFORMATION device_info;
1003     OBJECT_ATTRIBUTES attr;
1004     UNICODE_STRING newdir;
1005     IO_STATUS_BLOCK io;
1006     CURDIR *curdir;
1007     HANDLE handle;
1008     NTSTATUS nts;
1009     ULONG size;
1010     PWSTR ptr;
1011
1012     newdir.Buffer = NULL;
1013
1014     RtlAcquirePebLock();
1015
1016     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
1017         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
1018     else
1019         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
1020
1021     if (!RtlDosPathNameToNtPathName_U( dir->Buffer, &newdir, NULL, NULL ))
1022     {
1023         nts = STATUS_OBJECT_NAME_INVALID;
1024         goto out;
1025     }
1026
1027     attr.Length = sizeof(attr);
1028     attr.RootDirectory = 0;
1029     attr.Attributes = OBJ_CASE_INSENSITIVE;
1030     attr.ObjectName = &newdir;
1031     attr.SecurityDescriptor = NULL;
1032     attr.SecurityQualityOfService = NULL;
1033
1034     nts = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
1035     if (nts != STATUS_SUCCESS) goto out;
1036
1037     /* don't keep the directory handle open on removable media */
1038     if (!NtQueryVolumeInformationFile( handle, &io, &device_info,
1039                                        sizeof(device_info), FileFsDeviceInformation ) &&
1040         (device_info.Characteristics & FILE_REMOVABLE_MEDIA))
1041     {
1042         NtClose( handle );
1043         handle = 0;
1044     }
1045
1046     if (curdir->Handle) NtClose( curdir->Handle );
1047     curdir->Handle = handle;
1048
1049     /* append trailing \ if missing */
1050     size = newdir.Length / sizeof(WCHAR);
1051     ptr = newdir.Buffer;
1052     ptr += 4;  /* skip \??\ prefix */
1053     size -= 4;
1054     if (size && ptr[size - 1] != '\\') ptr[size++] = '\\';
1055
1056     memcpy( curdir->DosPath.Buffer, ptr, size * sizeof(WCHAR));
1057     curdir->DosPath.Buffer[size] = 0;
1058     curdir->DosPath.Length = size * sizeof(WCHAR);
1059
1060     TRACE( "curdir now %s %p\n", debugstr_w(curdir->DosPath.Buffer), curdir->Handle );
1061
1062  out:
1063     RtlFreeUnicodeString( &newdir );
1064     RtlReleasePebLock();
1065     return nts;
1066 }
1067
1068
1069 /******************************************************************
1070  *           wine_unix_to_nt_file_name  (NTDLL.@) Not a Windows API
1071  */
1072 NTSTATUS wine_unix_to_nt_file_name( const ANSI_STRING *name, UNICODE_STRING *nt )
1073 {
1074     static const WCHAR prefixW[] = {'\\','?','?','\\','a',':','\\'};
1075     unsigned int lenW, lenA = name->Length;
1076     const char *path = name->Buffer;
1077     char *cwd;
1078     WCHAR *p;
1079     NTSTATUS status;
1080     int drive;
1081
1082     if (!lenA || path[0] != '/')
1083     {
1084         char *newcwd, *end;
1085         size_t size;
1086
1087         if ((status = DIR_get_unix_cwd( &cwd )) != STATUS_SUCCESS) return status;
1088
1089         size = strlen(cwd) + lenA + 1;
1090         if (!(newcwd = RtlReAllocateHeap( GetProcessHeap(), 0, cwd, size )))
1091         {
1092             status = STATUS_NO_MEMORY;
1093             goto done;
1094         }
1095         cwd = newcwd;
1096         end = cwd + strlen(cwd);
1097         if (end > cwd && end[-1] != '/') *end++ = '/';
1098         memcpy( end, path, lenA );
1099         lenA += end - cwd;
1100         path = cwd;
1101
1102         status = find_drive_rootA( &path, lenA, &drive );
1103         lenA -= (path - cwd);
1104     }
1105     else
1106     {
1107         cwd = NULL;
1108         status = find_drive_rootA( &path, lenA, &drive );
1109         lenA -= (path - name->Buffer);
1110     }
1111
1112     if (status != STATUS_SUCCESS) goto done;
1113     while (lenA && path[0] == '/') { lenA--; path++; }
1114
1115     lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
1116     if (!(nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1117                                         (lenW + 1) * sizeof(WCHAR) + sizeof(prefixW) )))
1118     {
1119         status = STATUS_NO_MEMORY;
1120         goto done;
1121     }
1122
1123     memcpy( nt->Buffer, prefixW, sizeof(prefixW) );
1124     nt->Buffer[4] += drive;
1125     ntdll_umbstowcs( 0, path, lenA, nt->Buffer + sizeof(prefixW)/sizeof(WCHAR), lenW );
1126     lenW += sizeof(prefixW)/sizeof(WCHAR);
1127     nt->Buffer[lenW] = 0;
1128     nt->Length = lenW * sizeof(WCHAR);
1129     nt->MaximumLength = nt->Length + sizeof(WCHAR);
1130     for (p = nt->Buffer + sizeof(prefixW)/sizeof(WCHAR); *p; p++) if (*p == '/') *p = '\\';
1131
1132 done:
1133     RtlFreeHeap( GetProcessHeap(), 0, cwd );
1134     return status;
1135 }