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