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