Reverse the order for deleting the items in resetcontent to correctly
[wine] / dlls / ntdll / directory.c
1 /*
2  * NTDLL directory functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 2003 Eric Pouech
6  * Copyright 1996, 2004 Alexandre Julliard
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <sys/types.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #ifdef HAVE_MNTENT_H
35 #include <mntent.h>
36 #endif
37 #include <sys/stat.h>
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
40 #endif
41 #ifdef HAVE_LINUX_IOCTL_H
42 #include <linux/ioctl.h>
43 #endif
44 #ifdef HAVE_SYS_PARAM_H
45 #include <sys/param.h>
46 #endif
47 #ifdef HAVE_SYS_MOUNT_H
48 #include <sys/mount.h>
49 #endif
50 #include <time.h>
51 #ifdef HAVE_UNISTD_H
52 # include <unistd.h>
53 #endif
54
55 #define NONAMELESSUNION
56 #define NONAMELESSSTRUCT
57 #include "windef.h"
58 #include "winbase.h"
59 #include "winnt.h"
60 #include "winreg.h"
61 #include "ntstatus.h"
62 #include "winternl.h"
63 #include "ntdll_misc.h"
64 #include "wine/unicode.h"
65 #include "wine/server.h"
66 #include "wine/library.h"
67 #include "wine/debug.h"
68
69 WINE_DEFAULT_DEBUG_CHANNEL(file);
70
71 /* just in case... */
72 #undef VFAT_IOCTL_READDIR_BOTH
73 #undef USE_GETDENTS
74
75 #ifdef linux
76
77 /* We want the real kernel dirent structure, not the libc one */
78 typedef struct
79 {
80     long d_ino;
81     long d_off;
82     unsigned short d_reclen;
83     char d_name[256];
84 } KERNEL_DIRENT;
85
86 /* Define the VFAT ioctl to get both short and long file names */
87 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
88
89 #ifndef O_DIRECTORY
90 # define O_DIRECTORY 0200000 /* must be directory */
91 #endif
92
93 #ifdef __i386__
94
95 typedef struct
96 {
97     ULONG64        d_ino;
98     LONG64         d_off;
99     unsigned short d_reclen;
100     unsigned char  d_type;
101     char           d_name[256];
102 } KERNEL_DIRENT64;
103
104 static inline int getdents64( int fd, KERNEL_DIRENT64 *de, unsigned int size )
105 {
106     int ret;
107     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
108              : "=a" (ret)
109              : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
110              : "memory" );
111     if (ret < 0)
112     {
113         errno = -ret;
114         ret = -1;
115     }
116     return ret;
117 }
118 #define USE_GETDENTS
119
120 #endif  /* i386 */
121
122 #endif  /* linux */
123
124 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
125 #define IS_SEPARATOR(ch)   ((ch) == '\\' || (ch) == '/')
126
127 #define INVALID_NT_CHARS   '*','?','<','>','|','"'
128 #define INVALID_DOS_CHARS  INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
129
130 #define MAX_DIR_ENTRY_LEN 255  /* max length of a directory entry in chars */
131
132 static int show_dir_symlinks = -1;
133 static int show_dot_files;
134
135 /* at some point we may want to allow Winelib apps to set this */
136 static const int is_case_sensitive = FALSE;
137
138 static CRITICAL_SECTION dir_section;
139 static CRITICAL_SECTION_DEBUG critsect_debug =
140 {
141     0, 0, &dir_section,
142     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
143       0, 0, { 0, (DWORD)(__FILE__ ": dir_section") }
144 };
145 static CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
146
147
148 /* check if a given Unicode char is OK in a DOS short name */
149 static inline BOOL is_invalid_dos_char( WCHAR ch )
150 {
151     static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
152     if (ch > 0x7f) return TRUE;
153     return strchrW( invalid_chars, ch ) != NULL;
154 }
155
156 /***********************************************************************
157  *           get_default_com_device
158  *
159  * Return the default device to use for serial ports.
160  */
161 static char *get_default_com_device( int num )
162 {
163     char *ret = NULL;
164
165     if (!num || num > 9) return ret;
166 #ifdef linux
167     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
168     if (ret)
169     {
170         strcpy( ret, "/dev/ttyS0" );
171         ret[strlen(ret) - 1] = '0' + num - 1;
172     }
173 #else
174     FIXME( "no known default for device com%d\n", num );
175 #endif
176     return ret;
177 }
178
179
180 /***********************************************************************
181  *           get_default_lpt_device
182  *
183  * Return the default device to use for parallel ports.
184  */
185 static char *get_default_lpt_device( int num )
186 {
187     char *ret = NULL;
188
189     if (!num || num > 9) return ret;
190 #ifdef linux
191     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
192     if (ret)
193     {
194         strcpy( ret, "/dev/lp0" );
195         ret[strlen(ret) - 1] = '0' + num - 1;
196     }
197 #else
198     FIXME( "no known default for device lpt%d\n", num );
199 #endif
200     return ret;
201 }
202
203
204 /***********************************************************************
205  *           parse_mount_entries
206  *
207  * Parse mount entries looking for a given device. Helper for get_default_drive_device.
208  */
209 #ifdef linux
210 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
211 {
212     struct mntent *entry;
213     struct stat st;
214     char *device;
215
216     while ((entry = getmntent( f )))
217     {
218         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
219         if (!strcmp( entry->mnt_type, "nfs" ) ||
220             !strcmp( entry->mnt_type, "smbfs" ) ||
221             !strcmp( entry->mnt_type, "ncpfs" )) continue;
222
223         if (stat( entry->mnt_dir, &st ) == -1) continue;
224         if (st.st_dev != dev || st.st_ino != ino) continue;
225         if (!strcmp( entry->mnt_type, "supermount" ))
226         {
227             if ((device = strstr( entry->mnt_opts, "dev=" )))
228             {
229                 char *p = strchr( device + 4, ',' );
230                 if (p) *p = 0;
231                 return device + 4;
232             }
233         }
234         else
235             return entry->mnt_fsname;
236     }
237     return NULL;
238 }
239 #endif
240
241 /***********************************************************************
242  *           get_default_drive_device
243  *
244  * Return the default device to use for a given drive mount point.
245  */
246 static char *get_default_drive_device( const char *root )
247 {
248     char *ret = NULL;
249
250 #ifdef linux
251     FILE *f;
252     char *device = NULL;
253     int fd, res = -1;
254     struct stat st;
255
256     /* try to open it first to force it to get mounted */
257     if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
258     {
259         res = fstat( fd, &st );
260         close( fd );
261     }
262     /* now try normal stat just in case */
263     if (res == -1) res = stat( root, &st );
264     if (res == -1) return NULL;
265
266     RtlEnterCriticalSection( &dir_section );
267
268     if ((f = fopen( "/etc/mtab", "r" )))
269     {
270         device = parse_mount_entries( f, st.st_dev, st.st_ino );
271         endmntent( f );
272     }
273     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
274     if (!device && (f = fopen( "/etc/fstab", "r" )))
275     {
276         device = parse_mount_entries( f, st.st_dev, st.st_ino );
277         endmntent( f );
278     }
279     if (device)
280     {
281         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
282         if (ret) strcpy( ret, device );
283     }
284     RtlLeaveCriticalSection( &dir_section );
285 #elif defined(__APPLE__)
286     struct statfs *mntStat;
287     struct stat st;
288     int i;
289     int mntSize;
290     dev_t dev;
291     ino_t ino;
292     static const char path_bsd_device[] = "/dev/disk";
293     int res;
294
295     res = stat( root, &st );
296     if (res == -1) return NULL;
297
298     dev = st.st_dev;
299     ino = st.st_ino;
300
301     RtlEnterCriticalSection( &dir_section );
302
303     mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
304
305     for (i = 0; i < mntSize && !ret; i++)
306     {
307         if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
308         if (st.st_dev != dev || st.st_ino != ino) continue;
309
310         /* FIXME add support for mounted network drive */
311         if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
312         {
313             /* set return value to the corresponding raw BSD node */
314             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
315             if (ret)
316             {
317                 strcpy(ret, "/dev/r");
318                 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
319             }
320         }
321     }
322     RtlLeaveCriticalSection( &dir_section );
323 #else
324     static int warned;
325     if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
326 #endif
327     return ret;
328 }
329
330
331 /***********************************************************************
332  *           init_options
333  *
334  * Initialize the show_dir_symlinks and show_dot_files options.
335  */
336 static void init_options(void)
337 {
338     static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
339                                   'S','o','f','t','w','a','r','e','\\',
340                                   'W','i','n','e','\\','W','i','n','e','\\',
341                                   'C','o','n','f','i','g','\\','W','i','n','e',0};
342     static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
343     static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
344     char tmp[80];
345     HKEY hkey;
346     DWORD dummy;
347     OBJECT_ATTRIBUTES attr;
348     UNICODE_STRING nameW;
349
350     show_dot_files = show_dir_symlinks = 0;
351
352     attr.Length = sizeof(attr);
353     attr.RootDirectory = 0;
354     attr.ObjectName = &nameW;
355     attr.Attributes = 0;
356     attr.SecurityDescriptor = NULL;
357     attr.SecurityQualityOfService = NULL;
358     RtlInitUnicodeString( &nameW, WineW );
359
360     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
361     {
362         RtlInitUnicodeString( &nameW, ShowDotFilesW );
363         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
364         {
365             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
366             show_dot_files = IS_OPTION_TRUE( str[0] );
367         }
368         RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
369         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
370         {
371             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
372             show_dir_symlinks = IS_OPTION_TRUE( str[0] );
373         }
374         NtClose( hkey );
375     }
376 }
377
378
379 /***********************************************************************
380  *           DIR_is_hidden_file
381  *
382  * Check if the specified file should be hidden based on its name and the show dot files option.
383  */
384 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
385 {
386     WCHAR *p, *end;
387
388     if (show_dir_symlinks == -1) init_options();
389     if (show_dot_files) return FALSE;
390
391     end = p = name->Buffer + name->Length/sizeof(WCHAR);
392     while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
393     while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
394     if (p == end || *p != '.') return FALSE;
395     /* make sure it isn't '.' or '..' */
396     if (p + 1 == end) return FALSE;
397     if (p[1] == '.' && p + 2 == end) return FALSE;
398     return TRUE;
399 }
400
401
402 /***********************************************************************
403  *           hash_short_file_name
404  *
405  * Transform a Unix file name into a hashed DOS name. If the name is a valid
406  * DOS name, it is converted to upper-case; otherwise it is replaced by a
407  * hashed version that fits in 8.3 format.
408  * 'buffer' must be at least 12 characters long.
409  * Returns length of short name in bytes; short name is NOT null-terminated.
410  */
411 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
412 {
413     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
414
415     LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
416     LPWSTR dst;
417     unsigned short hash;
418     int i;
419
420     /* Compute the hash code of the file name */
421     /* If you know something about hash functions, feel free to */
422     /* insert a better algorithm here... */
423     if (!is_case_sensitive)
424     {
425         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
426             hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
427         hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
428     }
429     else
430     {
431         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
432             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
433         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
434     }
435
436     /* Find last dot for start of the extension */
437     for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
438
439     /* Copy first 4 chars, replacing invalid chars with '_' */
440     for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
441     {
442         if (p == end || p == ext) break;
443         *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
444     }
445     /* Pad to 5 chars with '~' */
446     while (i-- >= 0) *dst++ = '~';
447
448     /* Insert hash code converted to 3 ASCII chars */
449     *dst++ = hash_chars[(hash >> 10) & 0x1f];
450     *dst++ = hash_chars[(hash >> 5) & 0x1f];
451     *dst++ = hash_chars[hash & 0x1f];
452
453     /* Copy the first 3 chars of the extension (if any) */
454     if (ext)
455     {
456         *dst++ = '.';
457         for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
458             *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
459     }
460     return dst - buffer;
461 }
462
463
464 /***********************************************************************
465  *           match_filename
466  *
467  * Check a long file name against a mask.
468  *
469  * Tests (done in W95 DOS shell - case insensitive):
470  * *.txt                        test1.test.txt                          *
471  * *st1*                        test1.txt                               *
472  * *.t??????.t*                 test1.ta.tornado.txt                    *
473  * *tornado*                    test1.ta.tornado.txt                    *
474  * t*t                          test1.ta.tornado.txt                    *
475  * ?est*                        test1.txt                               *
476  * ?est???                      test1.txt                               -
477  * *test1.txt*                  test1.txt                               *
478  * h?l?o*t.dat                  hellothisisatest.dat                    *
479  */
480 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
481 {
482     int mismatch;
483     const WCHAR *name = name_str->Buffer;
484     const WCHAR *mask = mask_str->Buffer;
485     const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
486     const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
487     const WCHAR *lastjoker = NULL;
488     const WCHAR *next_to_retry = NULL;
489
490     TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
491
492     while (name < name_end && mask < mask_end)
493     {
494         switch(*mask)
495         {
496         case '*':
497             mask++;
498             while (mask < mask_end && *mask == '*') mask++;  /* Skip consecutive '*' */
499             if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
500             lastjoker = mask;
501
502             /* skip to the next match after the joker(s) */
503             if (is_case_sensitive)
504                 while (name < name_end && (*name != *mask)) name++;
505             else
506                 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
507             next_to_retry = name;
508             break;
509         case '?':
510             mask++;
511             name++;
512             break;
513         default:
514             if (is_case_sensitive) mismatch = (*mask != *name);
515             else mismatch = (toupperW(*mask) != toupperW(*name));
516
517             if (!mismatch)
518             {
519                 mask++;
520                 name++;
521                 if (mask == mask_end)
522                 {
523                     if (name == name_end) return TRUE;
524                     if (lastjoker) mask = lastjoker;
525                 }
526             }
527             else /* mismatch ! */
528             {
529                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
530                 {
531                     mask = lastjoker;
532
533                     /* this scan sequence was a mismatch, so restart
534                      * 1 char after the first char we checked last time */
535                     next_to_retry++;
536                     name = next_to_retry;
537                 }
538                 else return FALSE; /* bad luck */
539             }
540             break;
541         }
542     }
543     while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
544         mask++;  /* Ignore trailing '.' or '*' in mask */
545     return (name == name_end && mask == mask_end);
546 }
547
548
549 /***********************************************************************
550  *           append_entry
551  *
552  * helper for NtQueryDirectoryFile
553  */
554 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
555                                                 const char *long_name, const char *short_name,
556                                                 const UNICODE_STRING *mask )
557 {
558     FILE_BOTH_DIR_INFORMATION *info;
559     int i, long_len, short_len, total_len;
560     struct stat st;
561     WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
562     WCHAR short_nameW[12];
563     UNICODE_STRING str;
564
565     long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
566     if (long_len == -1) return NULL;
567
568     str.Buffer = long_nameW;
569     str.Length = long_len * sizeof(WCHAR);
570     str.MaximumLength = sizeof(long_nameW);
571
572     if (short_name)
573     {
574         short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
575                                      short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
576         if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
577     }
578     else  /* generate a short name if necessary */
579     {
580         BOOLEAN spaces;
581
582         short_len = 0;
583         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
584             short_len = hash_short_file_name( &str, short_nameW );
585     }
586
587     TRACE( "long %s short %s mask %s\n",
588            debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
589
590     if (mask && !match_filename( &str, mask ))
591     {
592         if (!short_len) return NULL;  /* no short name to match */
593         str.Buffer = short_nameW;
594         str.Length = short_len * sizeof(WCHAR);
595         str.MaximumLength = sizeof(short_nameW);
596         if (!match_filename( &str, mask )) return NULL;
597     }
598
599     total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
600     info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
601
602     if (*pos + total_len > max_length) total_len = max_length - *pos;
603
604     if (lstat( long_name, &st ) == -1) return NULL;
605     if (S_ISLNK( st.st_mode ))
606     {
607         if (stat( long_name, &st ) == -1) return NULL;
608         if (S_ISDIR( st.st_mode ) && !show_dir_symlinks) return NULL;
609     }
610
611     info->NextEntryOffset = total_len;
612     info->FileIndex = 0;  /* NTFS always has 0 here, so let's not bother with it */
613
614     RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
615     RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
616     RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
617     RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
618
619     if (S_ISDIR(st.st_mode))
620     {
621         info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
622         info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
623     }
624     else
625     {
626         info->EndOfFile.QuadPart = st.st_size;
627         info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
628         info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
629     }
630
631     if (!(st.st_mode & S_IWUSR))
632         info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
633
634     if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
635         info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
636
637     info->EaSize = 0; /* FIXME */
638     info->ShortNameLength = short_len * sizeof(WCHAR);
639     for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
640     info->FileNameLength = long_len * sizeof(WCHAR);
641     memcpy( info->FileName, long_nameW,
642             min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
643
644     *pos += total_len;
645     return info;
646 }
647
648
649 /***********************************************************************
650  *           read_directory_vfat
651  *
652  * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
653  */
654 #ifdef VFAT_IOCTL_READDIR_BOTH
655 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
656                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
657                                 BOOLEAN restart_scan )
658
659 {
660     int res;
661     KERNEL_DIRENT de[2];
662     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
663     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
664
665     io->u.Status = STATUS_SUCCESS;
666
667     if (restart_scan) lseek( fd, 0, SEEK_SET );
668
669     if (length < max_dir_info_size)  /* we may have to return a partial entry here */
670     {
671         off_t old_pos = lseek( fd, 0, SEEK_CUR );
672
673         res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
674         if (res == -1 && errno != ENOENT) return -1;  /* VFAT ioctl probably not supported */
675
676         while (res != -1)
677         {
678             if (!de[0].d_reclen) break;
679             if (de[1].d_name[0])
680                 info = append_entry( buffer, &io->Information, length,
681                                      de[1].d_name, de[0].d_name, mask );
682             else
683                 info = append_entry( buffer, &io->Information, length,
684                                      de[0].d_name, NULL, mask );
685             if (info)
686             {
687                 last_info = info;
688                 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
689                 {
690                     io->u.Status = STATUS_BUFFER_OVERFLOW;
691                     lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
692                 }
693                 break;
694             }
695             old_pos = lseek( fd, 0, SEEK_CUR );
696             res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
697         }
698     }
699     else  /* we'll only return full entries, no need to worry about overflow */
700     {
701         res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
702         if (res == -1 && errno != ENOENT) return -1;  /* VFAT ioctl probably not supported */
703
704         while (res != -1)
705         {
706             if (!de[0].d_reclen) break;
707             if (de[1].d_name[0])
708                 info = append_entry( buffer, &io->Information, length,
709                                      de[1].d_name, de[0].d_name, mask );
710             else
711                 info = append_entry( buffer, &io->Information, length,
712                                      de[0].d_name, NULL, mask );
713             if (info)
714             {
715                 last_info = info;
716                 if (single_entry) break;
717                 /* check if we still have enough space for the largest possible entry */
718                 if (io->Information + max_dir_info_size > length) break;
719             }
720             res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
721         }
722     }
723
724     if (last_info) last_info->NextEntryOffset = 0;
725     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
726     return 0;
727 }
728 #endif /* VFAT_IOCTL_READDIR_BOTH */
729
730
731 /***********************************************************************
732  *           read_directory_getdents
733  *
734  * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
735  */
736 #ifdef USE_GETDENTS
737 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
738                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
739                                     BOOLEAN restart_scan )
740 {
741     off_t old_pos = 0;
742     size_t size = length;
743     int res;
744     char local_buffer[8192];
745     KERNEL_DIRENT64 *data, *de;
746     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
747     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
748
749     if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
750     {
751         size = sizeof(local_buffer);
752         data = (KERNEL_DIRENT64 *)local_buffer;
753     }
754
755     if (restart_scan) lseek( fd, 0, SEEK_SET );
756     else if (length < max_dir_info_size)  /* we may have to return a partial entry here */
757     {
758         old_pos = lseek( fd, 0, SEEK_CUR );
759         if (old_pos == -1 && errno == ENOENT)
760         {
761             io->u.Status = STATUS_NO_MORE_FILES;
762             res = 0;
763             goto done;
764         }
765     }
766
767     io->u.Status = STATUS_SUCCESS;
768
769     res = getdents64( fd, data, size );
770     if (res == -1)
771     {
772         if (errno != ENOSYS)
773         {
774             io->u.Status = FILE_GetNtStatus();
775             res = 0;
776         }
777         goto done;
778     }
779
780     de = data;
781
782     while (res > 0)
783     {
784         res -= de->d_reclen;
785         info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
786         if (info)
787         {
788             last_info = info;
789             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
790             {
791                 io->u.Status = STATUS_BUFFER_OVERFLOW;
792                 lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
793                 break;
794             }
795             /* check if we still have enough space for the largest possible entry */
796             if (single_entry || io->Information + max_dir_info_size > length)
797             {
798                 if (res > 0) lseek( fd, de->d_off, SEEK_SET );  /* set pos to next entry */
799                 break;
800             }
801         }
802         old_pos = de->d_off;
803         /* move on to the next entry */
804         if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
805         else
806         {
807             res = getdents64( fd, data, size );
808             de = data;
809         }
810     }
811
812     if (last_info) last_info->NextEntryOffset = 0;
813     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
814     res = 0;
815 done:
816     if ((char *)data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
817     return res;
818 }
819 #endif  /* USE_GETDENTS */
820
821
822 /***********************************************************************
823  *           read_directory_readdir
824  *
825  * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
826  */
827 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
828                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
829                                     BOOLEAN restart_scan )
830 {
831     DIR *dir;
832     off_t i, old_pos = 0;
833     struct dirent *de;
834     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
835     static const unsigned int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
836
837     if (!(dir = opendir( "." )))
838     {
839         io->u.Status = FILE_GetNtStatus();
840         return;
841     }
842
843     if (!restart_scan)
844     {
845         old_pos = lseek( fd, 0, SEEK_CUR );
846         /* skip the right number of entries */
847         for (i = 0; i < old_pos; i++)
848         {
849             if (!readdir( dir ))
850             {
851                 closedir( dir );
852                 io->u.Status = STATUS_NO_MORE_FILES;
853                 return;
854             }
855         }
856     }
857     io->u.Status = STATUS_SUCCESS;
858
859     while ((de = readdir( dir )))
860     {
861         old_pos++;
862         info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
863         if (info)
864         {
865             last_info = info;
866             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
867             {
868                 io->u.Status = STATUS_BUFFER_OVERFLOW;
869                 old_pos--;  /* restore pos to previous entry */
870                 break;
871             }
872             if (single_entry) break;
873             /* check if we still have enough space for the largest possible entry */
874             if (io->Information + max_dir_info_size > length) break;
875         }
876     }
877
878     lseek( fd, old_pos, SEEK_SET );  /* store dir offset as filepos for fd */
879     closedir( dir );
880
881     if (last_info) last_info->NextEntryOffset = 0;
882     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
883 }
884
885
886 /******************************************************************************
887  *  NtQueryDirectoryFile        [NTDLL.@]
888  *  ZwQueryDirectoryFile        [NTDLL.@]
889  */
890 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
891                                       PIO_APC_ROUTINE apc_routine, PVOID apc_context,
892                                       PIO_STATUS_BLOCK io,
893                                       PVOID buffer, ULONG length,
894                                       FILE_INFORMATION_CLASS info_class,
895                                       BOOLEAN single_entry,
896                                       PUNICODE_STRING mask,
897                                       BOOLEAN restart_scan )
898 {
899     int cwd, fd;
900
901     TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
902           handle, event, apc_routine, apc_context, io, buffer,
903           length, info_class, single_entry, debugstr_us(mask),
904           restart_scan);
905
906     if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
907
908     if (event || apc_routine)
909     {
910         FIXME( "Unsupported yet option\n" );
911         return io->u.Status = STATUS_NOT_IMPLEMENTED;
912     }
913     if (info_class != FileBothDirectoryInformation)
914     {
915         FIXME( "Unsupported file info class %d\n", info_class );
916         return io->u.Status = STATUS_NOT_IMPLEMENTED;
917     }
918
919     if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ, &fd, NULL )) != STATUS_SUCCESS)
920         return io->u.Status;
921
922     io->Information = 0;
923
924     RtlEnterCriticalSection( &dir_section );
925
926     if (show_dir_symlinks == -1) init_options();
927
928     if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
929     {
930 #ifdef VFAT_IOCTL_READDIR_BOTH
931         if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
932 #endif
933 #ifdef USE_GETDENTS
934             if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) == -1)
935 #endif
936                 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
937
938         if (fchdir( cwd ) == -1) chdir( "/" );
939     }
940     else io->u.Status = FILE_GetNtStatus();
941
942     RtlLeaveCriticalSection( &dir_section );
943
944     wine_server_release_fd( handle, fd );
945     if (cwd != -1) close( cwd );
946     TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
947     return io->u.Status;
948 }
949
950
951 /***********************************************************************
952  *           find_file_in_dir
953  *
954  * Find a file in a directory the hard way, by doing a case-insensitive search.
955  * The file found is appended to unix_name at pos.
956  * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
957  */
958 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
959                                   int check_case )
960 {
961     WCHAR buffer[MAX_DIR_ENTRY_LEN];
962     UNICODE_STRING str;
963     BOOLEAN spaces;
964     DIR *dir;
965     struct dirent *de;
966     struct stat st;
967     int ret, used_default, is_name_8_dot_3;
968
969     /* try a shortcut for this directory */
970
971     unix_name[pos++] = '/';
972     ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
973                            NULL, &used_default );
974     /* if we used the default char, the Unix name won't round trip properly back to Unicode */
975     /* so it cannot match the file we are looking for */
976     if (ret >= 0 && !used_default)
977     {
978         unix_name[pos + ret] = 0;
979         if (!stat( unix_name, &st )) return STATUS_SUCCESS;
980     }
981     if (check_case) goto not_found;  /* we want an exact match */
982
983     if (pos > 1) unix_name[pos - 1] = 0;
984     else unix_name[1] = 0;  /* keep the initial slash */
985
986     /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
987
988     str.Buffer = (WCHAR *)name;
989     str.Length = length * sizeof(WCHAR);
990     str.MaximumLength = str.Length;
991     is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
992
993     /* now look for it through the directory */
994
995 #ifdef VFAT_IOCTL_READDIR_BOTH
996     if (is_name_8_dot_3)
997     {
998         int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
999         if (fd != -1)
1000         {
1001             KERNEL_DIRENT de[2];
1002
1003             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
1004             {
1005                 unix_name[pos - 1] = '/';
1006                 for (;;)
1007                 {
1008                     if (!de[0].d_reclen) break;
1009
1010                     if (de[1].d_name[0])
1011                     {
1012                         ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1013                                                buffer, MAX_DIR_ENTRY_LEN );
1014                         if (ret == length && !memicmpW( buffer, name, length))
1015                         {
1016                             strcpy( unix_name + pos, de[1].d_name );
1017                             close( fd );
1018                             return STATUS_SUCCESS;
1019                         }
1020                     }
1021                     ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1022                                            buffer, MAX_DIR_ENTRY_LEN );
1023                     if (ret == length && !memicmpW( buffer, name, length))
1024                     {
1025                         strcpy( unix_name + pos,
1026                                 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1027                         close( fd );
1028                         return STATUS_SUCCESS;
1029                     }
1030                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1031                     {
1032                         close( fd );
1033                         goto not_found;
1034                     }
1035                 }
1036             }
1037             close( fd );
1038         }
1039         /* fall through to normal handling */
1040     }
1041 #endif /* VFAT_IOCTL_READDIR_BOTH */
1042
1043     if (!(dir = opendir( unix_name )))
1044     {
1045         if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1046         else return FILE_GetNtStatus();
1047     }
1048     unix_name[pos - 1] = '/';
1049     str.Buffer = buffer;
1050     str.MaximumLength = sizeof(buffer);
1051     while ((de = readdir( dir )))
1052     {
1053         ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1054         if (ret == length && !memicmpW( buffer, name, length ))
1055         {
1056             strcpy( unix_name + pos, de->d_name );
1057             closedir( dir );
1058             return STATUS_SUCCESS;
1059         }
1060
1061         if (!is_name_8_dot_3) continue;
1062
1063         str.Length = ret * sizeof(WCHAR);
1064         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1065         {
1066             WCHAR short_nameW[12];
1067             ret = hash_short_file_name( &str, short_nameW );
1068             if (ret == length && !memicmpW( short_nameW, name, length ))
1069             {
1070                 strcpy( unix_name + pos, de->d_name );
1071                 closedir( dir );
1072                 return STATUS_SUCCESS;
1073             }
1074         }
1075     }
1076     closedir( dir );
1077     goto not_found;  /* avoid warning */
1078
1079 not_found:
1080     unix_name[pos - 1] = 0;
1081     return STATUS_OBJECT_PATH_NOT_FOUND;
1082 }
1083
1084
1085 /******************************************************************************
1086  *           get_dos_device
1087  *
1088  * Get the Unix path of a DOS device.
1089  */
1090 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1091 {
1092     const char *config_dir = wine_get_config_dir();
1093     struct stat st;
1094     char *unix_name, *new_name, *dev;
1095     unsigned int i;
1096     int unix_len;
1097
1098     /* make sure the device name is ASCII */
1099     for (i = 0; i < name_len; i++)
1100         if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
1101
1102     unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1103
1104     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1105         return STATUS_NO_MEMORY;
1106
1107     strcpy( unix_name, config_dir );
1108     strcat( unix_name, "/dosdevices/" );
1109     dev = unix_name + strlen(unix_name);
1110
1111     for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1112     dev[i] = 0;
1113
1114     /* special case for drive devices */
1115     if (name_len == 2 && dev[1] == ':')
1116     {
1117         dev[i++] = ':';
1118         dev[i] = 0;
1119     }
1120
1121     for (;;)
1122     {
1123         if (!stat( unix_name, &st ))
1124         {
1125             TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1126             unix_name_ret->Buffer = unix_name;
1127             unix_name_ret->Length = strlen(unix_name);
1128             unix_name_ret->MaximumLength = unix_len;
1129             return STATUS_SUCCESS;
1130         }
1131         if (!dev) break;
1132
1133         /* now try some defaults for it */
1134         if (!strcmp( dev, "aux" ))
1135         {
1136             strcpy( dev, "com1" );
1137             continue;
1138         }
1139         if (!strcmp( dev, "prn" ))
1140         {
1141             strcpy( dev, "lpt1" );
1142             continue;
1143         }
1144         if (!strcmp( dev, "nul" ))
1145         {
1146             strcpy( unix_name, "/dev/null" );
1147             dev = NULL; /* last try */
1148             continue;
1149         }
1150
1151         new_name = NULL;
1152         if (dev[1] == ':' && dev[2] == ':')  /* drive device */
1153         {
1154             dev[2] = 0;  /* remove last ':' to get the drive mount point symlink */
1155             new_name = get_default_drive_device( unix_name );
1156         }
1157         else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1158         else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1159
1160         if (!new_name) break;
1161
1162         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1163         unix_name = new_name;
1164         unix_len = strlen(unix_name) + 1;
1165         dev = NULL; /* last try */
1166     }
1167     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1168     return STATUS_OBJECT_NAME_NOT_FOUND;
1169 }
1170
1171
1172 /* return the length of the DOS namespace prefix if any */
1173 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1174 {
1175     static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1176     static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1177
1178     if (name->Length > sizeof(nt_prefixW) &&
1179         !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1180         return sizeof(nt_prefixW) / sizeof(WCHAR);
1181
1182     if (name->Length > sizeof(dosdev_prefixW) &&
1183         !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1184         return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1185
1186     return 0;
1187 }
1188
1189
1190 /******************************************************************************
1191  *           wine_nt_to_unix_file_name  (NTDLL.@) Not a Windows API
1192  *
1193  * Convert a file name from NT namespace to Unix namespace.
1194  *
1195  * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1196  * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1197  * returned, but the unix name is still filled in properly.
1198  */
1199 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1200                                     UINT disposition, BOOLEAN check_case )
1201 {
1202     static const WCHAR uncW[] = {'U','N','C','\\'};
1203     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1204
1205     NTSTATUS status = STATUS_SUCCESS;
1206     const char *config_dir = wine_get_config_dir();
1207     const WCHAR *name, *p;
1208     struct stat st;
1209     char *unix_name;
1210     int pos, ret, name_len, unix_len, used_default;
1211
1212     name     = nameW->Buffer;
1213     name_len = nameW->Length / sizeof(WCHAR);
1214
1215     if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1216
1217     if ((pos = get_dos_prefix_len( nameW )))
1218     {
1219         BOOLEAN is_unc = FALSE;
1220
1221         name += pos;
1222         name_len -= pos;
1223
1224         /* check for UNC prefix */
1225         if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1226         {
1227             name += 3;
1228             name_len -= 3;
1229             is_unc = TRUE;
1230         }
1231         else
1232         {
1233             /* check for a drive letter with path */
1234             if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1235             {
1236                 /* not a drive with path, try other DOS devices */
1237                 return get_dos_device( name, name_len, unix_name_ret );
1238             }
1239             name += 2;  /* skip drive letter */
1240             name_len -= 2;
1241         }
1242
1243         /* check for invalid characters */
1244         for (p = name; p < name + name_len; p++)
1245             if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1246
1247         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1248         unix_len += MAX_DIR_ENTRY_LEN + 3;
1249         unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1250         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1251             return STATUS_NO_MEMORY;
1252         strcpy( unix_name, config_dir );
1253         strcat( unix_name, "/dosdevices/" );
1254         pos = strlen(unix_name);
1255         if (is_unc)
1256         {
1257             strcpy( unix_name + pos, "unc" );
1258             pos += 3;
1259         }
1260         else
1261         {
1262             unix_name[pos++] = tolowerW( name[-2] );
1263             unix_name[pos++] = ':';
1264             unix_name[pos] = 0;
1265         }
1266     }
1267     else  /* no DOS prefix, assume NT native name, map directly to Unix */
1268     {
1269         if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1270         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1271         unix_len += MAX_DIR_ENTRY_LEN + 3;
1272         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1273             return STATUS_NO_MEMORY;
1274         pos = 0;
1275     }
1276
1277     /* try a shortcut first */
1278
1279     ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1280                            NULL, &used_default );
1281
1282     while (name_len && IS_SEPARATOR(*name))
1283     {
1284         name++;
1285         name_len--;
1286     }
1287
1288     if (ret > 0 && !used_default)  /* if we used the default char the name didn't convert properly */
1289     {
1290         char *p;
1291         unix_name[pos + ret] = 0;
1292         for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1293         if (!stat( unix_name, &st ))
1294         {
1295             /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1296             if (disposition == FILE_CREATE)
1297                 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1298             goto done;
1299         }
1300     }
1301
1302     if (!name_len)  /* empty name -> drive root doesn't exist */
1303     {
1304         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1305         return STATUS_OBJECT_PATH_NOT_FOUND;
1306     }
1307     if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1308     {
1309         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1310         return STATUS_OBJECT_NAME_NOT_FOUND;
1311     }
1312
1313     /* now do it component by component */
1314
1315     while (name_len)
1316     {
1317         const WCHAR *end, *next;
1318
1319         end = name;
1320         while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1321         next = end;
1322         while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1323         name_len -= next - name;
1324
1325         /* grow the buffer if needed */
1326
1327         if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1328         {
1329             char *new_name;
1330             unix_len += 2 * MAX_DIR_ENTRY_LEN;
1331             if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1332             {
1333                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1334                 return STATUS_NO_MEMORY;
1335             }
1336             unix_name = new_name;
1337         }
1338
1339         status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1340
1341         /* if this is the last element, not finding it is not necessarily fatal */
1342         if (!name_len)
1343         {
1344             if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1345             {
1346                 status = STATUS_OBJECT_NAME_NOT_FOUND;
1347                 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1348                 {
1349                     ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1350                                            MAX_DIR_ENTRY_LEN, NULL, &used_default );
1351                     if (ret > 0 && !used_default)
1352                     {
1353                         unix_name[pos] = '/';
1354                         unix_name[pos + 1 + ret] = 0;
1355                         status = STATUS_NO_SUCH_FILE;
1356                         break;
1357                     }
1358                 }
1359             }
1360             else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1361             {
1362                 status = STATUS_OBJECT_NAME_COLLISION;
1363             }
1364         }
1365
1366         if (status != STATUS_SUCCESS)
1367         {
1368             /* couldn't find it at all, fail */
1369             WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1370             RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1371             return status;
1372         }
1373
1374         pos += strlen( unix_name + pos );
1375         name = next;
1376     }
1377
1378     WARN( "%s -> %s required a case-insensitive search\n",
1379           debugstr_us(nameW), debugstr_a(unix_name) );
1380
1381 done:
1382     TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1383     unix_name_ret->Buffer = unix_name;
1384     unix_name_ret->Length = strlen(unix_name);
1385     unix_name_ret->MaximumLength = unix_len;
1386     return status;
1387 }
1388
1389
1390 /******************************************************************
1391  *              RtlDoesFileExists_U   (NTDLL.@)
1392  */
1393 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1394 {
1395     UNICODE_STRING nt_name;
1396     ANSI_STRING unix_name;
1397     BOOLEAN ret;
1398
1399     if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1400     ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1401     if (ret) RtlFreeAnsiString( &unix_name );
1402     RtlFreeUnicodeString( &nt_name );
1403     return ret;
1404 }