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