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