ws2_32: Only enable FD_WRITE on short sends.
[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     default:
291         break;
292     }
293
294     end = dos_name + strlenW(dos_name) - 1;
295     while (end >= dos_name && *end == ':') end--;  /* remove all trailing ':' */
296
297     /* find start of file name */
298     for (start = end; start >= dos_name; start--)
299     {
300         if (IS_SEPARATOR(start[0])) break;
301         /* check for ':' but ignore if before extension (for things like NUL:.txt) */
302         if (start[0] == ':' && start[1] != '.') break;
303     }
304     start++;
305
306     /* remove extension */
307     if ((p = strchrW( start, '.' )))
308     {
309         end = p - 1;
310         if (end >= dos_name && *end == ':') end--;  /* remove trailing ':' before extension */
311     }
312     /* remove trailing spaces */
313     while (end >= dos_name && *end == ' ') end--;
314
315     /* now we have a potential device name between start and end, check it */
316     switch(end - start + 1)
317     {
318     case 3:
319         if (strncmpiW( start, auxW, 3 ) &&
320             strncmpiW( start, conW, 3 ) &&
321             strncmpiW( start, nulW, 3 ) &&
322             strncmpiW( start, prnW, 3 )) break;
323         return MAKELONG( 3 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
324     case 4:
325         if (strncmpiW( start, comW, 3 ) && strncmpiW( start, lptW, 3 )) break;
326         if (*end <= '0' || *end > '9') break;
327         return MAKELONG( 4 * sizeof(WCHAR), (start - dos_name) * sizeof(WCHAR) );
328     default:  /* can't match anything */
329         break;
330     }
331     return 0;
332 }
333
334
335 /**************************************************************************
336  *                 RtlDosPathNameToNtPathName_U         [NTDLL.@]
337  *
338  * dos_path: a DOS path name (fully qualified or not)
339  * ntpath:   pointer to a UNICODE_STRING to hold the converted
340  *           path name
341  * file_part:will point (in ntpath) to the file part in the path
342  * cd:       directory reference (optional)
343  *
344  * FIXME:
345  *      + fill the cd structure
346  */
347 BOOLEAN  WINAPI RtlDosPathNameToNtPathName_U(PCWSTR dos_path,
348                                              PUNICODE_STRING ntpath,
349                                              PWSTR* file_part,
350                                              CURDIR* cd)
351 {
352     static const WCHAR LongFileNamePfxW[4] = {'\\','\\','?','\\'};
353     ULONG sz, offset;
354     WCHAR local[MAX_PATH];
355     LPWSTR ptr;
356
357     TRACE("(%s,%p,%p,%p)\n",
358           debugstr_w(dos_path), ntpath, file_part, cd);
359
360     if (cd)
361     {
362         FIXME("Unsupported parameter\n");
363         memset(cd, 0, sizeof(*cd));
364     }
365
366     if (!dos_path || !*dos_path) return FALSE;
367
368     if (!strncmpW(dos_path, LongFileNamePfxW, 4))
369     {
370         ntpath->Length = strlenW(dos_path) * sizeof(WCHAR);
371         ntpath->MaximumLength = ntpath->Length + sizeof(WCHAR);
372         ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
373         if (!ntpath->Buffer) return FALSE;
374         memcpy( ntpath->Buffer, dos_path, ntpath->MaximumLength );
375         ntpath->Buffer[1] = '?';  /* change \\?\ to \??\ */
376         if (file_part)
377         {
378             if ((ptr = strrchrW( ntpath->Buffer, '\\' )) && ptr[1]) *file_part = ptr + 1;
379             else *file_part = NULL;
380         }
381         return TRUE;
382     }
383
384     ptr = local;
385     sz = RtlGetFullPathName_U(dos_path, sizeof(local), ptr, file_part);
386     if (sz == 0) return FALSE;
387     if (sz > sizeof(local))
388     {
389         if (!(ptr = RtlAllocateHeap(GetProcessHeap(), 0, sz))) return FALSE;
390         sz = RtlGetFullPathName_U(dos_path, sz, ptr, file_part);
391     }
392
393     ntpath->MaximumLength = sz + (4 /* unc\ */ + 4 /* \??\ */) * sizeof(WCHAR);
394     ntpath->Buffer = RtlAllocateHeap(GetProcessHeap(), 0, ntpath->MaximumLength);
395     if (!ntpath->Buffer)
396     {
397         if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
398         return FALSE;
399     }
400
401     strcpyW(ntpath->Buffer, NTDosPrefixW);
402     switch (RtlDetermineDosPathNameType_U(ptr))
403     {
404     case UNC_PATH: /* \\foo */
405         offset = 2;
406         strcatW(ntpath->Buffer, UncPfxW);
407         break;
408     case DEVICE_PATH: /* \\.\foo */
409         offset = 4;
410         break;
411     default:
412         offset = 0;
413         break;
414     }
415
416     strcatW(ntpath->Buffer, ptr + offset);
417     ntpath->Length = strlenW(ntpath->Buffer) * sizeof(WCHAR);
418
419     if (file_part && *file_part)
420         *file_part = ntpath->Buffer + ntpath->Length / sizeof(WCHAR) - strlenW(*file_part);
421
422     /* FIXME: cd filling */
423
424     if (ptr != local) RtlFreeHeap(GetProcessHeap(), 0, ptr);
425     return TRUE;
426 }
427
428 /******************************************************************
429  *              RtlDosSearchPath_U
430  *
431  * Searches a file of name 'name' into a ';' separated list of paths
432  * (stored in paths)
433  * Doesn't seem to search elsewhere than the paths list
434  * Stores the result in buffer (file_part will point to the position
435  * of the file name in the buffer)
436  * FIXME:
437  * - how long shall the paths be ??? (MAX_PATH or larger with \\?\ constructs ???)
438  */
439 ULONG WINAPI RtlDosSearchPath_U(LPCWSTR paths, LPCWSTR search, LPCWSTR ext, 
440                                 ULONG buffer_size, LPWSTR buffer, 
441                                 LPWSTR* file_part)
442 {
443     DOS_PATHNAME_TYPE type = RtlDetermineDosPathNameType_U(search);
444     ULONG len = 0;
445
446     if (type == RELATIVE_PATH)
447     {
448         ULONG allocated = 0, needed, filelen;
449         WCHAR *name = NULL;
450
451         filelen = 1 /* for \ */ + strlenW(search) + 1 /* \0 */;
452
453         /* Windows only checks for '.' without worrying about path components */
454         if (strchrW( search, '.' )) ext = NULL;
455         if (ext != NULL) filelen += strlenW(ext);
456
457         while (*paths)
458         {
459             LPCWSTR ptr;
460
461             for (needed = 0, ptr = paths; *ptr != 0 && *ptr++ != ';'; needed++);
462             if (needed + filelen > allocated)
463             {
464                 if (!name) name = RtlAllocateHeap(GetProcessHeap(), 0,
465                                                   (needed + filelen) * sizeof(WCHAR));
466                 else
467                 {
468                     WCHAR *newname = RtlReAllocateHeap(GetProcessHeap(), 0, name,
469                                                        (needed + filelen) * sizeof(WCHAR));
470                     if (!newname) RtlFreeHeap(GetProcessHeap(), 0, name);
471                     name = newname;
472                 }
473                 if (!name) return 0;
474                 allocated = needed + filelen;
475             }
476             memmove(name, paths, needed * sizeof(WCHAR));
477             /* append '\\' if none is present */
478             if (needed > 0 && name[needed - 1] != '\\') name[needed++] = '\\';
479             strcpyW(&name[needed], search);
480             if (ext) strcatW(&name[needed], ext);
481             if (RtlDoesFileExists_U(name))
482             {
483                 len = RtlGetFullPathName_U(name, buffer_size, buffer, file_part);
484                 break;
485             }
486             paths = ptr;
487         }
488         RtlFreeHeap(GetProcessHeap(), 0, name);
489     }
490     else if (RtlDoesFileExists_U(search))
491     {
492         len = RtlGetFullPathName_U(search, buffer_size, buffer, file_part);
493     }
494
495     return len;
496 }
497
498
499 /******************************************************************
500  *              collapse_path
501  *
502  * Helper for RtlGetFullPathName_U.
503  * Get rid of . and .. components in the path.
504  */
505 static inline void collapse_path( WCHAR *path, UINT mark )
506 {
507     WCHAR *p, *next;
508
509     /* convert every / into a \ */
510     for (p = path; *p; p++) if (*p == '/') *p = '\\';
511
512     /* collapse duplicate backslashes */
513     next = path + max( 1, mark );
514     for (p = next; *p; p++) if (*p != '\\' || next[-1] != '\\') *next++ = *p;
515     *next = 0;
516
517     p = path + mark;
518     while (*p)
519     {
520         if (*p == '.')
521         {
522             switch(p[1])
523             {
524             case '\\': /* .\ component */
525                 next = p + 2;
526                 memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
527                 continue;
528             case 0:  /* final . */
529                 if (p > path + mark) p--;
530                 *p = 0;
531                 continue;
532             case '.':
533                 if (p[2] == '\\')  /* ..\ component */
534                 {
535                     next = p + 3;
536                     if (p > path + mark)
537                     {
538                         p--;
539                         while (p > path + mark && p[-1] != '\\') p--;
540                     }
541                     memmove( p, next, (strlenW(next) + 1) * sizeof(WCHAR) );
542                     continue;
543                 }
544                 else if (!p[2])  /* final .. */
545                 {
546                     if (p > path + mark)
547                     {
548                         p--;
549                         while (p > path + mark && p[-1] != '\\') p--;
550                         if (p > path + mark) p--;
551                     }
552                     *p = 0;
553                     continue;
554                 }
555                 break;
556             }
557         }
558         /* skip to the next component */
559         while (*p && *p != '\\') p++;
560         if (*p == '\\')
561         {
562             /* remove last dot in previous dir name */
563             if (p > path + mark && p[-1] == '.') memmove( p-1, p, (strlenW(p) + 1) * sizeof(WCHAR) );
564             else p++;
565         }
566     }
567
568     /* remove trailing spaces and dots (yes, Windows really does that, don't ask) */
569     while (p > path + mark && (p[-1] == ' ' || p[-1] == '.')) p--;
570     *p = 0;
571 }
572
573
574 /******************************************************************
575  *              skip_unc_prefix
576  *
577  * Skip the \\share\dir\ part of a file name. Helper for RtlGetFullPathName_U.
578  */
579 static const WCHAR *skip_unc_prefix( const WCHAR *ptr )
580 {
581     ptr += 2;
582     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* share name */
583     while (IS_SEPARATOR(*ptr)) ptr++;
584     while (*ptr && !IS_SEPARATOR(*ptr)) ptr++;  /* dir name */
585     while (IS_SEPARATOR(*ptr)) ptr++;
586     return ptr;
587 }
588
589
590 /******************************************************************
591  *              get_full_path_helper
592  *
593  * Helper for RtlGetFullPathName_U
594  * Note: name and buffer are allowed to point to the same memory spot
595  */
596 static ULONG get_full_path_helper(LPCWSTR name, LPWSTR buffer, ULONG size)
597 {
598     ULONG                       reqsize = 0, mark = 0, dep = 0, deplen;
599     LPWSTR                      ins_str = NULL;
600     LPCWSTR                     ptr;
601     const UNICODE_STRING*       cd;
602     WCHAR                       tmp[4];
603
604     /* return error if name only consists of spaces */
605     for (ptr = name; *ptr; ptr++) if (*ptr != ' ') break;
606     if (!*ptr) return 0;
607
608     RtlAcquirePebLock();
609
610     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
611         cd = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
612     else
613         cd = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
614
615     switch (RtlDetermineDosPathNameType_U(name))
616     {
617     case UNC_PATH:              /* \\foo   */
618         ptr = skip_unc_prefix( name );
619         mark = (ptr - name);
620         break;
621
622     case DEVICE_PATH:           /* \\.\foo */
623         mark = 4;
624         break;
625
626     case ABSOLUTE_DRIVE_PATH:   /* c:\foo  */
627         reqsize = sizeof(WCHAR);
628         tmp[0] = toupperW(name[0]);
629         ins_str = tmp;
630         dep = 1;
631         mark = 3;
632         break;
633
634     case RELATIVE_DRIVE_PATH:   /* c:foo   */
635         dep = 2;
636         if (toupperW(name[0]) != toupperW(cd->Buffer[0]) || cd->Buffer[1] != ':')
637         {
638             UNICODE_STRING      var, val;
639
640             tmp[0] = '=';
641             tmp[1] = name[0];
642             tmp[2] = ':';
643             tmp[3] = '\0';
644             var.Length = 3 * sizeof(WCHAR);
645             var.MaximumLength = 4 * sizeof(WCHAR);
646             var.Buffer = tmp;
647             val.Length = 0;
648             val.MaximumLength = size;
649             val.Buffer = RtlAllocateHeap(GetProcessHeap(), 0, size);
650
651             switch (RtlQueryEnvironmentVariable_U(NULL, &var, &val))
652             {
653             case STATUS_SUCCESS:
654                 /* FIXME: Win2k seems to check that the environment variable actually points 
655                  * to an existing directory. If not, root of the drive is used
656                  * (this seems also to be the only spot in RtlGetFullPathName that the 
657                  * existence of a part of a path is checked)
658                  */
659                 /* fall thru */
660             case STATUS_BUFFER_TOO_SMALL:
661                 reqsize = val.Length + sizeof(WCHAR); /* append trailing '\\' */
662                 val.Buffer[val.Length / sizeof(WCHAR)] = '\\';
663                 ins_str = val.Buffer;
664                 break;
665             case STATUS_VARIABLE_NOT_FOUND:
666                 reqsize = 3 * sizeof(WCHAR);
667                 tmp[0] = name[0];
668                 tmp[1] = ':';
669                 tmp[2] = '\\';
670                 ins_str = tmp;
671                 break;
672             default:
673                 ERR("Unsupported status code\n");
674                 break;
675             }
676             mark = 3;
677             break;
678         }
679         /* fall through */
680
681     case RELATIVE_PATH:         /* foo     */
682         reqsize = cd->Length;
683         ins_str = cd->Buffer;
684         if (cd->Buffer[1] != ':')
685         {
686             ptr = skip_unc_prefix( cd->Buffer );
687             mark = ptr - cd->Buffer;
688         }
689         else mark = 3;
690         break;
691
692     case ABSOLUTE_PATH:         /* \xxx    */
693         if (name[0] == '/')  /* may be a Unix path */
694         {
695             const WCHAR *ptr = name;
696             int drive = find_drive_rootW( &ptr );
697             if (drive != -1)
698             {
699                 reqsize = 3 * sizeof(WCHAR);
700                 tmp[0] = 'A' + drive;
701                 tmp[1] = ':';
702                 tmp[2] = '\\';
703                 ins_str = tmp;
704                 mark = 3;
705                 dep = ptr - name;
706                 break;
707             }
708         }
709         if (cd->Buffer[1] == ':')
710         {
711             reqsize = 2 * sizeof(WCHAR);
712             tmp[0] = cd->Buffer[0];
713             tmp[1] = ':';
714             ins_str = tmp;
715             mark = 3;
716         }
717         else
718         {
719             ptr = skip_unc_prefix( cd->Buffer );
720             reqsize = (ptr - cd->Buffer) * sizeof(WCHAR);
721             mark = reqsize / sizeof(WCHAR);
722             ins_str = cd->Buffer;
723         }
724         break;
725
726     case UNC_DOT_PATH:         /* \\.     */
727         reqsize = 4 * sizeof(WCHAR);
728         dep = 3;
729         tmp[0] = '\\';
730         tmp[1] = '\\';
731         tmp[2] = '.';
732         tmp[3] = '\\';
733         ins_str = tmp;
734         mark = 4;
735         break;
736
737     case INVALID_PATH:
738         goto done;
739     }
740
741     /* enough space ? */
742     deplen = strlenW(name + dep) * sizeof(WCHAR);
743     if (reqsize + deplen + sizeof(WCHAR) > size)
744     {
745         /* not enough space, return need size (including terminating '\0') */
746         reqsize += deplen + sizeof(WCHAR);
747         goto done;
748     }
749
750     memmove(buffer + reqsize / sizeof(WCHAR), name + dep, deplen + sizeof(WCHAR));
751     if (reqsize) memcpy(buffer, ins_str, reqsize);
752     reqsize += deplen;
753
754     if (ins_str != tmp && ins_str != cd->Buffer)
755         RtlFreeHeap(GetProcessHeap(), 0, ins_str);
756
757     collapse_path( buffer, mark );
758     reqsize = strlenW(buffer) * sizeof(WCHAR);
759
760 done:
761     RtlReleasePebLock();
762     return reqsize;
763 }
764
765 /******************************************************************
766  *              RtlGetFullPathName_U  (NTDLL.@)
767  *
768  * Returns the number of bytes written to buffer (not including the
769  * terminating NULL) if the function succeeds, or the required number of bytes
770  * (including the terminating NULL) if the buffer is too small.
771  *
772  * file_part will point to the filename part inside buffer (except if we use
773  * DOS device name, in which case file_in_buf is NULL)
774  *
775  */
776 DWORD WINAPI RtlGetFullPathName_U(const WCHAR* name, ULONG size, WCHAR* buffer,
777                                   WCHAR** file_part)
778 {
779     WCHAR*      ptr;
780     DWORD       dosdev;
781     DWORD       reqsize;
782
783     TRACE("(%s %u %p %p)\n", debugstr_w(name), size, buffer, file_part);
784
785     if (!name || !*name) return 0;
786
787     if (file_part) *file_part = NULL;
788
789     /* check for DOS device name */
790     dosdev = RtlIsDosDeviceName_U(name);
791     if (dosdev)
792     {
793         DWORD   offset = HIWORD(dosdev) / sizeof(WCHAR); /* get it in WCHARs, not bytes */
794         DWORD   sz = LOWORD(dosdev); /* in bytes */
795
796         if (8 + sz + 2 > size) return sz + 10;
797         strcpyW(buffer, DeviceRootW);
798         memmove(buffer + 4, name + offset, sz);
799         buffer[4 + sz / sizeof(WCHAR)] = '\0';
800         /* file_part isn't set in this case */
801         return sz + 8;
802     }
803
804     reqsize = get_full_path_helper(name, buffer, size);
805     if (!reqsize) return 0;
806     if (reqsize > size)
807     {
808         LPWSTR tmp = RtlAllocateHeap(GetProcessHeap(), 0, reqsize);
809         reqsize = get_full_path_helper(name, tmp, reqsize);
810         if (reqsize + sizeof(WCHAR) > size)  /* it may have worked the second time */
811         {
812             RtlFreeHeap(GetProcessHeap(), 0, tmp);
813             return reqsize + sizeof(WCHAR);
814         }
815         memcpy( buffer, tmp, reqsize + sizeof(WCHAR) );
816         RtlFreeHeap(GetProcessHeap(), 0, tmp);
817     }
818
819     /* find file part */
820     if (file_part && (ptr = strrchrW(buffer, '\\')) != NULL && ptr >= buffer + 2 && *++ptr)
821         *file_part = ptr;
822     return reqsize;
823 }
824
825 /*************************************************************************
826  * RtlGetLongestNtPathLength    [NTDLL.@]
827  *
828  * Get the longest allowed path length
829  *
830  * PARAMS
831  *  None.
832  *
833  * RETURNS
834  *  The longest allowed path length (277 characters under Win2k).
835  */
836 DWORD WINAPI RtlGetLongestNtPathLength(void)
837 {
838     return MAX_NT_PATH_LENGTH;
839 }
840
841 /******************************************************************
842  *             RtlIsNameLegalDOS8Dot3   (NTDLL.@)
843  *
844  * Returns TRUE iff unicode is a valid DOS (8+3) name.
845  * If the name is valid, oem gets filled with the corresponding OEM string
846  * spaces is set to TRUE if unicode contains spaces
847  */
848 BOOLEAN WINAPI RtlIsNameLegalDOS8Dot3( const UNICODE_STRING *unicode,
849                                        OEM_STRING *oem, BOOLEAN *spaces )
850 {
851     static const char illegal[] = "*?<>|\"+=,;[]:/\\\345";
852     int dot = -1;
853     int i;
854     char buffer[12];
855     OEM_STRING oem_str;
856     BOOLEAN got_space = FALSE;
857
858     if (!oem)
859     {
860         oem_str.Length = sizeof(buffer);
861         oem_str.MaximumLength = sizeof(buffer);
862         oem_str.Buffer = buffer;
863         oem = &oem_str;
864     }
865     if (RtlUpcaseUnicodeStringToCountedOemString( oem, unicode, FALSE ) != STATUS_SUCCESS)
866         return FALSE;
867
868     if (oem->Length > 12) return FALSE;
869
870     /* a starting . is invalid, except for . and .. */
871     if (oem->Buffer[0] == '.')
872     {
873         if (oem->Length != 1 && (oem->Length != 2 || oem->Buffer[1] != '.')) return FALSE;
874         if (spaces) *spaces = FALSE;
875         return TRUE;
876     }
877
878     for (i = 0; i < oem->Length; i++)
879     {
880         switch (oem->Buffer[i])
881         {
882         case ' ':
883             /* leading/trailing spaces not allowed */
884             if (!i || i == oem->Length-1 || oem->Buffer[i+1] == '.') return FALSE;
885             got_space = TRUE;
886             break;
887         case '.':
888             if (dot != -1) return FALSE;
889             dot = i;
890             break;
891         default:
892             if (strchr(illegal, oem->Buffer[i])) return FALSE;
893             break;
894         }
895     }
896     /* check file part is shorter than 8, extension shorter than 3
897      * dot cannot be last in string
898      */
899     if (dot == -1)
900     {
901         if (oem->Length > 8) return FALSE;
902     }
903     else
904     {
905         if (dot > 8 || (oem->Length - dot > 4) || dot == oem->Length - 1) return FALSE;
906     }
907     if (spaces) *spaces = got_space;
908     return TRUE;
909 }
910
911 /******************************************************************
912  *              RtlGetCurrentDirectory_U (NTDLL.@)
913  *
914  */
915 NTSTATUS WINAPI RtlGetCurrentDirectory_U(ULONG buflen, LPWSTR buf)
916 {
917     UNICODE_STRING*     us;
918     ULONG               len;
919
920     TRACE("(%u %p)\n", buflen, buf);
921
922     RtlAcquirePebLock();
923
924     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
925         us = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir.DosPath;
926     else
927         us = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory.DosPath;
928
929     len = us->Length / sizeof(WCHAR);
930     if (us->Buffer[len - 1] == '\\' && us->Buffer[len - 2] != ':')
931         len--;
932
933     if (buflen / sizeof(WCHAR) > len)
934     {
935         memcpy(buf, us->Buffer, len * sizeof(WCHAR));
936         buf[len] = '\0';
937     }
938     else
939     {
940         len++;
941     }
942
943     RtlReleasePebLock();
944
945     return len * sizeof(WCHAR);
946 }
947
948 /******************************************************************
949  *              RtlSetCurrentDirectory_U (NTDLL.@)
950  *
951  */
952 NTSTATUS WINAPI RtlSetCurrentDirectory_U(const UNICODE_STRING* dir)
953 {
954     FILE_FS_DEVICE_INFORMATION device_info;
955     OBJECT_ATTRIBUTES attr;
956     UNICODE_STRING newdir;
957     IO_STATUS_BLOCK io;
958     CURDIR *curdir;
959     HANDLE handle;
960     NTSTATUS nts;
961     ULONG size;
962     PWSTR ptr;
963
964     newdir.Buffer = NULL;
965
966     RtlAcquirePebLock();
967
968     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
969         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
970     else
971         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
972
973     if (!RtlDosPathNameToNtPathName_U( dir->Buffer, &newdir, NULL, NULL ))
974     {
975         nts = STATUS_OBJECT_NAME_INVALID;
976         goto out;
977     }
978
979     attr.Length = sizeof(attr);
980     attr.RootDirectory = 0;
981     attr.Attributes = OBJ_CASE_INSENSITIVE;
982     attr.ObjectName = &newdir;
983     attr.SecurityDescriptor = NULL;
984     attr.SecurityQualityOfService = NULL;
985
986     nts = NtOpenFile( &handle, 0, &attr, &io, 0, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
987     if (nts != STATUS_SUCCESS) goto out;
988
989     /* don't keep the directory handle open on removable media */
990     if (!NtQueryVolumeInformationFile( handle, &io, &device_info,
991                                        sizeof(device_info), FileFsDeviceInformation ) &&
992         (device_info.Characteristics & FILE_REMOVABLE_MEDIA))
993     {
994         NtClose( handle );
995         handle = 0;
996     }
997
998     if (curdir->Handle) NtClose( curdir->Handle );
999     curdir->Handle = handle;
1000
1001     /* append trailing \ if missing */
1002     size = newdir.Length / sizeof(WCHAR);
1003     ptr = newdir.Buffer;
1004     ptr += 4;  /* skip \??\ prefix */
1005     size -= 4;
1006     if (size && ptr[size - 1] != '\\') ptr[size++] = '\\';
1007
1008     memcpy( curdir->DosPath.Buffer, ptr, size * sizeof(WCHAR));
1009     curdir->DosPath.Buffer[size] = 0;
1010     curdir->DosPath.Length = size * sizeof(WCHAR);
1011
1012     TRACE( "curdir now %s %p\n", debugstr_w(curdir->DosPath.Buffer), curdir->Handle );
1013
1014  out:
1015     RtlFreeUnicodeString( &newdir );
1016     RtlReleasePebLock();
1017     return nts;
1018 }
1019
1020
1021 /******************************************************************
1022  *           wine_unix_to_nt_file_name  (NTDLL.@) Not a Windows API
1023  */
1024 NTSTATUS wine_unix_to_nt_file_name( const ANSI_STRING *name, UNICODE_STRING *nt )
1025 {
1026     static const WCHAR prefixW[] = {'\\','?','?','\\','A',':','\\'};
1027     unsigned int lenW, lenA = name->Length;
1028     const char *path = name->Buffer;
1029     char *cwd;
1030     WCHAR *p;
1031     NTSTATUS status;
1032     int drive;
1033
1034     if (!lenA || path[0] != '/')
1035     {
1036         char *newcwd, *end;
1037         size_t size;
1038
1039         if ((status = DIR_get_unix_cwd( &cwd )) != STATUS_SUCCESS) return status;
1040
1041         size = strlen(cwd) + lenA + 1;
1042         if (!(newcwd = RtlReAllocateHeap( GetProcessHeap(), 0, cwd, size )))
1043         {
1044             status = STATUS_NO_MEMORY;
1045             goto done;
1046         }
1047         cwd = newcwd;
1048         end = cwd + strlen(cwd);
1049         if (end > cwd && end[-1] != '/') *end++ = '/';
1050         memcpy( end, path, lenA );
1051         lenA += end - cwd;
1052         path = cwd;
1053
1054         status = find_drive_rootA( &path, lenA, &drive );
1055         lenA -= (path - cwd);
1056     }
1057     else
1058     {
1059         cwd = NULL;
1060         status = find_drive_rootA( &path, lenA, &drive );
1061         lenA -= (path - name->Buffer);
1062     }
1063
1064     if (status != STATUS_SUCCESS) goto done;
1065     while (lenA && path[0] == '/') { lenA--; path++; }
1066
1067     lenW = ntdll_umbstowcs( 0, path, lenA, NULL, 0 );
1068     if (!(nt->Buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1069                                         (lenW + 1) * sizeof(WCHAR) + sizeof(prefixW) )))
1070     {
1071         status = STATUS_NO_MEMORY;
1072         goto done;
1073     }
1074
1075     memcpy( nt->Buffer, prefixW, sizeof(prefixW) );
1076     nt->Buffer[4] += drive;
1077     ntdll_umbstowcs( 0, path, lenA, nt->Buffer + sizeof(prefixW)/sizeof(WCHAR), lenW );
1078     lenW += sizeof(prefixW)/sizeof(WCHAR);
1079     nt->Buffer[lenW] = 0;
1080     nt->Length = lenW * sizeof(WCHAR);
1081     nt->MaximumLength = nt->Length + sizeof(WCHAR);
1082     for (p = nt->Buffer + sizeof(prefixW)/sizeof(WCHAR); *p; p++) if (*p == '/') *p = '\\';
1083
1084 done:
1085     RtlFreeHeap( GetProcessHeap(), 0, cwd );
1086     return status;
1087 }