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