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