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