ntdll: Ignore failure to open current directory, it's broken on Mac OS X.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, 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 #include <limits.h>
35 #ifdef HAVE_MNTENT_H
36 #include <mntent.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_LINUX_IOCTL_H
45 #include <linux/ioctl.h>
46 #endif
47 #ifdef HAVE_LINUX_MAJOR_H
48 # include <linux/major.h>
49 #endif
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
52 #endif
53 #ifdef HAVE_SYS_MOUNT_H
54 #include <sys/mount.h>
55 #endif
56 #include <time.h>
57 #ifdef HAVE_UNISTD_H
58 # include <unistd.h>
59 #endif
60
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
63 #include "ntstatus.h"
64 #define WIN32_NO_STATUS
65 #include "windef.h"
66 #include "winnt.h"
67 #include "thread.h"
68 #include "winternl.h"
69 #include "ntdll_misc.h"
70 #include "wine/unicode.h"
71 #include "wine/server.h"
72 #include "wine/library.h"
73 #include "wine/debug.h"
74
75 WINE_DEFAULT_DEBUG_CHANNEL(file);
76
77 /* just in case... */
78 #undef VFAT_IOCTL_READDIR_BOTH
79 #undef USE_GETDENTS
80
81 #ifdef linux
82
83 /* We want the real kernel dirent structure, not the libc one */
84 typedef struct
85 {
86     long d_ino;
87     long d_off;
88     unsigned short d_reclen;
89     char d_name[256];
90 } KERNEL_DIRENT;
91
92 /* Define the VFAT ioctl to get both short and long file names */
93 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
94
95 #ifndef O_DIRECTORY
96 # define O_DIRECTORY 0200000 /* must be directory */
97 #endif
98
99 #ifdef __i386__
100
101 typedef struct
102 {
103     ULONG64        d_ino;
104     LONG64         d_off;
105     unsigned short d_reclen;
106     unsigned char  d_type;
107     char           d_name[256];
108 } KERNEL_DIRENT64;
109
110 static inline int getdents64( int fd, char *de, unsigned int size )
111 {
112     int ret;
113     __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
114              : "=a" (ret)
115              : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
116              : "memory" );
117     if (ret < 0)
118     {
119         errno = -ret;
120         ret = -1;
121     }
122     return ret;
123 }
124 #define USE_GETDENTS
125
126 #endif  /* i386 */
127
128 #endif  /* linux */
129
130 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
131 #define IS_SEPARATOR(ch)   ((ch) == '\\' || (ch) == '/')
132
133 #define INVALID_NT_CHARS   '*','?','<','>','|','"'
134 #define INVALID_DOS_CHARS  INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
135
136 #define MAX_DIR_ENTRY_LEN 255  /* max length of a directory entry in chars */
137
138 static const unsigned int max_dir_info_size = FIELD_OFFSET( FILE_BOTH_DIR_INFORMATION, FileName[MAX_DIR_ENTRY_LEN] );
139
140 static int show_dot_files = -1;
141
142 /* at some point we may want to allow Winelib apps to set this */
143 static const int is_case_sensitive = FALSE;
144
145 static RTL_CRITICAL_SECTION dir_section;
146 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
147 {
148     0, 0, &dir_section,
149     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
150       0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
151 };
152 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
153
154
155 /* check if a given Unicode char is OK in a DOS short name */
156 static inline BOOL is_invalid_dos_char( WCHAR ch )
157 {
158     static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
159     if (ch > 0x7f) return TRUE;
160     return strchrW( invalid_chars, ch ) != NULL;
161 }
162
163 /* check if the device can be a mounted volume */
164 static inline int is_valid_mounted_device( struct stat *st )
165 {
166 #if defined(linux) || defined(__sun__)
167     return S_ISBLK( st->st_mode );
168 #else
169     /* disks are char devices on *BSD */
170     return S_ISCHR( st->st_mode );
171 #endif
172 }
173
174 /***********************************************************************
175  *           get_default_com_device
176  *
177  * Return the default device to use for serial ports.
178  */
179 static char *get_default_com_device( int num )
180 {
181     char *ret = NULL;
182
183     if (!num || num > 9) return ret;
184 #ifdef linux
185     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
186     if (ret)
187     {
188         strcpy( ret, "/dev/ttyS0" );
189         ret[strlen(ret) - 1] = '0' + num - 1;
190     }
191 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
192     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
193     if (ret)
194     {
195         strcpy( ret, "/dev/cuad0" );
196         ret[strlen(ret) - 1] = '0' + num - 1;
197     }
198 #else
199     FIXME( "no known default for device com%d\n", num );
200 #endif
201     return ret;
202 }
203
204
205 /***********************************************************************
206  *           get_default_lpt_device
207  *
208  * Return the default device to use for parallel ports.
209  */
210 static char *get_default_lpt_device( int num )
211 {
212     char *ret = NULL;
213
214     if (!num || num > 9) return ret;
215 #ifdef linux
216     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
217     if (ret)
218     {
219         strcpy( ret, "/dev/lp0" );
220         ret[strlen(ret) - 1] = '0' + num - 1;
221     }
222 #else
223     FIXME( "no known default for device lpt%d\n", num );
224 #endif
225     return ret;
226 }
227
228
229 /***********************************************************************
230  *           parse_mount_entries
231  *
232  * Parse mount entries looking for a given device. Helper for get_default_drive_device.
233  */
234
235 #ifdef sun
236 #include <sys/vfstab.h>
237 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
238 {
239     struct vfstab entry;
240     struct stat st;
241     char *device;
242
243     while (! getvfsent( f, &entry ))
244     {
245         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
246         if (!strcmp( entry.vfs_fstype, "nfs" ) ||
247             !strcmp( entry.vfs_fstype, "smbfs" ) ||
248             !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
249
250         if (stat( entry.vfs_mountp, &st ) == -1) continue;
251         if (st.st_dev != dev || st.st_ino != ino) continue;
252         if (!strcmp( entry.vfs_fstype, "fd" ))
253         {
254             if ((device = strstr( entry.vfs_mntopts, "dev=" )))
255             {
256                 char *p = strchr( device + 4, ',' );
257                 if (p) *p = 0;
258                 return device + 4;
259             }
260         }
261         else
262             return entry.vfs_special;
263     }
264     return NULL;
265 }
266 #endif
267
268 #ifdef linux
269 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
270 {
271     struct mntent *entry;
272     struct stat st;
273     char *device;
274
275     while ((entry = getmntent( f )))
276     {
277         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
278         if (!strcmp( entry->mnt_type, "nfs" ) ||
279             !strcmp( entry->mnt_type, "smbfs" ) ||
280             !strcmp( entry->mnt_type, "ncpfs" )) continue;
281
282         if (stat( entry->mnt_dir, &st ) == -1) continue;
283         if (st.st_dev != dev || st.st_ino != ino) continue;
284         if (!strcmp( entry->mnt_type, "supermount" ))
285         {
286             if ((device = strstr( entry->mnt_opts, "dev=" )))
287             {
288                 char *p = strchr( device + 4, ',' );
289                 if (p) *p = 0;
290                 return device + 4;
291             }
292         }
293         else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
294         {
295             /* if device is a regular file check for a loop mount */
296             if ((device = strstr( entry->mnt_opts, "loop=" )))
297             {
298                 char *p = strchr( device + 5, ',' );
299                 if (p) *p = 0;
300                 return device + 5;
301             }
302         }
303         else
304             return entry->mnt_fsname;
305     }
306     return NULL;
307 }
308 #endif
309
310 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
311 #include <fstab.h>
312 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
313 {
314     struct fstab *entry;
315     struct stat st;
316
317     while ((entry = getfsent()))
318     {
319         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
320         if (!strcmp( entry->fs_vfstype, "nfs" ) ||
321             !strcmp( entry->fs_vfstype, "smbfs" ) ||
322             !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
323
324         if (stat( entry->fs_file, &st ) == -1) continue;
325         if (st.st_dev != dev || st.st_ino != ino) continue;
326         return entry->fs_spec;
327     }
328     return NULL;
329 }
330 #endif
331
332 #ifdef sun
333 #include <sys/mnttab.h>
334 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
335 {
336     struct mnttab entry;
337     struct stat st;
338     char *device;
339
340
341     while (( ! getmntent( f, &entry) ))
342     {
343         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
344         if (!strcmp( entry.mnt_fstype, "nfs" ) ||
345             !strcmp( entry.mnt_fstype, "smbfs" ) ||
346             !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
347
348         if (stat( entry.mnt_mountp, &st ) == -1) continue;
349         if (st.st_dev != dev || st.st_ino != ino) continue;
350         if (!strcmp( entry.mnt_fstype, "fd" ))
351         {
352             if ((device = strstr( entry.mnt_mntopts, "dev=" )))
353             {
354                 char *p = strchr( device + 4, ',' );
355                 if (p) *p = 0;
356                 return device + 4;
357             }
358         }
359         else
360             return entry.mnt_special;
361     }
362     return NULL;
363 }
364 #endif
365
366 /***********************************************************************
367  *           get_default_drive_device
368  *
369  * Return the default device to use for a given drive mount point.
370  */
371 static char *get_default_drive_device( const char *root )
372 {
373     char *ret = NULL;
374
375 #ifdef linux
376     FILE *f;
377     char *device = NULL;
378     int fd, res = -1;
379     struct stat st;
380
381     /* try to open it first to force it to get mounted */
382     if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
383     {
384         res = fstat( fd, &st );
385         close( fd );
386     }
387     /* now try normal stat just in case */
388     if (res == -1) res = stat( root, &st );
389     if (res == -1) return NULL;
390
391     RtlEnterCriticalSection( &dir_section );
392
393     if ((f = fopen( "/etc/mtab", "r" )))
394     {
395         device = parse_mount_entries( f, st.st_dev, st.st_ino );
396         endmntent( f );
397     }
398     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
399     if (!device && (f = fopen( "/etc/fstab", "r" )))
400     {
401         device = parse_mount_entries( f, st.st_dev, st.st_ino );
402         endmntent( f );
403     }
404     if (device)
405     {
406         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
407         if (ret) strcpy( ret, device );
408     }
409     RtlLeaveCriticalSection( &dir_section );
410
411 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
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     /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
429      * pass NULL.  Leave the argument in for symmetry.
430      */
431     device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
432     if (device)
433     {
434         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
435         if (ret) strcpy( ret, device );
436     }
437     RtlLeaveCriticalSection( &dir_section );
438
439 #elif defined( sun )
440     FILE *f;
441     char *device = NULL;
442     int fd, res = -1;
443     struct stat st;
444
445     /* try to open it first to force it to get mounted */
446     if ((fd = open( root, O_RDONLY )) != -1)
447     {
448         res = fstat( fd, &st );
449         close( fd );
450     }
451     /* now try normal stat just in case */
452     if (res == -1) res = stat( root, &st );
453     if (res == -1) return NULL;
454
455     RtlEnterCriticalSection( &dir_section );
456
457     if ((f = fopen( "/etc/mnttab", "r" )))
458     {
459         device = parse_mount_entries( f, st.st_dev, st.st_ino);
460         fclose( f );
461     }
462     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
463     if (!device && (f = fopen( "/etc/vfstab", "r" )))
464     {
465         device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
466         fclose( f );
467     }
468     if (device)
469     {
470         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
471         if (ret) strcpy( ret, device );
472     }
473     RtlLeaveCriticalSection( &dir_section );
474
475 #elif defined(__APPLE__)
476     struct statfs *mntStat;
477     struct stat st;
478     int i;
479     int mntSize;
480     dev_t dev;
481     ino_t ino;
482     static const char path_bsd_device[] = "/dev/disk";
483     int res;
484
485     res = stat( root, &st );
486     if (res == -1) return NULL;
487
488     dev = st.st_dev;
489     ino = st.st_ino;
490
491     RtlEnterCriticalSection( &dir_section );
492
493     mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
494
495     for (i = 0; i < mntSize && !ret; i++)
496     {
497         if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
498         if (st.st_dev != dev || st.st_ino != ino) continue;
499
500         /* FIXME add support for mounted network drive */
501         if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
502         {
503             /* set return value to the corresponding raw BSD node */
504             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
505             if (ret)
506             {
507                 strcpy(ret, "/dev/r");
508                 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
509             }
510         }
511     }
512     RtlLeaveCriticalSection( &dir_section );
513 #else
514     static int warned;
515     if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
516 #endif
517     return ret;
518 }
519
520
521 /***********************************************************************
522  *           get_device_mount_point
523  *
524  * Return the current mount point for a device.
525  */
526 static char *get_device_mount_point( dev_t dev )
527 {
528     char *ret = NULL;
529
530 #ifdef linux
531     FILE *f;
532
533     RtlEnterCriticalSection( &dir_section );
534
535     if ((f = fopen( "/etc/mtab", "r" )))
536     {
537         struct mntent *entry;
538         struct stat st;
539         char *p, *device;
540
541         while ((entry = getmntent( f )))
542         {
543             /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
544             if (!strcmp( entry->mnt_type, "nfs" ) ||
545                 !strcmp( entry->mnt_type, "smbfs" ) ||
546                 !strcmp( entry->mnt_type, "ncpfs" )) continue;
547
548             if (!strcmp( entry->mnt_type, "supermount" ))
549             {
550                 if ((device = strstr( entry->mnt_opts, "dev=" )))
551                 {
552                     device += 4;
553                     if ((p = strchr( device, ',' ))) *p = 0;
554                 }
555             }
556             else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
557             {
558                 /* if device is a regular file check for a loop mount */
559                 if ((device = strstr( entry->mnt_opts, "loop=" )))
560                 {
561                     device += 5;
562                     if ((p = strchr( device, ',' ))) *p = 0;
563                 }
564             }
565             else device = entry->mnt_fsname;
566
567             if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
568             {
569                 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
570                 if (ret) strcpy( ret, entry->mnt_dir );
571                 break;
572             }
573         }
574         endmntent( f );
575     }
576     RtlLeaveCriticalSection( &dir_section );
577 #elif defined(__APPLE__)
578     struct statfs *entry;
579     struct stat st;
580     int i, size;
581
582     RtlEnterCriticalSection( &dir_section );
583
584     size = getmntinfo( &entry, MNT_NOWAIT );
585     for (i = 0; i < size; i++)
586     {
587         if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
588         if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
589         {
590             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
591             if (ret) strcpy( ret, entry[i].f_mntfromname );
592             break;
593         }
594     }
595     RtlLeaveCriticalSection( &dir_section );
596 #else
597     static int warned;
598     if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
599 #endif
600     return ret;
601 }
602
603
604 /***********************************************************************
605  *           init_options
606  *
607  * Initialize the show_dot_files options.
608  */
609 static void init_options(void)
610 {
611     static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
612     static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
613     char tmp[80];
614     HANDLE root, hkey;
615     DWORD dummy;
616     OBJECT_ATTRIBUTES attr;
617     UNICODE_STRING nameW;
618
619     show_dot_files = 0;
620
621     RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
622     attr.Length = sizeof(attr);
623     attr.RootDirectory = root;
624     attr.ObjectName = &nameW;
625     attr.Attributes = 0;
626     attr.SecurityDescriptor = NULL;
627     attr.SecurityQualityOfService = NULL;
628     RtlInitUnicodeString( &nameW, WineW );
629
630     /* @@ Wine registry key: HKCU\Software\Wine */
631     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
632     {
633         RtlInitUnicodeString( &nameW, ShowDotFilesW );
634         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
635         {
636             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
637             show_dot_files = IS_OPTION_TRUE( str[0] );
638         }
639         NtClose( hkey );
640     }
641     NtClose( root );
642 }
643
644
645 /***********************************************************************
646  *           DIR_is_hidden_file
647  *
648  * Check if the specified file should be hidden based on its name and the show dot files option.
649  */
650 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
651 {
652     WCHAR *p, *end;
653
654     if (show_dot_files == -1) init_options();
655     if (show_dot_files) return FALSE;
656
657     end = p = name->Buffer + name->Length/sizeof(WCHAR);
658     while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
659     while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
660     if (p == end || *p != '.') return FALSE;
661     /* make sure it isn't '.' or '..' */
662     if (p + 1 == end) return FALSE;
663     if (p[1] == '.' && p + 2 == end) return FALSE;
664     return TRUE;
665 }
666
667
668 /***********************************************************************
669  *           hash_short_file_name
670  *
671  * Transform a Unix file name into a hashed DOS name. If the name is a valid
672  * DOS name, it is converted to upper-case; otherwise it is replaced by a
673  * hashed version that fits in 8.3 format.
674  * 'buffer' must be at least 12 characters long.
675  * Returns length of short name in bytes; short name is NOT null-terminated.
676  */
677 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
678 {
679     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
680
681     LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
682     LPWSTR dst;
683     unsigned short hash;
684     int i;
685
686     /* Compute the hash code of the file name */
687     /* If you know something about hash functions, feel free to */
688     /* insert a better algorithm here... */
689     if (!is_case_sensitive)
690     {
691         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
692             hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
693         hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
694     }
695     else
696     {
697         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
698             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
699         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
700     }
701
702     /* Find last dot for start of the extension */
703     for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
704
705     /* Copy first 4 chars, replacing invalid chars with '_' */
706     for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
707     {
708         if (p == end || p == ext) break;
709         *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
710     }
711     /* Pad to 5 chars with '~' */
712     while (i-- >= 0) *dst++ = '~';
713
714     /* Insert hash code converted to 3 ASCII chars */
715     *dst++ = hash_chars[(hash >> 10) & 0x1f];
716     *dst++ = hash_chars[(hash >> 5) & 0x1f];
717     *dst++ = hash_chars[hash & 0x1f];
718
719     /* Copy the first 3 chars of the extension (if any) */
720     if (ext)
721     {
722         *dst++ = '.';
723         for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
724             *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
725     }
726     return dst - buffer;
727 }
728
729
730 /***********************************************************************
731  *           match_filename
732  *
733  * Check a long file name against a mask.
734  *
735  * Tests (done in W95 DOS shell - case insensitive):
736  * *.txt                        test1.test.txt                          *
737  * *st1*                        test1.txt                               *
738  * *.t??????.t*                 test1.ta.tornado.txt                    *
739  * *tornado*                    test1.ta.tornado.txt                    *
740  * t*t                          test1.ta.tornado.txt                    *
741  * ?est*                        test1.txt                               *
742  * ?est???                      test1.txt                               -
743  * *test1.txt*                  test1.txt                               *
744  * h?l?o*t.dat                  hellothisisatest.dat                    *
745  */
746 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
747 {
748     int mismatch;
749     const WCHAR *name = name_str->Buffer;
750     const WCHAR *mask = mask_str->Buffer;
751     const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
752     const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
753     const WCHAR *lastjoker = NULL;
754     const WCHAR *next_to_retry = NULL;
755
756     TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
757
758     while (name < name_end && mask < mask_end)
759     {
760         switch(*mask)
761         {
762         case '*':
763             mask++;
764             while (mask < mask_end && *mask == '*') mask++;  /* Skip consecutive '*' */
765             if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
766             lastjoker = mask;
767
768             /* skip to the next match after the joker(s) */
769             if (is_case_sensitive)
770                 while (name < name_end && (*name != *mask)) name++;
771             else
772                 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
773             next_to_retry = name;
774             break;
775         case '?':
776             mask++;
777             name++;
778             break;
779         default:
780             if (is_case_sensitive) mismatch = (*mask != *name);
781             else mismatch = (toupperW(*mask) != toupperW(*name));
782
783             if (!mismatch)
784             {
785                 mask++;
786                 name++;
787                 if (mask == mask_end)
788                 {
789                     if (name == name_end) return TRUE;
790                     if (lastjoker) mask = lastjoker;
791                 }
792             }
793             else /* mismatch ! */
794             {
795                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
796                 {
797                     mask = lastjoker;
798
799                     /* this scan sequence was a mismatch, so restart
800                      * 1 char after the first char we checked last time */
801                     next_to_retry++;
802                     name = next_to_retry;
803                 }
804                 else return FALSE; /* bad luck */
805             }
806             break;
807         }
808     }
809     while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
810         mask++;  /* Ignore trailing '.' or '*' in mask */
811     return (name == name_end && mask == mask_end);
812 }
813
814
815 /***********************************************************************
816  *           append_entry
817  *
818  * helper for NtQueryDirectoryFile
819  */
820 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
821                                                 const char *long_name, const char *short_name,
822                                                 const UNICODE_STRING *mask )
823 {
824     FILE_BOTH_DIR_INFORMATION *info;
825     int i, long_len, short_len, total_len;
826     struct stat st;
827     WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
828     WCHAR short_nameW[12];
829     UNICODE_STRING str;
830
831     long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
832     if (long_len == -1) return NULL;
833
834     str.Buffer = long_nameW;
835     str.Length = long_len * sizeof(WCHAR);
836     str.MaximumLength = sizeof(long_nameW);
837
838     if (short_name)
839     {
840         short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
841                                      short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
842         if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
843     }
844     else  /* generate a short name if necessary */
845     {
846         BOOLEAN spaces;
847
848         short_len = 0;
849         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
850             short_len = hash_short_file_name( &str, short_nameW );
851     }
852
853     TRACE( "long %s short %s mask %s\n",
854            debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
855
856     if (mask && !match_filename( &str, mask ))
857     {
858         if (!short_len) return NULL;  /* no short name to match */
859         str.Buffer = short_nameW;
860         str.Length = short_len * sizeof(WCHAR);
861         str.MaximumLength = sizeof(short_nameW);
862         if (!match_filename( &str, mask )) return NULL;
863     }
864
865     total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
866     info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
867
868     if (*pos + total_len > max_length) total_len = max_length - *pos;
869
870     info->FileAttributes = 0;
871     if (lstat( long_name, &st ) == -1) return NULL;
872     if (S_ISLNK( st.st_mode ))
873     {
874         if (stat( long_name, &st ) == -1) return NULL;
875         if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
876     }
877
878     info->NextEntryOffset = total_len;
879     info->FileIndex = 0;  /* NTFS always has 0 here, so let's not bother with it */
880
881     RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
882     RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
883     RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
884     RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
885
886     if (S_ISDIR(st.st_mode))
887     {
888         info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
889         info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
890     }
891     else
892     {
893         info->EndOfFile.QuadPart = st.st_size;
894         info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
895         info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
896     }
897
898     if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
899         info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
900
901     if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
902         info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
903
904     info->EaSize = 0; /* FIXME */
905     info->ShortNameLength = short_len * sizeof(WCHAR);
906     for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
907     info->FileNameLength = long_len * sizeof(WCHAR);
908     memcpy( info->FileName, long_nameW,
909             min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
910
911     *pos += total_len;
912     return info;
913 }
914
915
916 #ifdef VFAT_IOCTL_READDIR_BOTH
917
918 /***********************************************************************
919  *           start_vfat_ioctl
920  *
921  * Wrapper for the VFAT ioctl to work around various kernel bugs.
922  * dir_section must be held by caller.
923  */
924 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
925 {
926     static KERNEL_DIRENT *de;
927     int res;
928
929     if (!de)
930     {
931         const size_t page_size = getpagesize();
932         SIZE_T size = 2 * sizeof(*de) + page_size;
933         void *addr = NULL;
934
935         if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
936             return NULL;
937         /* commit only the size needed for the dir entries */
938         /* this leaves an extra unaccessible page, which should make the kernel */
939         /* fail with -EFAULT before it stomps all over our memory */
940         de = addr;
941         size = 2 * sizeof(*de);
942         NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
943     }
944
945     /* set d_reclen to 65535 to work around an AFS kernel bug */
946     de[0].d_reclen = 65535;
947     res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
948     if (res == -1)
949     {
950         if (errno != ENOENT) return NULL;  /* VFAT ioctl probably not supported */
951         de[0].d_reclen = 0;  /* eof */
952     }
953     else if (!res && de[0].d_reclen == 65535) return NULL;  /* AFS bug */
954
955     return de;
956 }
957
958
959 /***********************************************************************
960  *           read_directory_vfat
961  *
962  * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
963  */
964 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
965                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
966                                 BOOLEAN restart_scan )
967
968 {
969     size_t len;
970     KERNEL_DIRENT *de;
971     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
972
973     io->u.Status = STATUS_SUCCESS;
974
975     if (restart_scan) lseek( fd, 0, SEEK_SET );
976
977     if (length < max_dir_info_size)  /* we may have to return a partial entry here */
978     {
979         off_t old_pos = lseek( fd, 0, SEEK_CUR );
980
981         if (!(de = start_vfat_ioctl( fd ))) return -1;  /* not supported */
982
983         while (de[0].d_reclen)
984         {
985             /* make sure names are null-terminated to work around an x86-64 kernel bug */
986             len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
987             de[0].d_name[len] = 0;
988             len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
989             de[1].d_name[len] = 0;
990
991             if (de[1].d_name[0])
992                 info = append_entry( buffer, &io->Information, length,
993                                      de[1].d_name, de[0].d_name, mask );
994             else
995                 info = append_entry( buffer, &io->Information, length,
996                                      de[0].d_name, NULL, mask );
997             if (info)
998             {
999                 last_info = info;
1000                 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1001                 {
1002                     io->u.Status = STATUS_BUFFER_OVERFLOW;
1003                     lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
1004                 }
1005                 break;
1006             }
1007             old_pos = lseek( fd, 0, SEEK_CUR );
1008             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1009         }
1010     }
1011     else  /* we'll only return full entries, no need to worry about overflow */
1012     {
1013         if (!(de = start_vfat_ioctl( fd ))) return -1;  /* not supported */
1014
1015         while (de[0].d_reclen)
1016         {
1017             /* make sure names are null-terminated to work around an x86-64 kernel bug */
1018             len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1019             de[0].d_name[len] = 0;
1020             len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1021             de[1].d_name[len] = 0;
1022
1023             if (de[1].d_name[0])
1024                 info = append_entry( buffer, &io->Information, length,
1025                                      de[1].d_name, de[0].d_name, mask );
1026             else
1027                 info = append_entry( buffer, &io->Information, length,
1028                                      de[0].d_name, NULL, mask );
1029             if (info)
1030             {
1031                 last_info = info;
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             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1037         }
1038     }
1039
1040     if (last_info) last_info->NextEntryOffset = 0;
1041     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1042     return 0;
1043 }
1044 #endif /* VFAT_IOCTL_READDIR_BOTH */
1045
1046
1047 /***********************************************************************
1048  *           read_directory_getdents
1049  *
1050  * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1051  */
1052 #ifdef USE_GETDENTS
1053 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1054                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
1055                                     BOOLEAN restart_scan )
1056 {
1057     off_t old_pos = 0;
1058     size_t size = length;
1059     int res, fake_dot_dot = 1;
1060     char *data, local_buffer[8192];
1061     KERNEL_DIRENT64 *de;
1062     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1063
1064     if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1065     {
1066         size = sizeof(local_buffer);
1067         data = local_buffer;
1068     }
1069
1070     if (restart_scan) lseek( fd, 0, SEEK_SET );
1071     else if (length < max_dir_info_size)  /* we may have to return a partial entry here */
1072     {
1073         old_pos = lseek( fd, 0, SEEK_CUR );
1074         if (old_pos == -1 && errno == ENOENT)
1075         {
1076             io->u.Status = STATUS_NO_MORE_FILES;
1077             res = 0;
1078             goto done;
1079         }
1080     }
1081
1082     io->u.Status = STATUS_SUCCESS;
1083
1084     res = getdents64( fd, data, size );
1085     if (res == -1)
1086     {
1087         if (errno != ENOSYS)
1088         {
1089             io->u.Status = FILE_GetNtStatus();
1090             res = 0;
1091         }
1092         goto done;
1093     }
1094
1095     de = (KERNEL_DIRENT64 *)data;
1096
1097     if (restart_scan)
1098     {
1099         /* check if we got . and .. from getdents */
1100         if (res > 0)
1101         {
1102             if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1103             {
1104                 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1105                 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1106             }
1107         }
1108         /* make sure we have enough room for both entries */
1109         if (fake_dot_dot)
1110         {
1111             static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1112                                                 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1113             if (length < min_info_size || single_entry)
1114             {
1115                 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1116                 fake_dot_dot = 0;
1117             }
1118         }
1119
1120         if (fake_dot_dot)
1121         {
1122             if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1123                 last_info = info;
1124             if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1125                 last_info = info;
1126
1127             /* check if we still have enough space for the largest possible entry */
1128             if (last_info && io->Information + max_dir_info_size > length)
1129             {
1130                 lseek( fd, 0, SEEK_SET );  /* reset pos to first entry */
1131                 res = 0;
1132             }
1133         }
1134     }
1135
1136     while (res > 0)
1137     {
1138         res -= de->d_reclen;
1139         if (!(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1140             (info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask )))
1141         {
1142             last_info = info;
1143             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1144             {
1145                 io->u.Status = STATUS_BUFFER_OVERFLOW;
1146                 lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
1147                 break;
1148             }
1149             /* check if we still have enough space for the largest possible entry */
1150             if (single_entry || io->Information + max_dir_info_size > length)
1151             {
1152                 if (res > 0) lseek( fd, de->d_off, SEEK_SET );  /* set pos to next entry */
1153                 break;
1154             }
1155         }
1156         old_pos = de->d_off;
1157         /* move on to the next entry */
1158         if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1159         else
1160         {
1161             res = getdents64( fd, data, size );
1162             de = (KERNEL_DIRENT64 *)data;
1163         }
1164     }
1165
1166     if (last_info) last_info->NextEntryOffset = 0;
1167     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1168     res = 0;
1169 done:
1170     if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1171     return res;
1172 }
1173
1174 #elif defined HAVE_GETDIRENTRIES
1175
1176 /***********************************************************************
1177  *           read_directory_getdirentries
1178  *
1179  * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1180  */
1181 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1182                                          BOOLEAN single_entry, const UNICODE_STRING *mask,
1183                                          BOOLEAN restart_scan )
1184 {
1185     long restart_pos;
1186     ULONG_PTR restart_info_pos = 0;
1187     size_t size, initial_size = length;
1188     int res, fake_dot_dot = 1;
1189     char *data, local_buffer[8192];
1190     struct dirent *de;
1191     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL, *restart_last_info = NULL;
1192
1193     size = initial_size;
1194     data = local_buffer;
1195     if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1196     {
1197         io->u.Status = STATUS_NO_MEMORY;
1198         return io->u.Status;
1199     }
1200
1201     if (restart_scan) lseek( fd, 0, SEEK_SET );
1202
1203     io->u.Status = STATUS_SUCCESS;
1204
1205     /* FIXME: should make sure size is larger than filesystem block size */
1206     res = getdirentries( fd, data, size, &restart_pos );
1207     if (res == -1)
1208     {
1209         io->u.Status = FILE_GetNtStatus();
1210         res = 0;
1211         goto done;
1212     }
1213
1214     de = (struct dirent *)data;
1215
1216     if (restart_scan)
1217     {
1218         /* check if we got . and .. from getdirentries */
1219         if (res > 0)
1220         {
1221             if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1222             {
1223                 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1224                 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1225             }
1226         }
1227         /* make sure we have enough room for both entries */
1228         if (fake_dot_dot)
1229         {
1230             static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1231                                                 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1232             if (length < min_info_size || single_entry)
1233             {
1234                 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1235                 fake_dot_dot = 0;
1236             }
1237         }
1238
1239         if (fake_dot_dot)
1240         {
1241             if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1242                 last_info = info;
1243             if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1244                 last_info = info;
1245
1246             restart_last_info = last_info;
1247             restart_info_pos = io->Information;
1248
1249             /* check if we still have enough space for the largest possible entry */
1250             if (last_info && io->Information + max_dir_info_size > length)
1251             {
1252                 lseek( fd, 0, SEEK_SET );  /* reset pos to first entry */
1253                 res = 0;
1254             }
1255         }
1256     }
1257
1258     while (res > 0)
1259     {
1260         res -= de->d_reclen;
1261         if (de->d_fileno &&
1262             !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1263             ((info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask ))))
1264         {
1265             last_info = info;
1266             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1267             {
1268                 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1269                 if (restart_info_pos)  /* if we have a complete read already, return it */
1270                 {
1271                     io->Information = restart_info_pos;
1272                     last_info = restart_last_info;
1273                     break;
1274                 }
1275                 /* otherwise restart from the start with a smaller size */
1276                 size = (char *)de - data;
1277                 if (!size)
1278                 {
1279                     io->u.Status = STATUS_BUFFER_OVERFLOW;
1280                     break;
1281                 }
1282                 io->Information = 0;
1283                 last_info = NULL;
1284                 goto restart;
1285             }
1286             /* if we have to return but the buffer contains more data, restart with a smaller size */
1287             if (res > 0 && (single_entry || io->Information + max_dir_info_size > length))
1288             {
1289                 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1290                 size = (char *)de - data;
1291                 io->Information = restart_info_pos;
1292                 last_info = restart_last_info;
1293                 goto restart;
1294             }
1295         }
1296         /* move on to the next entry */
1297         if (res > 0)
1298         {
1299             de = (struct dirent *)((char *)de + de->d_reclen);
1300             continue;
1301         }
1302         if (size < initial_size) break;  /* already restarted once, give up now */
1303         size = min( size, length - io->Information );
1304         /* if size is too small don't bother to continue */
1305         if (size < max_dir_info_size && last_info) break;
1306         restart_last_info = last_info;
1307         restart_info_pos = io->Information;
1308     restart:
1309         res = getdirentries( fd, data, size, &restart_pos );
1310         de = (struct dirent *)data;
1311     }
1312
1313     if (last_info) last_info->NextEntryOffset = 0;
1314     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1315     res = 0;
1316 done:
1317     if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1318     return res;
1319 }
1320 #endif  /* HAVE_GETDIRENTRIES */
1321
1322
1323 /***********************************************************************
1324  *           read_directory_readdir
1325  *
1326  * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1327  */
1328 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1329                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
1330                                     BOOLEAN restart_scan )
1331 {
1332     DIR *dir;
1333     off_t i, old_pos = 0;
1334     struct dirent *de;
1335     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1336
1337     if (!(dir = opendir( "." )))
1338     {
1339         io->u.Status = FILE_GetNtStatus();
1340         return;
1341     }
1342
1343     if (!restart_scan)
1344     {
1345         old_pos = lseek( fd, 0, SEEK_CUR );
1346         /* skip the right number of entries */
1347         for (i = 0; i < old_pos - 2; i++)
1348         {
1349             if (!readdir( dir ))
1350             {
1351                 closedir( dir );
1352                 io->u.Status = STATUS_NO_MORE_FILES;
1353                 return;
1354             }
1355         }
1356     }
1357     io->u.Status = STATUS_SUCCESS;
1358
1359     for (;;)
1360     {
1361         if (old_pos == 0)
1362             info = append_entry( buffer, &io->Information, length, ".", NULL, mask );
1363         else if (old_pos == 1)
1364             info = append_entry( buffer, &io->Information, length, "..", NULL, mask );
1365         else if ((de = readdir( dir )))
1366         {
1367             if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1368                 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1369             else
1370                 info = NULL;
1371         }
1372         else
1373             break;
1374         old_pos++;
1375         if (info)
1376         {
1377             last_info = info;
1378             if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1379             {
1380                 io->u.Status = STATUS_BUFFER_OVERFLOW;
1381                 old_pos--;  /* restore pos to previous entry */
1382                 break;
1383             }
1384             if (single_entry) break;
1385             /* check if we still have enough space for the largest possible entry */
1386             if (io->Information + max_dir_info_size > length) break;
1387         }
1388     }
1389
1390     lseek( fd, old_pos, SEEK_SET );  /* store dir offset as filepos for fd */
1391     closedir( dir );
1392
1393     if (last_info) last_info->NextEntryOffset = 0;
1394     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1395 }
1396
1397 /***********************************************************************
1398  *           read_directory_stat
1399  *
1400  * Read a single file from a directory by determining whether the file
1401  * identified by mask exists using stat.
1402  */
1403 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1404                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
1405                                 BOOLEAN restart_scan )
1406 {
1407     int unix_len, ret, used_default;
1408     char *unix_name;
1409     struct stat st;
1410
1411     TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1412
1413     unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1414     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1415     {
1416         io->u.Status = STATUS_NO_MEMORY;
1417         return 0;
1418     }
1419     ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1420                            NULL, &used_default );
1421     if (ret > 0 && !used_default)
1422     {
1423         unix_name[ret] = 0;
1424         if (restart_scan)
1425         {
1426             lseek( fd, 0, SEEK_SET );
1427         }
1428         else if (lseek( fd, 0, SEEK_CUR ) != 0)
1429         {
1430             io->u.Status = STATUS_NO_MORE_FILES;
1431             ret = 0;
1432             goto done;
1433         }
1434
1435         ret = stat( unix_name, &st );
1436         if (!ret)
1437         {
1438             FILE_BOTH_DIR_INFORMATION *info = append_entry( buffer, &io->Information, length, unix_name, NULL, mask );
1439             if (info)
1440             {
1441                 info->NextEntryOffset = 0;
1442                 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1443                     io->u.Status = STATUS_BUFFER_OVERFLOW;
1444                 else
1445                     lseek( fd, 1, SEEK_CUR );
1446             }
1447         }
1448     }
1449     else ret = -1;
1450
1451 done:
1452     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1453
1454     TRACE("returning %d\n", ret);
1455
1456     return ret;
1457 }
1458
1459
1460 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1461 {
1462     const WCHAR *end;
1463     for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1464     return NULL;
1465 }
1466
1467 /******************************************************************************
1468  *  NtQueryDirectoryFile        [NTDLL.@]
1469  *  ZwQueryDirectoryFile        [NTDLL.@]
1470  */
1471 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1472                                       PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1473                                       PIO_STATUS_BLOCK io,
1474                                       PVOID buffer, ULONG length,
1475                                       FILE_INFORMATION_CLASS info_class,
1476                                       BOOLEAN single_entry,
1477                                       PUNICODE_STRING mask,
1478                                       BOOLEAN restart_scan )
1479 {
1480     int cwd, fd, needs_close;
1481     static const WCHAR wszWildcards[] = { '*','?',0 };
1482
1483     TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1484           handle, event, apc_routine, apc_context, io, buffer,
1485           length, info_class, single_entry, debugstr_us(mask),
1486           restart_scan);
1487
1488     if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1489
1490     if (event || apc_routine)
1491     {
1492         FIXME( "Unsupported yet option\n" );
1493         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1494     }
1495     if (info_class != FileBothDirectoryInformation)
1496     {
1497         FIXME( "Unsupported file info class %d\n", info_class );
1498         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1499     }
1500
1501     if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1502         return io->u.Status;
1503
1504     io->Information = 0;
1505
1506     RtlEnterCriticalSection( &dir_section );
1507
1508     if (show_dot_files == -1) init_options();
1509
1510     cwd = open( ".", O_RDONLY );
1511     if (fchdir( fd ) != -1)
1512     {
1513 #ifdef VFAT_IOCTL_READDIR_BOTH
1514         if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1515             goto done;
1516 #endif
1517         if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1518             read_directory_stat( fd, io, buffer, length, single_entry, mask, restart_scan ) != -1)
1519             goto done;
1520 #ifdef USE_GETDENTS
1521         if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1522             goto done;
1523 #elif defined HAVE_GETDIRENTRIES
1524         if ((read_directory_getdirentries( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1525             goto done;
1526 #endif
1527         read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1528
1529     done:
1530         if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1531     }
1532     else io->u.Status = FILE_GetNtStatus();
1533
1534     RtlLeaveCriticalSection( &dir_section );
1535
1536     if (needs_close) close( fd );
1537     if (cwd != -1) close( cwd );
1538     TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1539     return io->u.Status;
1540 }
1541
1542
1543 /***********************************************************************
1544  *           find_file_in_dir
1545  *
1546  * Find a file in a directory the hard way, by doing a case-insensitive search.
1547  * The file found is appended to unix_name at pos.
1548  * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1549  */
1550 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1551                                   int check_case )
1552 {
1553     WCHAR buffer[MAX_DIR_ENTRY_LEN];
1554     UNICODE_STRING str;
1555     BOOLEAN spaces;
1556     DIR *dir;
1557     struct dirent *de;
1558     struct stat st;
1559     int ret, used_default, is_name_8_dot_3;
1560
1561     /* try a shortcut for this directory */
1562
1563     unix_name[pos++] = '/';
1564     ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1565                            NULL, &used_default );
1566     /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1567     /* so it cannot match the file we are looking for */
1568     if (ret >= 0 && !used_default)
1569     {
1570         unix_name[pos + ret] = 0;
1571         if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1572     }
1573     if (check_case) goto not_found;  /* we want an exact match */
1574
1575     if (pos > 1) unix_name[pos - 1] = 0;
1576     else unix_name[1] = 0;  /* keep the initial slash */
1577
1578     /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1579
1580     str.Buffer = (WCHAR *)name;
1581     str.Length = length * sizeof(WCHAR);
1582     str.MaximumLength = str.Length;
1583     is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1584
1585     /* now look for it through the directory */
1586
1587 #ifdef VFAT_IOCTL_READDIR_BOTH
1588     if (is_name_8_dot_3)
1589     {
1590         int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1591         if (fd != -1)
1592         {
1593             KERNEL_DIRENT *de;
1594
1595             RtlEnterCriticalSection( &dir_section );
1596             if ((de = start_vfat_ioctl( fd )))
1597             {
1598                 unix_name[pos - 1] = '/';
1599                 while (de[0].d_reclen)
1600                 {
1601                     /* make sure names are null-terminated to work around an x86-64 kernel bug */
1602                     size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1603                     de[0].d_name[len] = 0;
1604                     len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1605                     de[1].d_name[len] = 0;
1606
1607                     if (de[1].d_name[0])
1608                     {
1609                         ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1610                                                buffer, MAX_DIR_ENTRY_LEN );
1611                         if (ret == length && !memicmpW( buffer, name, length))
1612                         {
1613                             strcpy( unix_name + pos, de[1].d_name );
1614                             RtlLeaveCriticalSection( &dir_section );
1615                             close( fd );
1616                             return STATUS_SUCCESS;
1617                         }
1618                     }
1619                     ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1620                                            buffer, MAX_DIR_ENTRY_LEN );
1621                     if (ret == length && !memicmpW( buffer, name, length))
1622                     {
1623                         strcpy( unix_name + pos,
1624                                 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1625                         RtlLeaveCriticalSection( &dir_section );
1626                         close( fd );
1627                         return STATUS_SUCCESS;
1628                     }
1629                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1630                     {
1631                         RtlLeaveCriticalSection( &dir_section );
1632                         close( fd );
1633                         goto not_found;
1634                     }
1635                 }
1636             }
1637             RtlLeaveCriticalSection( &dir_section );
1638             close( fd );
1639         }
1640         /* fall through to normal handling */
1641     }
1642 #endif /* VFAT_IOCTL_READDIR_BOTH */
1643
1644     if (!(dir = opendir( unix_name )))
1645     {
1646         if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1647         else return FILE_GetNtStatus();
1648     }
1649     unix_name[pos - 1] = '/';
1650     str.Buffer = buffer;
1651     str.MaximumLength = sizeof(buffer);
1652     while ((de = readdir( dir )))
1653     {
1654         ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1655         if (ret == length && !memicmpW( buffer, name, length ))
1656         {
1657             strcpy( unix_name + pos, de->d_name );
1658             closedir( dir );
1659             return STATUS_SUCCESS;
1660         }
1661
1662         if (!is_name_8_dot_3) continue;
1663
1664         str.Length = ret * sizeof(WCHAR);
1665         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1666         {
1667             WCHAR short_nameW[12];
1668             ret = hash_short_file_name( &str, short_nameW );
1669             if (ret == length && !memicmpW( short_nameW, name, length ))
1670             {
1671                 strcpy( unix_name + pos, de->d_name );
1672                 closedir( dir );
1673                 return STATUS_SUCCESS;
1674             }
1675         }
1676     }
1677     closedir( dir );
1678     goto not_found;  /* avoid warning */
1679
1680 not_found:
1681     unix_name[pos - 1] = 0;
1682     return STATUS_OBJECT_PATH_NOT_FOUND;
1683 }
1684
1685
1686 /******************************************************************************
1687  *           get_dos_device
1688  *
1689  * Get the Unix path of a DOS device.
1690  */
1691 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1692 {
1693     const char *config_dir = wine_get_config_dir();
1694     struct stat st;
1695     char *unix_name, *new_name, *dev;
1696     unsigned int i;
1697     int unix_len;
1698
1699     /* make sure the device name is ASCII */
1700     for (i = 0; i < name_len; i++)
1701         if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1702
1703     unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1704
1705     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1706         return STATUS_NO_MEMORY;
1707
1708     strcpy( unix_name, config_dir );
1709     strcat( unix_name, "/dosdevices/" );
1710     dev = unix_name + strlen(unix_name);
1711
1712     for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1713     dev[i] = 0;
1714
1715     /* special case for drive devices */
1716     if (name_len == 2 && dev[1] == ':')
1717     {
1718         dev[i++] = ':';
1719         dev[i] = 0;
1720     }
1721
1722     for (;;)
1723     {
1724         if (!stat( unix_name, &st ))
1725         {
1726             TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1727             unix_name_ret->Buffer = unix_name;
1728             unix_name_ret->Length = strlen(unix_name);
1729             unix_name_ret->MaximumLength = unix_len;
1730             return STATUS_SUCCESS;
1731         }
1732         if (!dev) break;
1733
1734         /* now try some defaults for it */
1735         if (!strcmp( dev, "aux" ))
1736         {
1737             strcpy( dev, "com1" );
1738             continue;
1739         }
1740         if (!strcmp( dev, "prn" ))
1741         {
1742             strcpy( dev, "lpt1" );
1743             continue;
1744         }
1745         if (!strcmp( dev, "nul" ))
1746         {
1747             strcpy( unix_name, "/dev/null" );
1748             dev = NULL; /* last try */
1749             continue;
1750         }
1751
1752         new_name = NULL;
1753         if (dev[1] == ':' && dev[2] == ':')  /* drive device */
1754         {
1755             dev[2] = 0;  /* remove last ':' to get the drive mount point symlink */
1756             new_name = get_default_drive_device( unix_name );
1757         }
1758         else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1759         else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1760
1761         if (!new_name) break;
1762
1763         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1764         unix_name = new_name;
1765         unix_len = strlen(unix_name) + 1;
1766         dev = NULL; /* last try */
1767     }
1768     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1769     return STATUS_BAD_DEVICE_TYPE;
1770 }
1771
1772
1773 /* return the length of the DOS namespace prefix if any */
1774 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1775 {
1776     static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1777     static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1778
1779     if (name->Length > sizeof(nt_prefixW) &&
1780         !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1781         return sizeof(nt_prefixW) / sizeof(WCHAR);
1782
1783     if (name->Length > sizeof(dosdev_prefixW) &&
1784         !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1785         return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1786
1787     return 0;
1788 }
1789
1790
1791 /******************************************************************************
1792  *           wine_nt_to_unix_file_name  (NTDLL.@) Not a Windows API
1793  *
1794  * Convert a file name from NT namespace to Unix namespace.
1795  *
1796  * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1797  * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1798  * returned, but the unix name is still filled in properly.
1799  */
1800 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1801                                     UINT disposition, BOOLEAN check_case )
1802 {
1803     static const WCHAR unixW[] = {'u','n','i','x'};
1804     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1805
1806     NTSTATUS status = STATUS_SUCCESS;
1807     const char *config_dir = wine_get_config_dir();
1808     const WCHAR *name, *p;
1809     struct stat st;
1810     char *unix_name;
1811     int pos, ret, name_len, unix_len, prefix_len, used_default;
1812     WCHAR prefix[MAX_DIR_ENTRY_LEN];
1813     BOOLEAN is_unix = FALSE;
1814
1815     name     = nameW->Buffer;
1816     name_len = nameW->Length / sizeof(WCHAR);
1817
1818     if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1819
1820     if (!(pos = get_dos_prefix_len( nameW )))
1821         return STATUS_BAD_DEVICE_TYPE;  /* no DOS prefix, assume NT native name */
1822
1823     name += pos;
1824     name_len -= pos;
1825
1826     /* check for sub-directory */
1827     for (pos = 0; pos < name_len; pos++)
1828     {
1829         if (IS_SEPARATOR(name[pos])) break;
1830         if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
1831             return STATUS_OBJECT_NAME_INVALID;
1832     }
1833     if (pos > MAX_DIR_ENTRY_LEN)
1834         return STATUS_OBJECT_NAME_INVALID;
1835
1836     if (pos == name_len)  /* no subdir, plain DOS device */
1837         return get_dos_device( name, name_len, unix_name_ret );
1838
1839     for (prefix_len = 0; prefix_len < pos; prefix_len++)
1840         prefix[prefix_len] = tolowerW(name[prefix_len]);
1841
1842     name += prefix_len;
1843     name_len -= prefix_len;
1844
1845     /* check for invalid characters (all chars except 0 are valid for unix) */
1846     is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
1847     if (is_unix)
1848     {
1849         for (p = name; p < name + name_len; p++)
1850             if (!*p) return STATUS_OBJECT_NAME_INVALID;
1851         check_case = TRUE;
1852     }
1853     else
1854     {
1855         for (p = name; p < name + name_len; p++)
1856             if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1857     }
1858
1859     unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
1860     unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1861     unix_len += MAX_DIR_ENTRY_LEN + 3;
1862     unix_len += strlen(config_dir) + sizeof("/dosdevices/");
1863     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1864         return STATUS_NO_MEMORY;
1865     strcpy( unix_name, config_dir );
1866     strcat( unix_name, "/dosdevices/" );
1867     pos = strlen(unix_name);
1868
1869     ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
1870                            NULL, &used_default );
1871     if (!ret || used_default)
1872     {
1873         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1874         return STATUS_OBJECT_NAME_INVALID;
1875     }
1876     pos += ret;
1877
1878     /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
1879
1880     if (prefix_len != 2 || prefix[1] != ':')
1881     {
1882         unix_name[pos] = 0;
1883         if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
1884         {
1885             if (!is_unix)
1886             {
1887                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1888                 return STATUS_BAD_DEVICE_TYPE;
1889             }
1890             pos = 0;  /* fall back to unix root */
1891         }
1892     }
1893
1894     /* try a shortcut first */
1895
1896     ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1897                            NULL, &used_default );
1898
1899     while (name_len && IS_SEPARATOR(*name))
1900     {
1901         name++;
1902         name_len--;
1903     }
1904
1905     if (ret > 0 && !used_default)  /* if we used the default char the name didn't convert properly */
1906     {
1907         char *p;
1908         unix_name[pos + ret] = 0;
1909         for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1910         if (!stat( unix_name, &st ))
1911         {
1912             /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1913             if (disposition == FILE_CREATE)
1914             {
1915                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1916                 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1917             }
1918             goto done;
1919         }
1920     }
1921
1922     if (!name_len)  /* empty name -> drive root doesn't exist */
1923     {
1924         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1925         return STATUS_OBJECT_PATH_NOT_FOUND;
1926     }
1927     if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1928     {
1929         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1930         return STATUS_OBJECT_NAME_NOT_FOUND;
1931     }
1932
1933     /* now do it component by component */
1934
1935     while (name_len)
1936     {
1937         const WCHAR *end, *next;
1938
1939         end = name;
1940         while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1941         next = end;
1942         while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1943         name_len -= next - name;
1944
1945         /* grow the buffer if needed */
1946
1947         if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1948         {
1949             char *new_name;
1950             unix_len += 2 * MAX_DIR_ENTRY_LEN;
1951             if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1952             {
1953                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1954                 return STATUS_NO_MEMORY;
1955             }
1956             unix_name = new_name;
1957         }
1958
1959         status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1960
1961         /* if this is the last element, not finding it is not necessarily fatal */
1962         if (!name_len)
1963         {
1964             if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1965             {
1966                 status = STATUS_OBJECT_NAME_NOT_FOUND;
1967                 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1968                 {
1969                     ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1970                                            MAX_DIR_ENTRY_LEN, NULL, &used_default );
1971                     if (ret > 0 && !used_default)
1972                     {
1973                         unix_name[pos] = '/';
1974                         unix_name[pos + 1 + ret] = 0;
1975                         status = STATUS_NO_SUCH_FILE;
1976                         break;
1977                     }
1978                 }
1979             }
1980             else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1981             {
1982                 status = STATUS_OBJECT_NAME_COLLISION;
1983             }
1984         }
1985
1986         if (status != STATUS_SUCCESS)
1987         {
1988             /* couldn't find it at all, fail */
1989             WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1990             RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1991             return status;
1992         }
1993
1994         pos += strlen( unix_name + pos );
1995         name = next;
1996     }
1997
1998     WARN( "%s -> %s required a case-insensitive search\n",
1999           debugstr_us(nameW), debugstr_a(unix_name) );
2000
2001 done:
2002     TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2003     unix_name_ret->Buffer = unix_name;
2004     unix_name_ret->Length = strlen(unix_name);
2005     unix_name_ret->MaximumLength = unix_len;
2006     return status;
2007 }
2008
2009
2010 /******************************************************************
2011  *              RtlDoesFileExists_U   (NTDLL.@)
2012  */
2013 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2014 {
2015     UNICODE_STRING nt_name;
2016     ANSI_STRING unix_name;
2017     BOOLEAN ret;
2018
2019     if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2020     ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
2021     if (ret) RtlFreeAnsiString( &unix_name );
2022     RtlFreeUnicodeString( &nt_name );
2023     return ret;
2024 }
2025
2026
2027 /***********************************************************************
2028  *           DIR_unmount_device
2029  *
2030  * Unmount the specified device.
2031  */
2032 NTSTATUS DIR_unmount_device( HANDLE handle )
2033 {
2034     NTSTATUS status;
2035     int unix_fd, needs_close;
2036
2037     SERVER_START_REQ( unmount_device )
2038     {
2039         req->handle = handle;
2040         status = wine_server_call( req );
2041     }
2042     SERVER_END_REQ;
2043     if (status) return status;
2044
2045     if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2046     {
2047         struct stat st;
2048         char *mount_point = NULL;
2049
2050         if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2051             status = STATUS_INVALID_PARAMETER;
2052         else
2053         {
2054             if ((mount_point = get_device_mount_point( st.st_rdev )))
2055             {
2056 #ifdef __APPLE__
2057                 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2058 #else
2059                 static const char umount[] = "umount >/dev/null 2>&1 ";
2060 #endif
2061                 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2062                 if (cmd)
2063                 {
2064                     strcpy( cmd, umount );
2065                     strcat( cmd, mount_point );
2066                     system( cmd );
2067                     RtlFreeHeap( GetProcessHeap(), 0, cmd );
2068 #ifdef linux
2069                     /* umount will fail to release the loop device since we still have
2070                        a handle to it, so we release it here */
2071                     if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2072 #endif
2073                 }
2074                 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2075             }
2076         }
2077         if (needs_close) close( unix_fd );
2078     }
2079     return status;
2080 }
2081
2082
2083 /******************************************************************************
2084  *           DIR_get_unix_cwd
2085  *
2086  * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2087  * Returned value must be freed by caller.
2088  */
2089 NTSTATUS DIR_get_unix_cwd( char **cwd )
2090 {
2091     int old_cwd, unix_fd, needs_close;
2092     CURDIR *curdir;
2093     HANDLE handle;
2094     NTSTATUS status;
2095
2096     RtlAcquirePebLock();
2097
2098     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
2099         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2100     else
2101         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2102
2103     if (!(handle = curdir->Handle))
2104     {
2105         UNICODE_STRING dirW;
2106         OBJECT_ATTRIBUTES attr;
2107         IO_STATUS_BLOCK io;
2108
2109         if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2110         {
2111             status = STATUS_OBJECT_NAME_INVALID;
2112             goto done;
2113         }
2114         attr.Length = sizeof(attr);
2115         attr.RootDirectory = 0;
2116         attr.Attributes = OBJ_CASE_INSENSITIVE;
2117         attr.ObjectName = &dirW;
2118         attr.SecurityDescriptor = NULL;
2119         attr.SecurityQualityOfService = NULL;
2120
2121         status = NtOpenFile( &handle, 0, &attr, &io, 0,
2122                              FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2123         RtlFreeUnicodeString( &dirW );
2124         if (status != STATUS_SUCCESS) goto done;
2125     }
2126
2127     if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2128     {
2129         RtlEnterCriticalSection( &dir_section );
2130
2131         if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2132         {
2133             unsigned int size = 512;
2134
2135             for (;;)
2136             {
2137                 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2138                 {
2139                     status = STATUS_NO_MEMORY;
2140                     break;
2141                 }
2142                 if (getcwd( *cwd, size )) break;
2143                 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2144                 if (errno != ERANGE)
2145                 {
2146                     status = STATUS_OBJECT_PATH_INVALID;
2147                     break;
2148                 }
2149                 size *= 2;
2150             }
2151             if (fchdir( old_cwd ) == -1) chdir( "/" );
2152         }
2153         else status = FILE_GetNtStatus();
2154
2155         RtlLeaveCriticalSection( &dir_section );
2156         if (needs_close) close( unix_fd );
2157     }
2158     if (!curdir->Handle) NtClose( handle );
2159
2160 done:
2161     RtlReleasePebLock();
2162     return status;
2163 }
2164
2165 struct read_changes_info
2166 {
2167     HANDLE FileHandle;
2168     PVOID Buffer;
2169     ULONG BufferSize;
2170 };
2171
2172 static void WINAPI read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, ULONG status )
2173 {
2174     struct read_changes_info *info = user;
2175     char path[PATH_MAX];
2176     NTSTATUS ret = STATUS_SUCCESS;
2177     int len, action, i;
2178
2179     TRACE("%p %p %08x\n", info, iosb, status);
2180
2181     /*
2182      * FIXME: race me!
2183      *
2184      * hEvent/hDir is set before the output buffer and iosb is updated.
2185      * Since the thread that called NtNotifyChangeDirectoryFile is usually
2186      * waiting, we'll be safe since we're called in that thread's context.
2187      * If a different thread is waiting on our hEvent/hDir we're going to be
2188      * in trouble...
2189      */
2190     SERVER_START_REQ( read_change )
2191     {
2192         req->handle = info->FileHandle;
2193         wine_server_set_reply( req, path, PATH_MAX );
2194         ret = wine_server_call( req );
2195         action = reply->action;
2196         len = wine_server_reply_size( reply );
2197     }
2198     SERVER_END_REQ;
2199
2200     if (ret == STATUS_SUCCESS && info->Buffer && 
2201         (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2202     {
2203         PFILE_NOTIFY_INFORMATION pfni;
2204
2205         pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
2206
2207         /* convert to an NT style path */
2208         for (i=0; i<len; i++)
2209             if (path[i] == '/')
2210                 path[i] = '\\';
2211
2212         len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2213                                info->BufferSize - sizeof (*pfni) );
2214
2215         pfni->NextEntryOffset = 0;
2216         pfni->Action = action;
2217         pfni->FileNameLength = len * sizeof (WCHAR);
2218         pfni->FileName[len] = 0;
2219
2220         TRACE("action = %d name = %s\n", pfni->Action,
2221               debugstr_w(pfni->FileName) );
2222         len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2223     }
2224     else
2225     {
2226         ret = STATUS_NOTIFY_ENUM_DIR;
2227         len = 0;
2228     }
2229
2230     iosb->u.Status = ret;
2231     iosb->Information = len;
2232
2233     RtlFreeHeap( GetProcessHeap(), 0, info );
2234 }
2235
2236 #define FILE_NOTIFY_ALL        (  \
2237  FILE_NOTIFY_CHANGE_FILE_NAME   | \
2238  FILE_NOTIFY_CHANGE_DIR_NAME    | \
2239  FILE_NOTIFY_CHANGE_ATTRIBUTES  | \
2240  FILE_NOTIFY_CHANGE_SIZE        | \
2241  FILE_NOTIFY_CHANGE_LAST_WRITE  | \
2242  FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2243  FILE_NOTIFY_CHANGE_CREATION    | \
2244  FILE_NOTIFY_CHANGE_SECURITY   )
2245
2246 /******************************************************************************
2247  *  NtNotifyChangeDirectoryFile [NTDLL.@]
2248  */
2249 NTSTATUS WINAPI
2250 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2251         PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2252         PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2253         ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2254 {
2255     struct read_changes_info *info;
2256     NTSTATUS status;
2257
2258     TRACE("%p %p %p %p %p %p %u %u %d\n",
2259           FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2260           Buffer, BufferSize, CompletionFilter, WatchTree );
2261
2262     if (!IoStatusBlock)
2263         return STATUS_ACCESS_VIOLATION;
2264
2265     if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2266         return STATUS_INVALID_PARAMETER;
2267
2268     info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2269     if (!info)
2270         return STATUS_NO_MEMORY;
2271
2272     info->FileHandle = FileHandle;
2273     info->Buffer     = Buffer;
2274     info->BufferSize = BufferSize;
2275
2276     SERVER_START_REQ( read_directory_changes )
2277     {
2278         req->handle     = FileHandle;
2279         req->filter     = CompletionFilter;
2280         req->want_data  = (Buffer != NULL);
2281         req->subtree    = WatchTree;
2282         req->async.callback = read_changes_apc;
2283         req->async.iosb     = IoStatusBlock;
2284         req->async.arg      = info;
2285         req->async.apc      = ApcRoutine;
2286         req->async.apc_arg  = ApcContext;
2287         req->async.event    = Event;
2288         status = wine_server_call( req );
2289     }
2290     SERVER_END_REQ;
2291
2292     if (status != STATUS_PENDING)
2293         RtlFreeHeap( GetProcessHeap(), 0, info );
2294
2295     return status;
2296 }