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