msxml3: Store stream reference as destination.
[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 <assert.h>
27 #include <sys/types.h>
28 #ifdef HAVE_DIRENT_H
29 # include <dirent.h>
30 #endif
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <limits.h>
38 #ifdef HAVE_MNTENT_H
39 #include <mntent.h>
40 #endif
41 #ifdef HAVE_SYS_STAT_H
42 # include <sys/stat.h>
43 #endif
44 #ifdef HAVE_SYS_SYSCALL_H
45 # include <sys/syscall.h>
46 #endif
47 #ifdef HAVE_SYS_ATTR_H
48 #include <sys/attr.h>
49 #endif
50 #ifdef HAVE_SYS_IOCTL_H
51 #include <sys/ioctl.h>
52 #endif
53 #ifdef HAVE_LINUX_IOCTL_H
54 #include <linux/ioctl.h>
55 #endif
56 #ifdef HAVE_LINUX_MAJOR_H
57 # include <linux/major.h>
58 #endif
59 #ifdef HAVE_SYS_PARAM_H
60 #include <sys/param.h>
61 #endif
62 #ifdef HAVE_SYS_MOUNT_H
63 #include <sys/mount.h>
64 #endif
65 #ifdef HAVE_SYS_STATFS_H
66 #include <sys/statfs.h>
67 #endif
68 #include <time.h>
69 #ifdef HAVE_UNISTD_H
70 # include <unistd.h>
71 #endif
72
73 #define NONAMELESSUNION
74 #define NONAMELESSSTRUCT
75 #include "ntstatus.h"
76 #define WIN32_NO_STATUS
77 #include "windef.h"
78 #include "winnt.h"
79 #include "winternl.h"
80 #include "ntdll_misc.h"
81 #include "wine/unicode.h"
82 #include "wine/server.h"
83 #include "wine/list.h"
84 #include "wine/library.h"
85 #include "wine/debug.h"
86
87 WINE_DEFAULT_DEBUG_CHANNEL(file);
88
89 /* just in case... */
90 #undef VFAT_IOCTL_READDIR_BOTH
91 #undef USE_GETDENTS
92
93 #ifdef linux
94
95 /* We want the real kernel dirent structure, not the libc one */
96 typedef struct
97 {
98     long d_ino;
99     long d_off;
100     unsigned short d_reclen;
101     char d_name[256];
102 } KERNEL_DIRENT;
103
104 /* Define the VFAT ioctl to get both short and long file names */
105 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
106
107 #ifndef O_DIRECTORY
108 # define O_DIRECTORY 0200000 /* must be directory */
109 #endif
110
111 #ifdef SYS_getdents64
112 typedef struct
113 {
114     ULONG64        d_ino;
115     LONG64         d_off;
116     unsigned short d_reclen;
117     unsigned char  d_type;
118     char           d_name[256];
119 } KERNEL_DIRENT64;
120
121 static inline int getdents64( int fd, char *de, unsigned int size )
122 {
123     return syscall( SYS_getdents64, fd, de, size );
124 }
125 #define USE_GETDENTS
126 #endif
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 #define MAX_IGNORED_FILES 4
139
140 struct file_identity
141 {
142     dev_t dev;
143     ino_t ino;
144 };
145
146 static struct file_identity ignored_files[MAX_IGNORED_FILES];
147 static int ignored_files_count;
148
149 union file_directory_info
150 {
151     ULONG                              next;
152     FILE_DIRECTORY_INFORMATION         dir;
153     FILE_BOTH_DIRECTORY_INFORMATION    both;
154     FILE_FULL_DIRECTORY_INFORMATION    full;
155     FILE_ID_BOTH_DIRECTORY_INFORMATION id_both;
156     FILE_ID_FULL_DIRECTORY_INFORMATION id_full;
157 };
158
159 static int show_dot_files = -1;
160
161 /* at some point we may want to allow Winelib apps to set this */
162 static const int is_case_sensitive = FALSE;
163
164 UNICODE_STRING windows_dir = { 0, 0, NULL };  /* windows directory */
165 UNICODE_STRING system_dir = { 0, 0, NULL };  /* system directory */
166
167 static struct file_identity curdir;
168 static struct file_identity windir;
169
170 static RTL_CRITICAL_SECTION dir_section;
171 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
172 {
173     0, 0, &dir_section,
174     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
175       0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
176 };
177 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
178
179
180 /* check if a given Unicode char is OK in a DOS short name */
181 static inline BOOL is_invalid_dos_char( WCHAR ch )
182 {
183     static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
184     if (ch > 0x7f) return TRUE;
185     return strchrW( invalid_chars, ch ) != NULL;
186 }
187
188 /* check if the device can be a mounted volume */
189 static inline int is_valid_mounted_device( const struct stat *st )
190 {
191 #if defined(linux) || defined(__sun__)
192     return S_ISBLK( st->st_mode );
193 #else
194     /* disks are char devices on *BSD */
195     return S_ISCHR( st->st_mode );
196 #endif
197 }
198
199 static inline void ignore_file( const char *name )
200 {
201     struct stat st;
202     assert( ignored_files_count < MAX_IGNORED_FILES );
203     if (!stat( name, &st ))
204     {
205         ignored_files[ignored_files_count].dev = st.st_dev;
206         ignored_files[ignored_files_count].ino = st.st_ino;
207         ignored_files_count++;
208     }
209 }
210
211 static inline BOOL is_same_file( const struct file_identity *file, const struct stat *st )
212 {
213     return st->st_dev == file->dev && st->st_ino == file->ino;
214 }
215
216 static inline BOOL is_ignored_file( const struct stat *st )
217 {
218     unsigned int i;
219
220     for (i = 0; i < ignored_files_count; i++)
221         if (is_same_file( &ignored_files[i], st )) return TRUE;
222     return FALSE;
223 }
224
225 static inline unsigned int dir_info_size( FILE_INFORMATION_CLASS class, unsigned int len )
226 {
227     switch (class)
228     {
229     case FileDirectoryInformation:
230         return (FIELD_OFFSET( FILE_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
231     case FileBothDirectoryInformation:
232         return (FIELD_OFFSET( FILE_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
233     case FileFullDirectoryInformation:
234         return (FIELD_OFFSET( FILE_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
235     case FileIdBothDirectoryInformation:
236         return (FIELD_OFFSET( FILE_ID_BOTH_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
237     case FileIdFullDirectoryInformation:
238         return (FIELD_OFFSET( FILE_ID_FULL_DIRECTORY_INFORMATION, FileName[len] ) + 3) & ~3;
239     default:
240         assert(0);
241         return 0;
242     }
243 }
244
245 static inline unsigned int max_dir_info_size( FILE_INFORMATION_CLASS class )
246 {
247     return dir_info_size( class, MAX_DIR_ENTRY_LEN );
248 }
249
250
251 /* support for a directory queue for filesystem searches */
252
253 struct dir_name
254 {
255     struct list entry;
256     char name[1];
257 };
258
259 static struct list dir_queue = LIST_INIT( dir_queue );
260
261 static NTSTATUS add_dir_to_queue( const char *name )
262 {
263     int len = strlen( name ) + 1;
264     struct dir_name *dir = RtlAllocateHeap( GetProcessHeap(), 0,
265                                             FIELD_OFFSET( struct dir_name, name[len] ));
266     if (!dir) return STATUS_NO_MEMORY;
267     strcpy( dir->name, name );
268     list_add_tail( &dir_queue, &dir->entry );
269     return STATUS_SUCCESS;
270 }
271
272 static NTSTATUS next_dir_in_queue( char *name )
273 {
274     struct list *head = list_head( &dir_queue );
275     if (head)
276     {
277         struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
278         strcpy( name, dir->name );
279         list_remove( &dir->entry );
280         RtlFreeHeap( GetProcessHeap(), 0, dir );
281         return STATUS_SUCCESS;
282     }
283     return STATUS_OBJECT_NAME_NOT_FOUND;
284 }
285
286 static void flush_dir_queue(void)
287 {
288     struct list *head;
289
290     while ((head = list_head( &dir_queue )))
291     {
292         struct dir_name *dir = LIST_ENTRY( head, struct dir_name, entry );
293         list_remove( &dir->entry );
294         RtlFreeHeap( GetProcessHeap(), 0, dir );
295     }
296 }
297
298
299 /***********************************************************************
300  *           get_default_com_device
301  *
302  * Return the default device to use for serial ports.
303  */
304 static char *get_default_com_device( int num )
305 {
306     char *ret = NULL;
307
308     if (!num || num > 9) return ret;
309 #ifdef linux
310     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
311     if (ret)
312     {
313         strcpy( ret, "/dev/ttyS0" );
314         ret[strlen(ret) - 1] = '0' + num - 1;
315     }
316 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
317     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
318     if (ret)
319     {
320         strcpy( ret, "/dev/cuad0" );
321         ret[strlen(ret) - 1] = '0' + num - 1;
322     }
323 #else
324     FIXME( "no known default for device com%d\n", num );
325 #endif
326     return ret;
327 }
328
329
330 /***********************************************************************
331  *           get_default_lpt_device
332  *
333  * Return the default device to use for parallel ports.
334  */
335 static char *get_default_lpt_device( int num )
336 {
337     char *ret = NULL;
338
339     if (!num || num > 9) return ret;
340 #ifdef linux
341     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
342     if (ret)
343     {
344         strcpy( ret, "/dev/lp0" );
345         ret[strlen(ret) - 1] = '0' + num - 1;
346     }
347 #else
348     FIXME( "no known default for device lpt%d\n", num );
349 #endif
350     return ret;
351 }
352
353
354 /***********************************************************************
355  *           DIR_get_drives_info
356  *
357  * Retrieve device/inode number for all the drives. Helper for find_drive_root.
358  */
359 unsigned int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
360 {
361     static struct drive_info cache[MAX_DOS_DRIVES];
362     static time_t last_update;
363     static unsigned int nb_drives;
364     unsigned int ret;
365     time_t now = time(NULL);
366
367     RtlEnterCriticalSection( &dir_section );
368     if (now != last_update)
369     {
370         const char *config_dir = wine_get_config_dir();
371         char *buffer, *p;
372         struct stat st;
373         unsigned int i;
374
375         if ((buffer = RtlAllocateHeap( GetProcessHeap(), 0,
376                                        strlen(config_dir) + sizeof("/dosdevices/a:") )))
377         {
378             strcpy( buffer, config_dir );
379             strcat( buffer, "/dosdevices/a:" );
380             p = buffer + strlen(buffer) - 2;
381
382             for (i = nb_drives = 0; i < MAX_DOS_DRIVES; i++)
383             {
384                 *p = 'a' + i;
385                 if (!stat( buffer, &st ))
386                 {
387                     cache[i].dev = st.st_dev;
388                     cache[i].ino = st.st_ino;
389                     nb_drives++;
390                 }
391                 else
392                 {
393                     cache[i].dev = 0;
394                     cache[i].ino = 0;
395                 }
396             }
397             RtlFreeHeap( GetProcessHeap(), 0, buffer );
398         }
399         last_update = now;
400     }
401     memcpy( info, cache, sizeof(cache) );
402     ret = nb_drives;
403     RtlLeaveCriticalSection( &dir_section );
404     return ret;
405 }
406
407
408 /***********************************************************************
409  *           parse_mount_entries
410  *
411  * Parse mount entries looking for a given device. Helper for get_default_drive_device.
412  */
413
414 #ifdef sun
415 #include <sys/vfstab.h>
416 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
417 {
418     struct vfstab entry;
419     struct stat st;
420     char *device;
421
422     while (! getvfsent( f, &entry ))
423     {
424         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
425         if (!strcmp( entry.vfs_fstype, "nfs" ) ||
426             !strcmp( entry.vfs_fstype, "smbfs" ) ||
427             !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
428
429         if (stat( entry.vfs_mountp, &st ) == -1) continue;
430         if (st.st_dev != dev || st.st_ino != ino) continue;
431         if (!strcmp( entry.vfs_fstype, "fd" ))
432         {
433             if ((device = strstr( entry.vfs_mntopts, "dev=" )))
434             {
435                 char *p = strchr( device + 4, ',' );
436                 if (p) *p = 0;
437                 return device + 4;
438             }
439         }
440         else
441             return entry.vfs_special;
442     }
443     return NULL;
444 }
445 #endif
446
447 #ifdef linux
448 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
449 {
450     struct mntent *entry;
451     struct stat st;
452     char *device;
453
454     while ((entry = getmntent( f )))
455     {
456         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
457         if (!strcmp( entry->mnt_type, "nfs" ) ||
458             !strcmp( entry->mnt_type, "smbfs" ) ||
459             !strcmp( entry->mnt_type, "ncpfs" )) continue;
460
461         if (stat( entry->mnt_dir, &st ) == -1) continue;
462         if (st.st_dev != dev || st.st_ino != ino) continue;
463         if (!strcmp( entry->mnt_type, "supermount" ))
464         {
465             if ((device = strstr( entry->mnt_opts, "dev=" )))
466             {
467                 char *p = strchr( device + 4, ',' );
468                 if (p) *p = 0;
469                 return device + 4;
470             }
471         }
472         else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
473         {
474             /* if device is a regular file check for a loop mount */
475             if ((device = strstr( entry->mnt_opts, "loop=" )))
476             {
477                 char *p = strchr( device + 5, ',' );
478                 if (p) *p = 0;
479                 return device + 5;
480             }
481         }
482         else
483             return entry->mnt_fsname;
484     }
485     return NULL;
486 }
487 #endif
488
489 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
490 #include <fstab.h>
491 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
492 {
493     struct fstab *entry;
494     struct stat st;
495
496     while ((entry = getfsent()))
497     {
498         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
499         if (!strcmp( entry->fs_vfstype, "nfs" ) ||
500             !strcmp( entry->fs_vfstype, "smbfs" ) ||
501             !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
502
503         if (stat( entry->fs_file, &st ) == -1) continue;
504         if (st.st_dev != dev || st.st_ino != ino) continue;
505         return entry->fs_spec;
506     }
507     return NULL;
508 }
509 #endif
510
511 #ifdef sun
512 #include <sys/mnttab.h>
513 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
514 {
515     struct mnttab entry;
516     struct stat st;
517     char *device;
518
519
520     while (( ! getmntent( f, &entry) ))
521     {
522         /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
523         if (!strcmp( entry.mnt_fstype, "nfs" ) ||
524             !strcmp( entry.mnt_fstype, "smbfs" ) ||
525             !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
526
527         if (stat( entry.mnt_mountp, &st ) == -1) continue;
528         if (st.st_dev != dev || st.st_ino != ino) continue;
529         if (!strcmp( entry.mnt_fstype, "fd" ))
530         {
531             if ((device = strstr( entry.mnt_mntopts, "dev=" )))
532             {
533                 char *p = strchr( device + 4, ',' );
534                 if (p) *p = 0;
535                 return device + 4;
536             }
537         }
538         else
539             return entry.mnt_special;
540     }
541     return NULL;
542 }
543 #endif
544
545 /***********************************************************************
546  *           get_default_drive_device
547  *
548  * Return the default device to use for a given drive mount point.
549  */
550 static char *get_default_drive_device( const char *root )
551 {
552     char *ret = NULL;
553
554 #ifdef linux
555     FILE *f;
556     char *device = NULL;
557     int fd, res = -1;
558     struct stat st;
559
560     /* try to open it first to force it to get mounted */
561     if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
562     {
563         res = fstat( fd, &st );
564         close( fd );
565     }
566     /* now try normal stat just in case */
567     if (res == -1) res = stat( root, &st );
568     if (res == -1) return NULL;
569
570     RtlEnterCriticalSection( &dir_section );
571
572     if ((f = fopen( "/etc/mtab", "r" )))
573     {
574         device = parse_mount_entries( f, st.st_dev, st.st_ino );
575         endmntent( f );
576     }
577     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
578     if (!device && (f = fopen( "/etc/fstab", "r" )))
579     {
580         device = parse_mount_entries( f, st.st_dev, st.st_ino );
581         endmntent( f );
582     }
583     if (device)
584     {
585         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
586         if (ret) strcpy( ret, device );
587     }
588     RtlLeaveCriticalSection( &dir_section );
589
590 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
591     char *device = NULL;
592     int fd, res = -1;
593     struct stat st;
594
595     /* try to open it first to force it to get mounted */
596     if ((fd = open( root, O_RDONLY )) != -1)
597     {
598         res = fstat( fd, &st );
599         close( fd );
600     }
601     /* now try normal stat just in case */
602     if (res == -1) res = stat( root, &st );
603     if (res == -1) return NULL;
604
605     RtlEnterCriticalSection( &dir_section );
606
607     /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
608      * pass NULL.  Leave the argument in for symmetry.
609      */
610     device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
611     if (device)
612     {
613         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
614         if (ret) strcpy( ret, device );
615     }
616     RtlLeaveCriticalSection( &dir_section );
617
618 #elif defined( sun )
619     FILE *f;
620     char *device = NULL;
621     int fd, res = -1;
622     struct stat st;
623
624     /* try to open it first to force it to get mounted */
625     if ((fd = open( root, O_RDONLY )) != -1)
626     {
627         res = fstat( fd, &st );
628         close( fd );
629     }
630     /* now try normal stat just in case */
631     if (res == -1) res = stat( root, &st );
632     if (res == -1) return NULL;
633
634     RtlEnterCriticalSection( &dir_section );
635
636     if ((f = fopen( "/etc/mnttab", "r" )))
637     {
638         device = parse_mount_entries( f, st.st_dev, st.st_ino);
639         fclose( f );
640     }
641     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
642     if (!device && (f = fopen( "/etc/vfstab", "r" )))
643     {
644         device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
645         fclose( f );
646     }
647     if (device)
648     {
649         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
650         if (ret) strcpy( ret, device );
651     }
652     RtlLeaveCriticalSection( &dir_section );
653
654 #elif defined(__APPLE__)
655     struct statfs *mntStat;
656     struct stat st;
657     int i;
658     int mntSize;
659     dev_t dev;
660     ino_t ino;
661     static const char path_bsd_device[] = "/dev/disk";
662     int res;
663
664     res = stat( root, &st );
665     if (res == -1) return NULL;
666
667     dev = st.st_dev;
668     ino = st.st_ino;
669
670     RtlEnterCriticalSection( &dir_section );
671
672     mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
673
674     for (i = 0; i < mntSize && !ret; i++)
675     {
676         if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
677         if (st.st_dev != dev || st.st_ino != ino) continue;
678
679         /* FIXME add support for mounted network drive */
680         if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
681         {
682             /* set return value to the corresponding raw BSD node */
683             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
684             if (ret)
685             {
686                 strcpy(ret, "/dev/r");
687                 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
688             }
689         }
690     }
691     RtlLeaveCriticalSection( &dir_section );
692 #else
693     static int warned;
694     if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
695 #endif
696     return ret;
697 }
698
699
700 /***********************************************************************
701  *           get_device_mount_point
702  *
703  * Return the current mount point for a device.
704  */
705 static char *get_device_mount_point( dev_t dev )
706 {
707     char *ret = NULL;
708
709 #ifdef linux
710     FILE *f;
711
712     RtlEnterCriticalSection( &dir_section );
713
714     if ((f = fopen( "/etc/mtab", "r" )))
715     {
716         struct mntent *entry;
717         struct stat st;
718         char *p, *device;
719
720         while ((entry = getmntent( f )))
721         {
722             /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
723             if (!strcmp( entry->mnt_type, "nfs" ) ||
724                 !strcmp( entry->mnt_type, "smbfs" ) ||
725                 !strcmp( entry->mnt_type, "ncpfs" )) continue;
726
727             if (!strcmp( entry->mnt_type, "supermount" ))
728             {
729                 if ((device = strstr( entry->mnt_opts, "dev=" )))
730                 {
731                     device += 4;
732                     if ((p = strchr( device, ',' ))) *p = 0;
733                 }
734             }
735             else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
736             {
737                 /* if device is a regular file check for a loop mount */
738                 if ((device = strstr( entry->mnt_opts, "loop=" )))
739                 {
740                     device += 5;
741                     if ((p = strchr( device, ',' ))) *p = 0;
742                 }
743             }
744             else device = entry->mnt_fsname;
745
746             if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
747             {
748                 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
749                 if (ret) strcpy( ret, entry->mnt_dir );
750                 break;
751             }
752         }
753         endmntent( f );
754     }
755     RtlLeaveCriticalSection( &dir_section );
756 #elif defined(__APPLE__)
757     struct statfs *entry;
758     struct stat st;
759     int i, size;
760
761     RtlEnterCriticalSection( &dir_section );
762
763     size = getmntinfo( &entry, MNT_NOWAIT );
764     for (i = 0; i < size; i++)
765     {
766         if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
767         if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
768         {
769             ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
770             if (ret) strcpy( ret, entry[i].f_mntfromname );
771             break;
772         }
773     }
774     RtlLeaveCriticalSection( &dir_section );
775 #else
776     static int warned;
777     if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
778 #endif
779     return ret;
780 }
781
782
783 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
784     defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
785
786 struct get_fsid
787 {
788     ULONG size;
789     dev_t dev;
790     fsid_t fsid;
791 };
792
793 struct fs_cache
794 {
795     dev_t dev;
796     fsid_t fsid;
797     BOOLEAN case_sensitive;
798 } fs_cache[64];
799
800 struct vol_caps
801 {
802     ULONG size;
803     vol_capabilities_attr_t caps;
804 };
805
806 /***********************************************************************
807  *           look_up_fs_cache
808  *
809  * Checks if the specified file system is in the cache.
810  */
811 static struct fs_cache *look_up_fs_cache( dev_t dev )
812 {
813     int i;
814     for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
815         if (fs_cache[i].dev == dev)
816             return fs_cache+i;
817     return NULL;
818 }
819
820 /***********************************************************************
821  *           add_fs_cache
822  *
823  * Adds the specified file system to the cache.
824  */
825 static void add_fs_cache( dev_t dev, fsid_t fsid, BOOLEAN case_sensitive )
826 {
827     int i;
828     struct fs_cache *entry = look_up_fs_cache( dev );
829     static int once = 0;
830     if (entry)
831     {
832         /* Update the cache */
833         entry->fsid = fsid;
834         entry->case_sensitive = case_sensitive;
835         return;
836     }
837
838     /* Add a new entry */
839     for (i = 0; i < sizeof(fs_cache)/sizeof(fs_cache[0]); i++)
840         if (fs_cache[i].dev == 0)
841         {
842             /* This entry is empty, use it */
843             fs_cache[i].dev = dev;
844             fs_cache[i].fsid = fsid;
845             fs_cache[i].case_sensitive = case_sensitive;
846             return;
847         }
848
849     /* Cache is out of space, warn */
850     if (!once++)
851         WARN( "FS cache is out of space, expect performance problems\n" );
852 }
853
854 /***********************************************************************
855  *           get_dir_case_sensitivity_attr
856  *
857  * Checks if the volume containing the specified directory is case
858  * sensitive or not. Uses getattrlist(2).
859  */
860 static int get_dir_case_sensitivity_attr( const char *dir )
861 {
862     char *mntpoint = NULL;
863     struct attrlist attr;
864     struct vol_caps caps;
865     struct get_fsid get_fsid;
866     struct fs_cache *entry;
867
868     /* First get the FS ID of the volume */
869     attr.bitmapcount = ATTR_BIT_MAP_COUNT;
870     attr.reserved = 0;
871     attr.commonattr = ATTR_CMN_DEVID|ATTR_CMN_FSID;
872     attr.volattr = attr.dirattr = attr.fileattr = attr.forkattr = 0;
873     get_fsid.size = 0;
874     if (getattrlist( dir, &attr, &get_fsid, sizeof(get_fsid), 0 ) != 0 ||
875         get_fsid.size != sizeof(get_fsid))
876         return -1;
877     /* Try to look it up in the cache */
878     entry = look_up_fs_cache( get_fsid.dev );
879     if (entry && !memcmp( &entry->fsid, &get_fsid.fsid, sizeof(fsid_t) ))
880         /* Cache lookup succeeded */
881         return entry->case_sensitive;
882     /* Cache is stale at this point, we have to update it */
883
884     mntpoint = get_device_mount_point( get_fsid.dev );
885     /* Now look up the case-sensitivity */
886     attr.commonattr = 0;
887     attr.volattr = ATTR_VOL_INFO|ATTR_VOL_CAPABILITIES;
888     if (getattrlist( mntpoint, &attr, &caps, sizeof(caps), 0 ) < 0)
889     {
890         RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
891         add_fs_cache( get_fsid.dev, get_fsid.fsid, TRUE );
892         return TRUE;
893     }
894     RtlFreeHeap( GetProcessHeap(), 0, mntpoint );
895     if (caps.size == sizeof(caps) &&
896         (caps.caps.valid[VOL_CAPABILITIES_FORMAT] &
897          (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING)) ==
898         (VOL_CAP_FMT_CASE_SENSITIVE | VOL_CAP_FMT_CASE_PRESERVING))
899     {
900         BOOLEAN ret;
901
902         if ((caps.caps.capabilities[VOL_CAPABILITIES_FORMAT] &
903             VOL_CAP_FMT_CASE_SENSITIVE) != VOL_CAP_FMT_CASE_SENSITIVE)
904             ret = FALSE;
905         else
906             ret = TRUE;
907         /* Update the cache */
908         add_fs_cache( get_fsid.dev, get_fsid.fsid, ret );
909         return ret;
910     }
911     return FALSE;
912 }
913 #endif
914
915 /***********************************************************************
916  *           get_dir_case_sensitivity_stat
917  *
918  * Checks if the volume containing the specified directory is case
919  * sensitive or not. Uses statfs(2) or statvfs(2).
920  */
921 static BOOLEAN get_dir_case_sensitivity_stat( const char *dir )
922 {
923 #if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
924     struct statfs stfs;
925
926     if (statfs( dir, &stfs ) == -1) return FALSE;
927     /* Assume these file systems are always case insensitive on Mac OS.
928      * For FreeBSD, only assume CIOPFS is case insensitive (AFAIK, Mac OS
929      * is the only UNIX that supports case-insensitive lookup).
930      */
931     if (!strcmp( stfs.f_fstypename, "fusefs" ) &&
932         !strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
933         return FALSE;
934 #ifdef __APPLE__
935     if (!strcmp( stfs.f_fstypename, "msdos" ) ||
936         !strcmp( stfs.f_fstypename, "cd9660" ) ||
937         !strcmp( stfs.f_fstypename, "udf" ) ||
938         !strcmp( stfs.f_fstypename, "ntfs" ) ||
939         !strcmp( stfs.f_fstypename, "smbfs" ))
940         return FALSE;
941 #ifdef _DARWIN_FEATURE_64_BIT_INODE
942      if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_fssubtype == 0 ||
943                                                  stfs.f_fssubtype == 1 ||
944                                                  stfs.f_fssubtype == 128))
945         return FALSE;
946 #else
947      /* The field says "reserved", but a quick look at the kernel source
948       * tells us that this "reserved" field is really the same as the
949       * "fssubtype" field from the inode64 structure (see munge_statfs()
950       * in <xnu-source>/bsd/vfs/vfs_syscalls.c).
951       */
952      if (!strcmp( stfs.f_fstypename, "hfs" ) && (stfs.f_reserved1 == 0 ||
953                                                  stfs.f_reserved1 == 1 ||
954                                                  stfs.f_reserved1 == 128))
955         return FALSE;
956 #endif
957 #endif
958     return TRUE;
959
960 #elif defined(__NetBSD__)
961     struct statvfs stfs;
962
963     if (statvfs( dir, &stfs ) == -1) return FALSE;
964     /* Only assume CIOPFS is case insensitive. */
965     if (strcmp( stfs.f_fstypename, "fusefs" ) ||
966         strncmp( stfs.f_mntfromname, "ciopfs", 5 ))
967         return TRUE;
968     return FALSE;
969
970 #elif defined(__linux__)
971     struct statfs stfs;
972     struct stat st;
973     char *cifile;
974
975     /* Only assume CIOPFS is case insensitive. */
976     if (statfs( dir, &stfs ) == -1) return FALSE;
977     if (stfs.f_type != 0x65735546 /* FUSE_SUPER_MAGIC */)
978         return TRUE;
979     /* Normally, we'd have to parse the mtab to find out exactly what
980      * kind of FUSE FS this is. But, someone on wine-devel suggested
981      * a shortcut. We'll stat a special file in the directory. If it's
982      * there, we'll assume it's a CIOPFS, else not.
983      * This will break if somebody puts a file named ".ciopfs" in a non-
984      * CIOPFS directory.
985      */
986     cifile = RtlAllocateHeap( GetProcessHeap(), 0, strlen( dir )+sizeof("/.ciopfs") );
987     if (!cifile) return TRUE;
988     strcpy( cifile, dir );
989     strcat( cifile, "/.ciopfs" );
990     if (stat( cifile, &st ) == 0)
991     {
992         RtlFreeHeap( GetProcessHeap(), 0, cifile );
993         return FALSE;
994     }
995     RtlFreeHeap( GetProcessHeap(), 0, cifile );
996     return TRUE;
997 #else
998     return TRUE;
999 #endif
1000 }
1001
1002
1003 /***********************************************************************
1004  *           get_dir_case_sensitivity
1005  *
1006  * Checks if the volume containing the specified directory is case
1007  * sensitive or not. Uses statfs(2) or statvfs(2).
1008  */
1009 static BOOLEAN get_dir_case_sensitivity( const char *dir )
1010 {
1011 #if defined(HAVE_GETATTRLIST) && defined(ATTR_VOL_CAPABILITIES) && \
1012     defined(VOL_CAPABILITIES_FORMAT) && defined(VOL_CAP_FMT_CASE_SENSITIVE)
1013     int case_sensitive = get_dir_case_sensitivity_attr( dir );
1014     if (case_sensitive != -1) return case_sensitive;
1015 #endif
1016     return get_dir_case_sensitivity_stat( dir );
1017 }
1018
1019
1020 /***********************************************************************
1021  *           init_options
1022  *
1023  * Initialize the show_dot_files options.
1024  */
1025 static void init_options(void)
1026 {
1027     static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
1028     static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
1029     char tmp[80];
1030     HANDLE root, hkey;
1031     DWORD dummy;
1032     OBJECT_ATTRIBUTES attr;
1033     UNICODE_STRING nameW;
1034
1035     show_dot_files = 0;
1036
1037     RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
1038     attr.Length = sizeof(attr);
1039     attr.RootDirectory = root;
1040     attr.ObjectName = &nameW;
1041     attr.Attributes = 0;
1042     attr.SecurityDescriptor = NULL;
1043     attr.SecurityQualityOfService = NULL;
1044     RtlInitUnicodeString( &nameW, WineW );
1045
1046     /* @@ Wine registry key: HKCU\Software\Wine */
1047     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
1048     {
1049         RtlInitUnicodeString( &nameW, ShowDotFilesW );
1050         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
1051         {
1052             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
1053             show_dot_files = IS_OPTION_TRUE( str[0] );
1054         }
1055         NtClose( hkey );
1056     }
1057     NtClose( root );
1058
1059     /* a couple of directories that we don't want to return in directory searches */
1060     ignore_file( wine_get_config_dir() );
1061     ignore_file( "/dev" );
1062     ignore_file( "/proc" );
1063 #ifdef linux
1064     ignore_file( "/sys" );
1065 #endif
1066 }
1067
1068
1069 /***********************************************************************
1070  *           DIR_is_hidden_file
1071  *
1072  * Check if the specified file should be hidden based on its name and the show dot files option.
1073  */
1074 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
1075 {
1076     WCHAR *p, *end;
1077
1078     if (show_dot_files == -1) init_options();
1079     if (show_dot_files) return FALSE;
1080
1081     end = p = name->Buffer + name->Length/sizeof(WCHAR);
1082     while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
1083     while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
1084     if (p == end || *p != '.') return FALSE;
1085     /* make sure it isn't '.' or '..' */
1086     if (p + 1 == end) return FALSE;
1087     if (p[1] == '.' && p + 2 == end) return FALSE;
1088     return TRUE;
1089 }
1090
1091
1092 /***********************************************************************
1093  *           hash_short_file_name
1094  *
1095  * Transform a Unix file name into a hashed DOS name. If the name is a valid
1096  * DOS name, it is converted to upper-case; otherwise it is replaced by a
1097  * hashed version that fits in 8.3 format.
1098  * 'buffer' must be at least 12 characters long.
1099  * Returns length of short name in bytes; short name is NOT null-terminated.
1100  */
1101 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
1102 {
1103     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
1104
1105     LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
1106     LPWSTR dst;
1107     unsigned short hash;
1108     int i;
1109
1110     /* Compute the hash code of the file name */
1111     /* If you know something about hash functions, feel free to */
1112     /* insert a better algorithm here... */
1113     if (!is_case_sensitive)
1114     {
1115         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1116             hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
1117         hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
1118     }
1119     else
1120     {
1121         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
1122             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
1123         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
1124     }
1125
1126     /* Find last dot for start of the extension */
1127     for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
1128
1129     /* Copy first 4 chars, replacing invalid chars with '_' */
1130     for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
1131     {
1132         if (p == end || p == ext) break;
1133         *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
1134     }
1135     /* Pad to 5 chars with '~' */
1136     while (i-- >= 0) *dst++ = '~';
1137
1138     /* Insert hash code converted to 3 ASCII chars */
1139     *dst++ = hash_chars[(hash >> 10) & 0x1f];
1140     *dst++ = hash_chars[(hash >> 5) & 0x1f];
1141     *dst++ = hash_chars[hash & 0x1f];
1142
1143     /* Copy the first 3 chars of the extension (if any) */
1144     if (ext)
1145     {
1146         *dst++ = '.';
1147         for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
1148             *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
1149     }
1150     return dst - buffer;
1151 }
1152
1153
1154 /***********************************************************************
1155  *           match_filename
1156  *
1157  * Check a long file name against a mask.
1158  *
1159  * Tests (done in W95 DOS shell - case insensitive):
1160  * *.txt                        test1.test.txt                          *
1161  * *st1*                        test1.txt                               *
1162  * *.t??????.t*                 test1.ta.tornado.txt                    *
1163  * *tornado*                    test1.ta.tornado.txt                    *
1164  * t*t                          test1.ta.tornado.txt                    *
1165  * ?est*                        test1.txt                               *
1166  * ?est???                      test1.txt                               -
1167  * *test1.txt*                  test1.txt                               *
1168  * h?l?o*t.dat                  hellothisisatest.dat                    *
1169  */
1170 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
1171 {
1172     int mismatch;
1173     const WCHAR *name = name_str->Buffer;
1174     const WCHAR *mask = mask_str->Buffer;
1175     const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
1176     const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
1177     const WCHAR *lastjoker = NULL;
1178     const WCHAR *next_to_retry = NULL;
1179
1180     TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
1181
1182     while (name < name_end && mask < mask_end)
1183     {
1184         switch(*mask)
1185         {
1186         case '*':
1187             mask++;
1188             while (mask < mask_end && *mask == '*') mask++;  /* Skip consecutive '*' */
1189             if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
1190             lastjoker = mask;
1191
1192             /* skip to the next match after the joker(s) */
1193             if (is_case_sensitive)
1194                 while (name < name_end && (*name != *mask)) name++;
1195             else
1196                 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
1197             next_to_retry = name;
1198             break;
1199         case '?':
1200             mask++;
1201             name++;
1202             break;
1203         default:
1204             if (is_case_sensitive) mismatch = (*mask != *name);
1205             else mismatch = (toupperW(*mask) != toupperW(*name));
1206
1207             if (!mismatch)
1208             {
1209                 mask++;
1210                 name++;
1211                 if (mask == mask_end)
1212                 {
1213                     if (name == name_end) return TRUE;
1214                     if (lastjoker) mask = lastjoker;
1215                 }
1216             }
1217             else /* mismatch ! */
1218             {
1219                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1220                 {
1221                     mask = lastjoker;
1222
1223                     /* this scan sequence was a mismatch, so restart
1224                      * 1 char after the first char we checked last time */
1225                     next_to_retry++;
1226                     name = next_to_retry;
1227                 }
1228                 else return FALSE; /* bad luck */
1229             }
1230             break;
1231         }
1232     }
1233     while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1234         mask++;  /* Ignore trailing '.' or '*' in mask */
1235     return (name == name_end && mask == mask_end);
1236 }
1237
1238
1239 /***********************************************************************
1240  *           append_entry
1241  *
1242  * helper for NtQueryDirectoryFile
1243  */
1244 static union file_directory_info *append_entry( void *info_ptr, IO_STATUS_BLOCK *io, ULONG max_length,
1245                                                 const char *long_name, const char *short_name,
1246                                                 const UNICODE_STRING *mask, FILE_INFORMATION_CLASS class )
1247 {
1248     union file_directory_info *info;
1249     int i, long_len, short_len, total_len;
1250     struct stat st;
1251     WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1252     WCHAR short_nameW[12];
1253     WCHAR *filename;
1254     UNICODE_STRING str;
1255     ULONG attributes = 0;
1256
1257     io->u.Status = STATUS_SUCCESS;
1258     long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1259     if (long_len == -1) return NULL;
1260
1261     str.Buffer = long_nameW;
1262     str.Length = long_len * sizeof(WCHAR);
1263     str.MaximumLength = sizeof(long_nameW);
1264
1265     if (short_name)
1266     {
1267         short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1268                                      short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1269         if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1270     }
1271     else  /* generate a short name if necessary */
1272     {
1273         BOOLEAN spaces;
1274
1275         short_len = 0;
1276         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1277             short_len = hash_short_file_name( &str, short_nameW );
1278     }
1279
1280     TRACE( "long %s short %s mask %s\n",
1281            debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1282
1283     if (mask && !match_filename( &str, mask ))
1284     {
1285         if (!short_len) return NULL;  /* no short name to match */
1286         str.Buffer = short_nameW;
1287         str.Length = short_len * sizeof(WCHAR);
1288         str.MaximumLength = sizeof(short_nameW);
1289         if (!match_filename( &str, mask )) return NULL;
1290     }
1291
1292     if (lstat( long_name, &st ) == -1) return NULL;
1293     if (S_ISLNK( st.st_mode ))
1294     {
1295         if (stat( long_name, &st ) == -1) return NULL;
1296         if (S_ISDIR( st.st_mode )) attributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1297     }
1298     if (is_ignored_file( &st ))
1299     {
1300         TRACE( "ignoring file %s\n", long_name );
1301         return NULL;
1302     }
1303     if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1304         attributes |= FILE_ATTRIBUTE_HIDDEN;
1305
1306     total_len = dir_info_size( class, long_len );
1307     if (io->Information + total_len > max_length)
1308     {
1309         total_len = max_length - io->Information;
1310         io->u.Status = STATUS_BUFFER_OVERFLOW;
1311     }
1312     info = (union file_directory_info *)((char *)info_ptr + io->Information);
1313     if (st.st_dev != curdir.dev) st.st_ino = 0;  /* ignore inode if on a different device */
1314     /* all the structures start with a FileDirectoryInformation layout */
1315     fill_stat_info( &st, info, class );
1316     info->dir.NextEntryOffset = total_len;
1317     info->dir.FileIndex = 0;  /* NTFS always has 0 here, so let's not bother with it */
1318     info->dir.FileAttributes |= attributes;
1319
1320     switch (class)
1321     {
1322     case FileDirectoryInformation:
1323         info->dir.FileNameLength = long_len * sizeof(WCHAR);
1324         filename = info->dir.FileName;
1325         break;
1326
1327     case FileFullDirectoryInformation:
1328         info->full.EaSize = 0; /* FIXME */
1329         info->full.FileNameLength = long_len * sizeof(WCHAR);
1330         filename = info->full.FileName;
1331         break;
1332
1333     case FileIdFullDirectoryInformation:
1334         info->id_full.EaSize = 0; /* FIXME */
1335         info->id_full.FileNameLength = long_len * sizeof(WCHAR);
1336         filename = info->id_full.FileName;
1337         break;
1338
1339     case FileBothDirectoryInformation:
1340         info->both.EaSize = 0; /* FIXME */
1341         info->both.ShortNameLength = short_len * sizeof(WCHAR);
1342         for (i = 0; i < short_len; i++) info->both.ShortName[i] = toupperW(short_nameW[i]);
1343         info->both.FileNameLength = long_len * sizeof(WCHAR);
1344         filename = info->both.FileName;
1345         break;
1346
1347     case FileIdBothDirectoryInformation:
1348         info->id_both.EaSize = 0; /* FIXME */
1349         info->id_both.ShortNameLength = short_len * sizeof(WCHAR);
1350         for (i = 0; i < short_len; i++) info->id_both.ShortName[i] = toupperW(short_nameW[i]);
1351         info->id_both.FileNameLength = long_len * sizeof(WCHAR);
1352         filename = info->id_both.FileName;
1353         break;
1354
1355     default:
1356         assert(0);
1357         return NULL;
1358     }
1359     memcpy( filename, long_nameW, total_len - ((char *)filename - (char *)info) );
1360     io->Information += total_len;
1361     return info;
1362 }
1363
1364
1365 #ifdef VFAT_IOCTL_READDIR_BOTH
1366
1367 /***********************************************************************
1368  *           start_vfat_ioctl
1369  *
1370  * Wrapper for the VFAT ioctl to work around various kernel bugs.
1371  * dir_section must be held by caller.
1372  */
1373 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1374 {
1375     static KERNEL_DIRENT *de;
1376     int res;
1377
1378     if (!de)
1379     {
1380         const size_t page_size = getpagesize();
1381         SIZE_T size = 2 * sizeof(*de) + page_size;
1382         void *addr = NULL;
1383
1384         if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1385             return NULL;
1386         /* commit only the size needed for the dir entries */
1387         /* this leaves an extra unaccessible page, which should make the kernel */
1388         /* fail with -EFAULT before it stomps all over our memory */
1389         de = addr;
1390         size = 2 * sizeof(*de);
1391         NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1392     }
1393
1394     /* set d_reclen to 65535 to work around an AFS kernel bug */
1395     de[0].d_reclen = 65535;
1396     res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1397     if (res == -1)
1398     {
1399         if (errno != ENOENT) return NULL;  /* VFAT ioctl probably not supported */
1400         de[0].d_reclen = 0;  /* eof */
1401     }
1402     else if (!res && de[0].d_reclen == 65535) return NULL;  /* AFS bug */
1403
1404     return de;
1405 }
1406
1407
1408 /***********************************************************************
1409  *           read_directory_vfat
1410  *
1411  * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1412  */
1413 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1414                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
1415                                 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1416
1417 {
1418     size_t len;
1419     KERNEL_DIRENT *de;
1420     union file_directory_info *info, *last_info = NULL;
1421
1422     io->u.Status = STATUS_SUCCESS;
1423
1424     if (restart_scan) lseek( fd, 0, SEEK_SET );
1425
1426     if (length < max_dir_info_size(class))  /* we may have to return a partial entry here */
1427     {
1428         off_t old_pos = lseek( fd, 0, SEEK_CUR );
1429
1430         if (!(de = start_vfat_ioctl( fd ))) return -1;  /* not supported */
1431
1432         while (de[0].d_reclen)
1433         {
1434             /* make sure names are null-terminated to work around an x86-64 kernel bug */
1435             len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1436             de[0].d_name[len] = 0;
1437             len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1438             de[1].d_name[len] = 0;
1439
1440             if (de[1].d_name[0])
1441                 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1442             else
1443                 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1444             if (info)
1445             {
1446                 last_info = info;
1447                 if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1448                     lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
1449                 break;
1450             }
1451             old_pos = lseek( fd, 0, SEEK_CUR );
1452             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1453         }
1454     }
1455     else  /* we'll only return full entries, no need to worry about overflow */
1456     {
1457         if (!(de = start_vfat_ioctl( fd ))) return -1;  /* not supported */
1458
1459         while (de[0].d_reclen)
1460         {
1461             /* make sure names are null-terminated to work around an x86-64 kernel bug */
1462             len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1463             de[0].d_name[len] = 0;
1464             len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1465             de[1].d_name[len] = 0;
1466
1467             if (de[1].d_name[0])
1468                 info = append_entry( buffer, io, length, de[1].d_name, de[0].d_name, mask, class );
1469             else
1470                 info = append_entry( buffer, io, length, de[0].d_name, NULL, mask, class );
1471             if (info)
1472             {
1473                 last_info = info;
1474                 if (single_entry) break;
1475                 /* check if we still have enough space for the largest possible entry */
1476                 if (io->Information + max_dir_info_size(class) > length) break;
1477             }
1478             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1479         }
1480     }
1481
1482     if (last_info) last_info->next = 0;
1483     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1484     return 0;
1485 }
1486 #endif /* VFAT_IOCTL_READDIR_BOTH */
1487
1488
1489 /***********************************************************************
1490  *           read_directory_getdents
1491  *
1492  * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1493  */
1494 #ifdef USE_GETDENTS
1495 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1496                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
1497                                     BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1498 {
1499     off_t old_pos = 0;
1500     size_t size = length;
1501     int res, fake_dot_dot = 1;
1502     char *data, local_buffer[8192];
1503     KERNEL_DIRENT64 *de;
1504     union file_directory_info *info, *last_info = NULL;
1505
1506     if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1507     {
1508         size = sizeof(local_buffer);
1509         data = local_buffer;
1510     }
1511
1512     if (restart_scan) lseek( fd, 0, SEEK_SET );
1513     else if (length < max_dir_info_size(class))  /* we may have to return a partial entry here */
1514     {
1515         old_pos = lseek( fd, 0, SEEK_CUR );
1516         if (old_pos == -1 && errno == ENOENT)
1517         {
1518             io->u.Status = STATUS_NO_MORE_FILES;
1519             res = 0;
1520             goto done;
1521         }
1522     }
1523
1524     io->u.Status = STATUS_SUCCESS;
1525
1526     res = getdents64( fd, data, size );
1527     if (res == -1)
1528     {
1529         if (errno != ENOSYS)
1530         {
1531             io->u.Status = FILE_GetNtStatus();
1532             res = 0;
1533         }
1534         goto done;
1535     }
1536
1537     de = (KERNEL_DIRENT64 *)data;
1538
1539     if (restart_scan)
1540     {
1541         /* check if we got . and .. from getdents */
1542         if (res > 0)
1543         {
1544             if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1545             {
1546                 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1547                 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1548             }
1549         }
1550         /* make sure we have enough room for both entries */
1551         if (fake_dot_dot)
1552         {
1553             const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1554             if (length < min_info_size || single_entry)
1555             {
1556                 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1557                 fake_dot_dot = 0;
1558             }
1559         }
1560
1561         if (fake_dot_dot)
1562         {
1563             if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1564                 last_info = info;
1565             if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1566                 last_info = info;
1567
1568             /* check if we still have enough space for the largest possible entry */
1569             if (last_info && io->Information + max_dir_info_size(class) > length)
1570             {
1571                 lseek( fd, 0, SEEK_SET );  /* reset pos to first entry */
1572                 res = 0;
1573             }
1574         }
1575     }
1576
1577     while (res > 0)
1578     {
1579         res -= de->d_reclen;
1580         if (de->d_ino &&
1581             !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1582             (info = append_entry( buffer, io, length, de->d_name, NULL, mask, class )))
1583         {
1584             last_info = info;
1585             if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1586             {
1587                 lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
1588                 break;
1589             }
1590             /* check if we still have enough space for the largest possible entry */
1591             if (single_entry || io->Information + max_dir_info_size(class) > length)
1592             {
1593                 if (res > 0) lseek( fd, de->d_off, SEEK_SET );  /* set pos to next entry */
1594                 break;
1595             }
1596         }
1597         old_pos = de->d_off;
1598         /* move on to the next entry */
1599         if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1600         else
1601         {
1602             res = getdents64( fd, data, size );
1603             de = (KERNEL_DIRENT64 *)data;
1604         }
1605     }
1606
1607     if (last_info) last_info->next = 0;
1608     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1609     res = 0;
1610 done:
1611     if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1612     return res;
1613 }
1614
1615 #elif defined HAVE_GETDIRENTRIES
1616
1617 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1618
1619 /* Darwin doesn't provide a version of getdirentries with support for 64-bit
1620  * inodes.  When 64-bit inodes are enabled, the getdirentries symbol is mapped
1621  * to _getdirentries_is_not_available_when_64_bit_inodes_are_in_effect so that
1622  * we get link errors if we try to use it.  We still need getdirentries, but we
1623  * don't need it to support 64-bit inodes.  So, we use the legacy getdirentries
1624  * with 32-bit inodes.  We have to be careful to use a corresponding dirent
1625  * structure, too.
1626  */
1627 int darwin_legacy_getdirentries(int, char *, int, long *) __asm("_getdirentries");
1628 #define getdirentries darwin_legacy_getdirentries
1629
1630 struct darwin_legacy_dirent {
1631     __uint32_t d_ino;
1632     __uint16_t d_reclen;
1633     __uint8_t  d_type;
1634     __uint8_t  d_namlen;
1635     char d_name[__DARWIN_MAXNAMLEN + 1];
1636 };
1637 #define dirent darwin_legacy_dirent
1638
1639 #endif
1640
1641 /***********************************************************************
1642  *           wine_getdirentries
1643  *
1644  * Wrapper for the BSD getdirentries system call to fix a bug in the
1645  * Mac OS X version.  For some file systems (at least Apple Filing
1646  * Protocol a.k.a. AFP), getdirentries resets the file position to 0
1647  * when it's about to return 0 (no more entries).  So, a subsequent
1648  * getdirentries call starts over at the beginning again, causing an
1649  * infinite loop.
1650  */
1651 static inline int wine_getdirentries(int fd, char *buf, int nbytes, long *basep)
1652 {
1653     int res = getdirentries(fd, buf, nbytes, basep);
1654 #ifdef __APPLE__
1655     if (res == 0)
1656         lseek(fd, *basep, SEEK_SET);
1657 #endif
1658     return res;
1659 }
1660
1661 /***********************************************************************
1662  *           read_directory_getdirentries
1663  *
1664  * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1665  */
1666 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1667                                          BOOLEAN single_entry, const UNICODE_STRING *mask,
1668                                          BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1669 {
1670     long restart_pos;
1671     ULONG_PTR restart_info_pos = 0;
1672     size_t size, initial_size = length;
1673     int res, fake_dot_dot = 1;
1674     char *data, local_buffer[8192];
1675     struct dirent *de;
1676     union file_directory_info *info, *last_info = NULL, *restart_last_info = NULL;
1677
1678     size = initial_size;
1679     data = local_buffer;
1680     if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1681     {
1682         io->u.Status = STATUS_NO_MEMORY;
1683         return io->u.Status;
1684     }
1685
1686     if (restart_scan) lseek( fd, 0, SEEK_SET );
1687
1688     io->u.Status = STATUS_SUCCESS;
1689
1690     /* FIXME: should make sure size is larger than filesystem block size */
1691     res = wine_getdirentries( fd, data, size, &restart_pos );
1692     if (res == -1)
1693     {
1694         io->u.Status = FILE_GetNtStatus();
1695         res = 0;
1696         goto done;
1697     }
1698
1699     de = (struct dirent *)data;
1700
1701     if (restart_scan)
1702     {
1703         /* check if we got . and .. from getdirentries */
1704         if (res > 0)
1705         {
1706             if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1707             {
1708                 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1709                 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1710             }
1711         }
1712         /* make sure we have enough room for both entries */
1713         if (fake_dot_dot)
1714         {
1715             const ULONG min_info_size = dir_info_size( class, 1 ) + dir_info_size( class, 2 );
1716             if (length < min_info_size || single_entry)
1717             {
1718                 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1719                 fake_dot_dot = 0;
1720             }
1721         }
1722
1723         if (fake_dot_dot)
1724         {
1725             if ((info = append_entry( buffer, io, length, ".", NULL, mask, class )))
1726                 last_info = info;
1727             if ((info = append_entry( buffer, io, length, "..", NULL, mask, class )))
1728                 last_info = info;
1729
1730             restart_last_info = last_info;
1731             restart_info_pos = io->Information;
1732
1733             /* check if we still have enough space for the largest possible entry */
1734             if (last_info && io->Information + max_dir_info_size(class) > length)
1735             {
1736                 lseek( fd, 0, SEEK_SET );  /* reset pos to first entry */
1737                 res = 0;
1738             }
1739         }
1740     }
1741
1742     while (res > 0)
1743     {
1744         res -= de->d_reclen;
1745         if (de->d_fileno &&
1746             !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1747             ((info = append_entry( buffer, io, length, de->d_name, NULL, mask, class ))))
1748         {
1749             last_info = info;
1750             if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1751             {
1752                 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1753                 if (restart_info_pos)  /* if we have a complete read already, return it */
1754                 {
1755                     io->u.Status = STATUS_SUCCESS;
1756                     io->Information = restart_info_pos;
1757                     last_info = restart_last_info;
1758                     break;
1759                 }
1760                 /* otherwise restart from the start with a smaller size */
1761                 size = (char *)de - data;
1762                 if (!size) break;
1763                 io->Information = 0;
1764                 last_info = NULL;
1765                 goto restart;
1766             }
1767             /* if we have to return but the buffer contains more data, restart with a smaller size */
1768             if (res > 0 && (single_entry || io->Information + max_dir_info_size(class) > length))
1769             {
1770                 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1771                 size = (char *)de - data;
1772                 io->Information = restart_info_pos;
1773                 last_info = restart_last_info;
1774                 goto restart;
1775             }
1776         }
1777         /* move on to the next entry */
1778         if (res > 0)
1779         {
1780             de = (struct dirent *)((char *)de + de->d_reclen);
1781             continue;
1782         }
1783         if (size < initial_size) break;  /* already restarted once, give up now */
1784         size = min( size, length - io->Information );
1785         /* if size is too small don't bother to continue */
1786         if (size < max_dir_info_size(class) && last_info) break;
1787         restart_last_info = last_info;
1788         restart_info_pos = io->Information;
1789     restart:
1790         res = wine_getdirentries( fd, data, size, &restart_pos );
1791         de = (struct dirent *)data;
1792     }
1793
1794     if (last_info) last_info->next = 0;
1795     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1796     res = 0;
1797 done:
1798     if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1799     return res;
1800 }
1801
1802 #ifdef _DARWIN_FEATURE_64_BIT_INODE
1803 #undef getdirentries
1804 #undef dirent
1805 #endif
1806
1807 #endif  /* HAVE_GETDIRENTRIES */
1808
1809
1810 /***********************************************************************
1811  *           read_directory_readdir
1812  *
1813  * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1814  */
1815 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1816                                     BOOLEAN single_entry, const UNICODE_STRING *mask,
1817                                     BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1818 {
1819     DIR *dir;
1820     off_t i, old_pos = 0;
1821     struct dirent *de;
1822     union file_directory_info *info, *last_info = NULL;
1823
1824     if (!(dir = opendir( "." )))
1825     {
1826         io->u.Status = FILE_GetNtStatus();
1827         return;
1828     }
1829
1830     if (!restart_scan)
1831     {
1832         old_pos = lseek( fd, 0, SEEK_CUR );
1833         /* skip the right number of entries */
1834         for (i = 0; i < old_pos - 2; i++)
1835         {
1836             if (!readdir( dir ))
1837             {
1838                 closedir( dir );
1839                 io->u.Status = STATUS_NO_MORE_FILES;
1840                 return;
1841             }
1842         }
1843     }
1844     io->u.Status = STATUS_SUCCESS;
1845
1846     for (;;)
1847     {
1848         if (old_pos == 0)
1849             info = append_entry( buffer, io, length, ".", NULL, mask, class );
1850         else if (old_pos == 1)
1851             info = append_entry( buffer, io, length, "..", NULL, mask, class );
1852         else if ((de = readdir( dir )))
1853         {
1854             if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1855                 info = append_entry( buffer, io, length, de->d_name, NULL, mask, class );
1856             else
1857                 info = NULL;
1858         }
1859         else
1860             break;
1861         old_pos++;
1862         if (info)
1863         {
1864             last_info = info;
1865             if (io->u.Status == STATUS_BUFFER_OVERFLOW)
1866             {
1867                 old_pos--;  /* restore pos to previous entry */
1868                 break;
1869             }
1870             if (single_entry) break;
1871             /* check if we still have enough space for the largest possible entry */
1872             if (io->Information + max_dir_info_size(class) > length) break;
1873         }
1874     }
1875
1876     lseek( fd, old_pos, SEEK_SET );  /* store dir offset as filepos for fd */
1877     closedir( dir );
1878
1879     if (last_info) last_info->next = 0;
1880     else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1881 }
1882
1883 /***********************************************************************
1884  *           read_directory_stat
1885  *
1886  * Read a single file from a directory by determining whether the file
1887  * identified by mask exists using stat.
1888  */
1889 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1890                                 BOOLEAN single_entry, const UNICODE_STRING *mask,
1891                                 BOOLEAN restart_scan, FILE_INFORMATION_CLASS class )
1892 {
1893     int unix_len, ret, used_default;
1894     char *unix_name;
1895     struct stat st;
1896
1897     TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1898
1899     unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1900     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1901     {
1902         io->u.Status = STATUS_NO_MEMORY;
1903         return 0;
1904     }
1905     ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1906                            NULL, &used_default );
1907     if (ret > 0 && !used_default)
1908     {
1909         unix_name[ret] = 0;
1910         if (restart_scan)
1911         {
1912             lseek( fd, 0, SEEK_SET );
1913         }
1914         else if (lseek( fd, 0, SEEK_CUR ) != 0)
1915         {
1916             io->u.Status = STATUS_NO_MORE_FILES;
1917             ret = 0;
1918             goto done;
1919         }
1920
1921         ret = stat( unix_name, &st );
1922         if (!ret)
1923         {
1924             union file_directory_info *info = append_entry( buffer, io, length, unix_name, NULL, NULL, class );
1925             if (info)
1926             {
1927                 info->next = 0;
1928                 if (io->u.Status != STATUS_BUFFER_OVERFLOW) lseek( fd, 1, SEEK_CUR );
1929             }
1930             else io->u.Status = STATUS_NO_MORE_FILES;
1931         }
1932     }
1933     else ret = -1;
1934
1935 done:
1936     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1937
1938     TRACE("returning %d\n", ret);
1939
1940     return ret;
1941 }
1942
1943
1944 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1945 {
1946     const WCHAR *end;
1947     for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1948     return NULL;
1949 }
1950
1951 /******************************************************************************
1952  *  NtQueryDirectoryFile        [NTDLL.@]
1953  *  ZwQueryDirectoryFile        [NTDLL.@]
1954  */
1955 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1956                                       PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1957                                       PIO_STATUS_BLOCK io,
1958                                       PVOID buffer, ULONG length,
1959                                       FILE_INFORMATION_CLASS info_class,
1960                                       BOOLEAN single_entry,
1961                                       PUNICODE_STRING mask,
1962                                       BOOLEAN restart_scan )
1963 {
1964     int cwd, fd, needs_close;
1965     static const WCHAR wszWildcards[] = { '*','?',0 };
1966
1967     TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1968           handle, event, apc_routine, apc_context, io, buffer,
1969           length, info_class, single_entry, debugstr_us(mask),
1970           restart_scan);
1971
1972     if (event || apc_routine)
1973     {
1974         FIXME( "Unsupported yet option\n" );
1975         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1976     }
1977     switch (info_class)
1978     {
1979     case FileDirectoryInformation:
1980     case FileBothDirectoryInformation:
1981     case FileFullDirectoryInformation:
1982     case FileIdBothDirectoryInformation:
1983     case FileIdFullDirectoryInformation:
1984         if (length < dir_info_size( info_class, 1 )) return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1985         break;
1986     default:
1987         FIXME( "Unsupported file info class %d\n", info_class );
1988         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1989     }
1990
1991     if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1992         return io->u.Status;
1993
1994     io->Information = 0;
1995
1996     RtlEnterCriticalSection( &dir_section );
1997
1998     if (show_dot_files == -1) init_options();
1999
2000     cwd = open( ".", O_RDONLY );
2001     if (fchdir( fd ) != -1)
2002     {
2003         struct stat st;
2004         fstat( fd, &st );
2005         curdir.dev = st.st_dev;
2006         curdir.ino = st.st_ino;
2007 #ifdef VFAT_IOCTL_READDIR_BOTH
2008         if ((read_directory_vfat( fd, io, buffer, length, single_entry,
2009                                   mask, restart_scan, info_class )) != -1) goto done;
2010 #endif
2011         if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
2012             read_directory_stat( fd, io, buffer, length, single_entry,
2013                                  mask, restart_scan, info_class ) != -1) goto done;
2014 #ifdef USE_GETDENTS
2015         if ((read_directory_getdents( fd, io, buffer, length, single_entry,
2016                                       mask, restart_scan, info_class )) != -1) goto done;
2017 #elif defined HAVE_GETDIRENTRIES
2018         if ((read_directory_getdirentries( fd, io, buffer, length, single_entry,
2019                                            mask, restart_scan, info_class )) != -1) goto done;
2020 #endif
2021         read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan, info_class );
2022
2023     done:
2024         if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
2025     }
2026     else io->u.Status = FILE_GetNtStatus();
2027
2028     RtlLeaveCriticalSection( &dir_section );
2029
2030     if (needs_close) close( fd );
2031     if (cwd != -1) close( cwd );
2032     TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
2033     return io->u.Status;
2034 }
2035
2036
2037 /***********************************************************************
2038  *           find_file_in_dir
2039  *
2040  * Find a file in a directory the hard way, by doing a case-insensitive search.
2041  * The file found is appended to unix_name at pos.
2042  * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
2043  */
2044 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
2045                                   int check_case, int *is_win_dir )
2046 {
2047     WCHAR buffer[MAX_DIR_ENTRY_LEN];
2048     UNICODE_STRING str;
2049     BOOLEAN spaces;
2050     DIR *dir;
2051     struct dirent *de;
2052     struct stat st;
2053     int ret, used_default, is_name_8_dot_3;
2054
2055     /* try a shortcut for this directory */
2056
2057     unix_name[pos++] = '/';
2058     ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
2059                            NULL, &used_default );
2060     /* if we used the default char, the Unix name won't round trip properly back to Unicode */
2061     /* so it cannot match the file we are looking for */
2062     if (ret >= 0 && !used_default)
2063     {
2064         unix_name[pos + ret] = 0;
2065         if (!stat( unix_name, &st ))
2066         {
2067             if (is_win_dir) *is_win_dir = is_same_file( &windir, &st );
2068             return STATUS_SUCCESS;
2069         }
2070     }
2071     if (check_case) goto not_found;  /* we want an exact match */
2072
2073     if (pos > 1) unix_name[pos - 1] = 0;
2074     else unix_name[1] = 0;  /* keep the initial slash */
2075
2076     /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
2077
2078     str.Buffer = (WCHAR *)name;
2079     str.Length = length * sizeof(WCHAR);
2080     str.MaximumLength = str.Length;
2081     is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
2082
2083     if (!is_name_8_dot_3 && !get_dir_case_sensitivity( unix_name )) goto not_found;
2084
2085     /* now look for it through the directory */
2086
2087 #ifdef VFAT_IOCTL_READDIR_BOTH
2088     if (is_name_8_dot_3)
2089     {
2090         int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
2091         if (fd != -1)
2092         {
2093             KERNEL_DIRENT *de;
2094
2095             RtlEnterCriticalSection( &dir_section );
2096             if ((de = start_vfat_ioctl( fd )))
2097             {
2098                 unix_name[pos - 1] = '/';
2099                 while (de[0].d_reclen)
2100                 {
2101                     /* make sure names are null-terminated to work around an x86-64 kernel bug */
2102                     size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
2103                     de[0].d_name[len] = 0;
2104                     len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
2105                     de[1].d_name[len] = 0;
2106
2107                     if (de[1].d_name[0])
2108                     {
2109                         ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
2110                                                buffer, MAX_DIR_ENTRY_LEN );
2111                         if (ret == length && !memicmpW( buffer, name, length))
2112                         {
2113                             strcpy( unix_name + pos, de[1].d_name );
2114                             RtlLeaveCriticalSection( &dir_section );
2115                             close( fd );
2116                             goto success;
2117                         }
2118                     }
2119                     ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
2120                                            buffer, MAX_DIR_ENTRY_LEN );
2121                     if (ret == length && !memicmpW( buffer, name, length))
2122                     {
2123                         strcpy( unix_name + pos,
2124                                 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
2125                         RtlLeaveCriticalSection( &dir_section );
2126                         close( fd );
2127                         goto success;
2128                     }
2129                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
2130                     {
2131                         RtlLeaveCriticalSection( &dir_section );
2132                         close( fd );
2133                         goto not_found;
2134                     }
2135                 }
2136             }
2137             RtlLeaveCriticalSection( &dir_section );
2138             close( fd );
2139         }
2140         /* fall through to normal handling */
2141     }
2142 #endif /* VFAT_IOCTL_READDIR_BOTH */
2143
2144     if (!(dir = opendir( unix_name )))
2145     {
2146         if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
2147         else return FILE_GetNtStatus();
2148     }
2149     unix_name[pos - 1] = '/';
2150     str.Buffer = buffer;
2151     str.MaximumLength = sizeof(buffer);
2152     while ((de = readdir( dir )))
2153     {
2154         ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
2155         if (ret == length && !memicmpW( buffer, name, length ))
2156         {
2157             strcpy( unix_name + pos, de->d_name );
2158             closedir( dir );
2159             goto success;
2160         }
2161
2162         if (!is_name_8_dot_3) continue;
2163
2164         str.Length = ret * sizeof(WCHAR);
2165         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
2166         {
2167             WCHAR short_nameW[12];
2168             ret = hash_short_file_name( &str, short_nameW );
2169             if (ret == length && !memicmpW( short_nameW, name, length ))
2170             {
2171                 strcpy( unix_name + pos, de->d_name );
2172                 closedir( dir );
2173                 goto success;
2174             }
2175         }
2176     }
2177     closedir( dir );
2178
2179 not_found:
2180     unix_name[pos - 1] = 0;
2181     return STATUS_OBJECT_PATH_NOT_FOUND;
2182
2183 success:
2184     if (is_win_dir && !stat( unix_name, &st )) *is_win_dir = is_same_file( &windir, &st );
2185     return STATUS_SUCCESS;
2186 }
2187
2188
2189 #ifndef _WIN64
2190
2191 static const WCHAR catrootW[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t',0};
2192 static const WCHAR catroot2W[] = {'s','y','s','t','e','m','3','2','\\','c','a','t','r','o','o','t','2',0};
2193 static const WCHAR driversstoreW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','s','t','o','r','e',0};
2194 static const WCHAR driversetcW[] = {'s','y','s','t','e','m','3','2','\\','d','r','i','v','e','r','s','\\','e','t','c',0};
2195 static const WCHAR logfilesW[] = {'s','y','s','t','e','m','3','2','\\','l','o','g','f','i','l','e','s',0};
2196 static const WCHAR spoolW[] = {'s','y','s','t','e','m','3','2','\\','s','p','o','o','l',0};
2197 static const WCHAR system32W[] = {'s','y','s','t','e','m','3','2',0};
2198 static const WCHAR syswow64W[] = {'s','y','s','w','o','w','6','4',0};
2199 static const WCHAR sysnativeW[] = {'s','y','s','n','a','t','i','v','e',0};
2200 static const WCHAR regeditW[] = {'r','e','g','e','d','i','t','.','e','x','e',0};
2201 static const WCHAR wow_regeditW[] = {'s','y','s','w','o','w','6','4','\\','r','e','g','e','d','i','t','.','e','x','e',0};
2202
2203 static struct
2204 {
2205     const WCHAR *source;
2206     const WCHAR *dos_target;
2207     const char *unix_target;
2208 } redirects[] =
2209 {
2210     { catrootW, NULL, NULL },
2211     { catroot2W, NULL, NULL },
2212     { driversstoreW, NULL, NULL },
2213     { driversetcW, NULL, NULL },
2214     { logfilesW, NULL, NULL },
2215     { spoolW, NULL, NULL },
2216     { system32W, syswow64W, NULL },
2217     { sysnativeW, system32W, NULL },
2218     { regeditW, wow_regeditW, NULL }
2219 };
2220
2221 static unsigned int nb_redirects;
2222
2223
2224 /***********************************************************************
2225  *           get_redirect_target
2226  *
2227  * Find the target unix name for a redirected dir.
2228  */
2229 static const char *get_redirect_target( const char *windows_dir, const WCHAR *name )
2230 {
2231     int used_default, len, pos, win_len = strlen( windows_dir );
2232     char *unix_name, *unix_target = NULL;
2233     NTSTATUS status;
2234
2235     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, win_len + MAX_DIR_ENTRY_LEN + 2 )))
2236         return NULL;
2237     memcpy( unix_name, windows_dir, win_len );
2238     pos = win_len;
2239
2240     while (*name)
2241     {
2242         const WCHAR *end, *next;
2243
2244         for (end = name; *end; end++) if (IS_SEPARATOR(*end)) break;
2245         for (next = end; *next; next++) if (!IS_SEPARATOR(*next)) break;
2246
2247         status = find_file_in_dir( unix_name, pos, name, end - name, FALSE, NULL );
2248         if (status == STATUS_OBJECT_PATH_NOT_FOUND && !*next)  /* not finding last element is ok */
2249         {
2250             len = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2251                                    MAX_DIR_ENTRY_LEN - (pos - win_len), NULL, &used_default );
2252             if (len > 0 && !used_default)
2253             {
2254                 unix_name[pos] = '/';
2255                 pos += len + 1;
2256                 unix_name[pos] = 0;
2257                 break;
2258             }
2259         }
2260         if (status) goto done;
2261         pos += strlen( unix_name + pos );
2262         name = next;
2263     }
2264
2265     if ((unix_target = RtlAllocateHeap( GetProcessHeap(), 0, pos - win_len )))
2266         memcpy( unix_target, unix_name + win_len + 1, pos - win_len );
2267
2268 done:
2269     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2270     return unix_target;
2271 }
2272
2273
2274 /***********************************************************************
2275  *           init_redirects
2276  */
2277 static void init_redirects(void)
2278 {
2279     UNICODE_STRING nt_name;
2280     ANSI_STRING unix_name;
2281     NTSTATUS status;
2282     struct stat st;
2283     unsigned int i;
2284
2285     if (!RtlDosPathNameToNtPathName_U( windows_dir.Buffer, &nt_name, NULL, NULL ))
2286     {
2287         ERR( "can't convert %s\n", debugstr_us(&windows_dir) );
2288         return;
2289     }
2290     status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN_IF, FALSE );
2291     RtlFreeUnicodeString( &nt_name );
2292     if (status)
2293     {
2294         ERR( "cannot open %s (%x)\n", debugstr_us(&windows_dir), status );
2295         return;
2296     }
2297     if (!stat( unix_name.Buffer, &st ))
2298     {
2299         windir.dev = st.st_dev;
2300         windir.ino = st.st_ino;
2301         nb_redirects = sizeof(redirects) / sizeof(redirects[0]);
2302         for (i = 0; i < nb_redirects; i++)
2303         {
2304             if (!redirects[i].dos_target) continue;
2305             redirects[i].unix_target = get_redirect_target( unix_name.Buffer, redirects[i].dos_target );
2306             TRACE( "%s -> %s\n", debugstr_w(redirects[i].source), redirects[i].unix_target );
2307         }
2308     }
2309     RtlFreeAnsiString( &unix_name );
2310
2311 }
2312
2313
2314 /***********************************************************************
2315  *           match_redirect
2316  *
2317  * Check if path matches a redirect name. If yes, return matched length.
2318  */
2319 static int match_redirect( const WCHAR *path, int len, const WCHAR *redir, int check_case )
2320 {
2321     int i = 0;
2322
2323     while (i < len && *redir)
2324     {
2325         if (IS_SEPARATOR(path[i]))
2326         {
2327             if (*redir++ != '\\') return 0;
2328             while (i < len && IS_SEPARATOR(path[i])) i++;
2329             continue;  /* move on to next path component */
2330         }
2331         else if (check_case)
2332         {
2333             if (path[i] != *redir) return 0;
2334         }
2335         else
2336         {
2337             if (tolowerW(path[i]) != tolowerW(*redir)) return 0;
2338         }
2339         i++;
2340         redir++;
2341     }
2342     if (*redir) return 0;
2343     if (i < len && !IS_SEPARATOR(path[i])) return 0;
2344     while (i < len && IS_SEPARATOR(path[i])) i++;
2345     return i;
2346 }
2347
2348
2349 /***********************************************************************
2350  *           get_redirect_path
2351  *
2352  * Retrieve the Unix path corresponding to a redirected path if any.
2353  */
2354 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2355 {
2356     unsigned int i;
2357     int len;
2358
2359     for (i = 0; i < nb_redirects; i++)
2360     {
2361         if ((len = match_redirect( name, length, redirects[i].source, check_case )))
2362         {
2363             if (!redirects[i].unix_target) break;
2364             unix_name[pos++] = '/';
2365             strcpy( unix_name + pos, redirects[i].unix_target );
2366             return len;
2367         }
2368     }
2369     return 0;
2370 }
2371
2372 #else  /* _WIN64 */
2373
2374 /* there are no redirects on 64-bit */
2375
2376 static const unsigned int nb_redirects = 0;
2377
2378 static int get_redirect_path( char *unix_name, int pos, const WCHAR *name, int length, int check_case )
2379 {
2380     return 0;
2381 }
2382
2383 #endif
2384
2385 /***********************************************************************
2386  *           DIR_init_windows_dir
2387  */
2388 void DIR_init_windows_dir( const WCHAR *win, const WCHAR *sys )
2389 {
2390     /* FIXME: should probably store paths as NT file names */
2391
2392     RtlCreateUnicodeString( &windows_dir, win );
2393     RtlCreateUnicodeString( &system_dir, sys );
2394
2395 #ifndef _WIN64
2396     if (is_wow64) init_redirects();
2397 #endif
2398 }
2399
2400
2401 /******************************************************************************
2402  *           get_dos_device
2403  *
2404  * Get the Unix path of a DOS device.
2405  */
2406 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
2407 {
2408     const char *config_dir = wine_get_config_dir();
2409     struct stat st;
2410     char *unix_name, *new_name, *dev;
2411     unsigned int i;
2412     int unix_len;
2413
2414     /* make sure the device name is ASCII */
2415     for (i = 0; i < name_len; i++)
2416         if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
2417
2418     unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
2419
2420     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2421         return STATUS_NO_MEMORY;
2422
2423     strcpy( unix_name, config_dir );
2424     strcat( unix_name, "/dosdevices/" );
2425     dev = unix_name + strlen(unix_name);
2426
2427     for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
2428     dev[i] = 0;
2429
2430     /* special case for drive devices */
2431     if (name_len == 2 && dev[1] == ':')
2432     {
2433         dev[i++] = ':';
2434         dev[i] = 0;
2435     }
2436
2437     for (;;)
2438     {
2439         if (!stat( unix_name, &st ))
2440         {
2441             TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
2442             unix_name_ret->Buffer = unix_name;
2443             unix_name_ret->Length = strlen(unix_name);
2444             unix_name_ret->MaximumLength = unix_len;
2445             return STATUS_SUCCESS;
2446         }
2447         if (!dev) break;
2448
2449         /* now try some defaults for it */
2450         if (!strcmp( dev, "aux" ))
2451         {
2452             strcpy( dev, "com1" );
2453             continue;
2454         }
2455         if (!strcmp( dev, "prn" ))
2456         {
2457             strcpy( dev, "lpt1" );
2458             continue;
2459         }
2460         if (!strcmp( dev, "nul" ))
2461         {
2462             strcpy( unix_name, "/dev/null" );
2463             dev = NULL; /* last try */
2464             continue;
2465         }
2466
2467         new_name = NULL;
2468         if (dev[1] == ':' && dev[2] == ':')  /* drive device */
2469         {
2470             dev[2] = 0;  /* remove last ':' to get the drive mount point symlink */
2471             new_name = get_default_drive_device( unix_name );
2472         }
2473         else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( atoi(dev + 3 ));
2474         else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( atoi(dev + 3 ));
2475
2476         if (!new_name) break;
2477
2478         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2479         unix_name = new_name;
2480         unix_len = strlen(unix_name) + 1;
2481         dev = NULL; /* last try */
2482     }
2483     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2484     return STATUS_BAD_DEVICE_TYPE;
2485 }
2486
2487
2488 /* return the length of the DOS namespace prefix if any */
2489 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
2490 {
2491     static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
2492     static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
2493
2494     if (name->Length > sizeof(nt_prefixW) &&
2495         !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
2496         return sizeof(nt_prefixW) / sizeof(WCHAR);
2497
2498     if (name->Length > sizeof(dosdev_prefixW) &&
2499         !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
2500         return sizeof(dosdev_prefixW) / sizeof(WCHAR);
2501
2502     return 0;
2503 }
2504
2505
2506 /******************************************************************************
2507  *           find_file_id
2508  *
2509  * Recursively search directories from the dir queue for a given inode.
2510  */
2511 static NTSTATUS find_file_id( ANSI_STRING *unix_name, ULONGLONG file_id, dev_t dev )
2512 {
2513     unsigned int pos;
2514     DIR *dir;
2515     struct dirent *de;
2516     NTSTATUS status;
2517     struct stat st;
2518
2519     while (!(status = next_dir_in_queue( unix_name->Buffer )))
2520     {
2521         if (!(dir = opendir( unix_name->Buffer ))) continue;
2522         TRACE( "searching %s for %s\n", unix_name->Buffer, wine_dbgstr_longlong(file_id) );
2523         pos = strlen( unix_name->Buffer );
2524         if (pos + MAX_DIR_ENTRY_LEN >= unix_name->MaximumLength/sizeof(WCHAR))
2525         {
2526             char *new = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name->Buffer,
2527                                            unix_name->MaximumLength * 2 );
2528             if (!new)
2529             {
2530                 closedir( dir );
2531                 return STATUS_NO_MEMORY;
2532             }
2533             unix_name->MaximumLength *= 2;
2534             unix_name->Buffer = new;
2535         }
2536         unix_name->Buffer[pos++] = '/';
2537         while ((de = readdir( dir )))
2538         {
2539             if (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." )) continue;
2540             strcpy( unix_name->Buffer + pos, de->d_name );
2541             if (lstat( unix_name->Buffer, &st ) == -1) continue;
2542             if (st.st_dev != dev) continue;
2543             if (st.st_ino == file_id)
2544             {
2545                 closedir( dir );
2546                 return STATUS_SUCCESS;
2547             }
2548             if (!S_ISDIR( st.st_mode )) continue;
2549             if ((status = add_dir_to_queue( unix_name->Buffer )) != STATUS_SUCCESS)
2550             {
2551                 closedir( dir );
2552                 return status;
2553             }
2554         }
2555         closedir( dir );
2556     }
2557     return status;
2558 }
2559
2560
2561 /******************************************************************************
2562  *           file_id_to_unix_file_name
2563  *
2564  * Lookup a file from its file id instead of its name.
2565  */
2566 NTSTATUS file_id_to_unix_file_name( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name )
2567 {
2568     enum server_fd_type type;
2569     int old_cwd, root_fd, needs_close;
2570     NTSTATUS status;
2571     ULONGLONG file_id;
2572     struct stat st, root_st;
2573
2574     if (attr->ObjectName->Length != sizeof(ULONGLONG)) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2575     if (!attr->RootDirectory) return STATUS_INVALID_PARAMETER;
2576     memcpy( &file_id, attr->ObjectName->Buffer, sizeof(file_id) );
2577
2578     unix_name->MaximumLength = 2 * MAX_DIR_ENTRY_LEN + 4;
2579     if (!(unix_name->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, unix_name->MaximumLength )))
2580         return STATUS_NO_MEMORY;
2581     strcpy( unix_name->Buffer, "." );
2582
2583     if ((status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2584         goto done;
2585
2586     if (type != FD_TYPE_DIR)
2587     {
2588         status = STATUS_OBJECT_TYPE_MISMATCH;
2589         goto done;
2590     }
2591
2592     fstat( root_fd, &root_st );
2593     if (root_st.st_ino == file_id)  /* shortcut for "." */
2594     {
2595         status = STATUS_SUCCESS;
2596         goto done;
2597     }
2598
2599     RtlEnterCriticalSection( &dir_section );
2600     if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2601     {
2602         /* shortcut for ".." */
2603         if (!stat( "..", &st ) && st.st_dev == root_st.st_dev && st.st_ino == file_id)
2604         {
2605             strcpy( unix_name->Buffer, ".." );
2606             status = STATUS_SUCCESS;
2607         }
2608         else
2609         {
2610             status = add_dir_to_queue( "." );
2611             if (!status)
2612                 status = find_file_id( unix_name, file_id, root_st.st_dev );
2613             if (!status)  /* get rid of "./" prefix */
2614                 memmove( unix_name->Buffer, unix_name->Buffer + 2, strlen(unix_name->Buffer) - 1 );
2615             flush_dir_queue();
2616         }
2617         if (fchdir( old_cwd ) == -1) chdir( "/" );
2618     }
2619     else status = FILE_GetNtStatus();
2620     RtlLeaveCriticalSection( &dir_section );
2621     if (old_cwd != -1) close( old_cwd );
2622
2623 done:
2624     if (status == STATUS_SUCCESS)
2625     {
2626         TRACE( "%s -> %s\n", wine_dbgstr_longlong(file_id), debugstr_a(unix_name->Buffer) );
2627         unix_name->Length = strlen( unix_name->Buffer );
2628     }
2629     else
2630     {
2631         TRACE( "%s not found in dir %p\n", wine_dbgstr_longlong(file_id), attr->RootDirectory );
2632         RtlFreeHeap( GetProcessHeap(), 0, unix_name->Buffer );
2633     }
2634     if (needs_close) close( root_fd );
2635     return status;
2636 }
2637
2638
2639 /******************************************************************************
2640  *           lookup_unix_name
2641  *
2642  * Helper for nt_to_unix_file_name
2643  */
2644 static NTSTATUS lookup_unix_name( const WCHAR *name, int name_len, char **buffer, int unix_len, int pos,
2645                                   UINT disposition, BOOLEAN check_case )
2646 {
2647     NTSTATUS status;
2648     int ret, used_default, len;
2649     struct stat st;
2650     char *unix_name = *buffer;
2651     const BOOL redirect = nb_redirects && ntdll_get_thread_data()->wow64_redir;
2652
2653     /* try a shortcut first */
2654
2655     ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2656                            NULL, &used_default );
2657
2658     while (name_len && IS_SEPARATOR(*name))
2659     {
2660         name++;
2661         name_len--;
2662     }
2663
2664     if (ret >= 0 && !used_default)  /* if we used the default char the name didn't convert properly */
2665     {
2666         char *p;
2667         unix_name[pos + ret] = 0;
2668         for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2669         if (!redirect || (!strstr( unix_name, "/windows/") && strncmp( unix_name, "windows/", 8 )))
2670         {
2671             if (!stat( unix_name, &st ))
2672             {
2673                 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2674                 if (disposition == FILE_CREATE)
2675                     return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2676                 return STATUS_SUCCESS;
2677             }
2678         }
2679     }
2680
2681     if (!name_len)  /* empty name -> drive root doesn't exist */
2682         return STATUS_OBJECT_PATH_NOT_FOUND;
2683     if (check_case && !redirect && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2684         return STATUS_OBJECT_NAME_NOT_FOUND;
2685
2686     /* now do it component by component */
2687
2688     while (name_len)
2689     {
2690         const WCHAR *end, *next;
2691         int is_win_dir = 0;
2692
2693         end = name;
2694         while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2695         next = end;
2696         while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2697         name_len -= next - name;
2698
2699         /* grow the buffer if needed */
2700
2701         if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2702         {
2703             char *new_name;
2704             unix_len += 2 * MAX_DIR_ENTRY_LEN;
2705             if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2706                 return STATUS_NO_MEMORY;
2707             unix_name = *buffer = new_name;
2708         }
2709
2710         status = find_file_in_dir( unix_name, pos, name, end - name,
2711                                    check_case, redirect ? &is_win_dir : NULL );
2712
2713         /* if this is the last element, not finding it is not necessarily fatal */
2714         if (!name_len)
2715         {
2716             if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2717             {
2718                 status = STATUS_OBJECT_NAME_NOT_FOUND;
2719                 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2720                 {
2721                     ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2722                                            MAX_DIR_ENTRY_LEN, NULL, &used_default );
2723                     if (ret > 0 && !used_default)
2724                     {
2725                         unix_name[pos] = '/';
2726                         unix_name[pos + 1 + ret] = 0;
2727                         status = STATUS_NO_SUCH_FILE;
2728                         break;
2729                     }
2730                 }
2731             }
2732             else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2733             {
2734                 status = STATUS_OBJECT_NAME_COLLISION;
2735             }
2736         }
2737
2738         if (status != STATUS_SUCCESS) break;
2739
2740         pos += strlen( unix_name + pos );
2741         name = next;
2742
2743         if (is_win_dir && (len = get_redirect_path( unix_name, pos, name, name_len, check_case )))
2744         {
2745             name += len;
2746             name_len -= len;
2747             pos += strlen( unix_name + pos );
2748             TRACE( "redirecting -> %s + %s\n", debugstr_a(unix_name), debugstr_w(name) );
2749         }
2750     }
2751
2752     return status;
2753 }
2754
2755
2756 /******************************************************************************
2757  *           nt_to_unix_file_name_attr
2758  */
2759 NTSTATUS nt_to_unix_file_name_attr( const OBJECT_ATTRIBUTES *attr, ANSI_STRING *unix_name_ret,
2760                                     UINT disposition )
2761 {
2762     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2763     enum server_fd_type type;
2764     int old_cwd, root_fd, needs_close;
2765     const WCHAR *name, *p;
2766     char *unix_name;
2767     int name_len, unix_len;
2768     NTSTATUS status;
2769     BOOLEAN check_case = !(attr->Attributes & OBJ_CASE_INSENSITIVE);
2770
2771     if (!attr->RootDirectory)  /* without root dir fall back to normal lookup */
2772         return wine_nt_to_unix_file_name( attr->ObjectName, unix_name_ret, disposition, check_case );
2773
2774     name     = attr->ObjectName->Buffer;
2775     name_len = attr->ObjectName->Length / sizeof(WCHAR);
2776
2777     if (name_len && IS_SEPARATOR(name[0])) return STATUS_INVALID_PARAMETER;
2778
2779     /* check for invalid characters */
2780     for (p = name; p < name + name_len; p++)
2781         if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2782
2783     unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2784     unix_len += MAX_DIR_ENTRY_LEN + 3;
2785     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2786         return STATUS_NO_MEMORY;
2787     unix_name[0] = '.';
2788
2789     if (!(status = server_get_unix_fd( attr->RootDirectory, 0, &root_fd, &needs_close, &type, NULL )))
2790     {
2791         if (type != FD_TYPE_DIR)
2792         {
2793             if (needs_close) close( root_fd );
2794             status = STATUS_BAD_DEVICE_TYPE;
2795         }
2796         else
2797         {
2798             RtlEnterCriticalSection( &dir_section );
2799             if ((old_cwd = open( ".", O_RDONLY )) != -1 && fchdir( root_fd ) != -1)
2800             {
2801                 status = lookup_unix_name( name, name_len, &unix_name, unix_len, 1,
2802                                            disposition, check_case );
2803                 if (fchdir( old_cwd ) == -1) chdir( "/" );
2804             }
2805             else status = FILE_GetNtStatus();
2806             RtlLeaveCriticalSection( &dir_section );
2807             if (old_cwd != -1) close( old_cwd );
2808             if (needs_close) close( root_fd );
2809         }
2810     }
2811     else if (status == STATUS_OBJECT_TYPE_MISMATCH) status = STATUS_BAD_DEVICE_TYPE;
2812
2813     if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2814     {
2815         TRACE( "%s -> %s\n", debugstr_us(attr->ObjectName), debugstr_a(unix_name) );
2816         unix_name_ret->Buffer = unix_name;
2817         unix_name_ret->Length = strlen(unix_name);
2818         unix_name_ret->MaximumLength = unix_len;
2819     }
2820     else
2821     {
2822         TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2823         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2824     }
2825     return status;
2826 }
2827
2828
2829 /******************************************************************************
2830  *           wine_nt_to_unix_file_name  (NTDLL.@) Not a Windows API
2831  *
2832  * Convert a file name from NT namespace to Unix namespace.
2833  *
2834  * If disposition is not FILE_OPEN or FILE_OVERWRITE, the last path
2835  * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2836  * returned, but the unix name is still filled in properly.
2837  */
2838 NTSTATUS CDECL wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2839                                           UINT disposition, BOOLEAN check_case )
2840 {
2841     static const WCHAR unixW[] = {'u','n','i','x'};
2842     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2843
2844     NTSTATUS status = STATUS_SUCCESS;
2845     const char *config_dir = wine_get_config_dir();
2846     const WCHAR *name, *p;
2847     struct stat st;
2848     char *unix_name;
2849     int pos, ret, name_len, unix_len, prefix_len, used_default;
2850     WCHAR prefix[MAX_DIR_ENTRY_LEN];
2851     BOOLEAN is_unix = FALSE;
2852
2853     name     = nameW->Buffer;
2854     name_len = nameW->Length / sizeof(WCHAR);
2855
2856     if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2857
2858     if (!(pos = get_dos_prefix_len( nameW )))
2859         return STATUS_BAD_DEVICE_TYPE;  /* no DOS prefix, assume NT native name */
2860
2861     name += pos;
2862     name_len -= pos;
2863
2864     /* check for sub-directory */
2865     for (pos = 0; pos < name_len; pos++)
2866     {
2867         if (IS_SEPARATOR(name[pos])) break;
2868         if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2869             return STATUS_OBJECT_NAME_INVALID;
2870     }
2871     if (pos > MAX_DIR_ENTRY_LEN)
2872         return STATUS_OBJECT_NAME_INVALID;
2873
2874     if (pos == name_len)  /* no subdir, plain DOS device */
2875         return get_dos_device( name, name_len, unix_name_ret );
2876
2877     for (prefix_len = 0; prefix_len < pos; prefix_len++)
2878         prefix[prefix_len] = tolowerW(name[prefix_len]);
2879
2880     name += prefix_len;
2881     name_len -= prefix_len;
2882
2883     /* check for invalid characters (all chars except 0 are valid for unix) */
2884     is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2885     if (is_unix)
2886     {
2887         for (p = name; p < name + name_len; p++)
2888             if (!*p) return STATUS_OBJECT_NAME_INVALID;
2889         check_case = TRUE;
2890     }
2891     else
2892     {
2893         for (p = name; p < name + name_len; p++)
2894             if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2895     }
2896
2897     unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2898     unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2899     unix_len += MAX_DIR_ENTRY_LEN + 3;
2900     unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2901     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2902         return STATUS_NO_MEMORY;
2903     strcpy( unix_name, config_dir );
2904     strcat( unix_name, "/dosdevices/" );
2905     pos = strlen(unix_name);
2906
2907     ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2908                            NULL, &used_default );
2909     if (!ret || used_default)
2910     {
2911         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2912         return STATUS_OBJECT_NAME_INVALID;
2913     }
2914     pos += ret;
2915
2916     /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2917
2918     if (prefix_len != 2 || prefix[1] != ':')
2919     {
2920         unix_name[pos] = 0;
2921         if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2922         {
2923             if (!is_unix)
2924             {
2925                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2926                 return STATUS_BAD_DEVICE_TYPE;
2927             }
2928             pos = 0;  /* fall back to unix root */
2929         }
2930     }
2931
2932     status = lookup_unix_name( name, name_len, &unix_name, unix_len, pos, disposition, check_case );
2933     if (status == STATUS_SUCCESS || status == STATUS_NO_SUCH_FILE)
2934     {
2935         TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2936         unix_name_ret->Buffer = unix_name;
2937         unix_name_ret->Length = strlen(unix_name);
2938         unix_name_ret->MaximumLength = unix_len;
2939     }
2940     else
2941     {
2942         TRACE( "%s not found in %s\n", debugstr_w(name), unix_name );
2943         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2944     }
2945     return status;
2946 }
2947
2948
2949 /******************************************************************
2950  *              RtlWow64EnableFsRedirection   (NTDLL.@)
2951  */
2952 NTSTATUS WINAPI RtlWow64EnableFsRedirection( BOOLEAN enable )
2953 {
2954     if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2955     ntdll_get_thread_data()->wow64_redir = enable;
2956     return STATUS_SUCCESS;
2957 }
2958
2959
2960 /******************************************************************
2961  *              RtlWow64EnableFsRedirectionEx   (NTDLL.@)
2962  */
2963 NTSTATUS WINAPI RtlWow64EnableFsRedirectionEx( ULONG disable, ULONG *old_value )
2964 {
2965     if (!is_wow64) return STATUS_NOT_IMPLEMENTED;
2966     *old_value = !ntdll_get_thread_data()->wow64_redir;
2967     ntdll_get_thread_data()->wow64_redir = !disable;
2968     return STATUS_SUCCESS;
2969 }
2970
2971
2972 /******************************************************************
2973  *              RtlDoesFileExists_U   (NTDLL.@)
2974  */
2975 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2976 {
2977     UNICODE_STRING nt_name;
2978     FILE_BASIC_INFORMATION basic_info;
2979     OBJECT_ATTRIBUTES attr;
2980     BOOLEAN ret;
2981
2982     if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2983
2984     attr.Length = sizeof(attr);
2985     attr.RootDirectory = 0;
2986     attr.ObjectName = &nt_name;
2987     attr.Attributes = OBJ_CASE_INSENSITIVE;
2988     attr.SecurityDescriptor = NULL;
2989     attr.SecurityQualityOfService = NULL;
2990
2991     ret = NtQueryAttributesFile(&attr, &basic_info) == STATUS_SUCCESS;
2992
2993     RtlFreeUnicodeString( &nt_name );
2994     return ret;
2995 }
2996
2997
2998 /***********************************************************************
2999  *           DIR_unmount_device
3000  *
3001  * Unmount the specified device.
3002  */
3003 NTSTATUS DIR_unmount_device( HANDLE handle )
3004 {
3005     NTSTATUS status;
3006     int unix_fd, needs_close;
3007
3008     if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
3009     {
3010         struct stat st;
3011         char *mount_point = NULL;
3012
3013         if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
3014             status = STATUS_INVALID_PARAMETER;
3015         else
3016         {
3017             if ((mount_point = get_device_mount_point( st.st_rdev )))
3018             {
3019 #ifdef __APPLE__
3020                 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
3021 #else
3022                 static const char umount[] = "umount >/dev/null 2>&1 ";
3023 #endif
3024                 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
3025                 if (cmd)
3026                 {
3027                     strcpy( cmd, umount );
3028                     strcat( cmd, mount_point );
3029                     system( cmd );
3030                     RtlFreeHeap( GetProcessHeap(), 0, cmd );
3031 #ifdef linux
3032                     /* umount will fail to release the loop device since we still have
3033                        a handle to it, so we release it here */
3034                     if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
3035 #endif
3036                 }
3037                 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
3038             }
3039         }
3040         if (needs_close) close( unix_fd );
3041     }
3042     return status;
3043 }
3044
3045
3046 /******************************************************************************
3047  *           DIR_get_unix_cwd
3048  *
3049  * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
3050  * Returned value must be freed by caller.
3051  */
3052 NTSTATUS DIR_get_unix_cwd( char **cwd )
3053 {
3054     int old_cwd, unix_fd, needs_close;
3055     CURDIR *curdir;
3056     HANDLE handle;
3057     NTSTATUS status;
3058
3059     RtlAcquirePebLock();
3060
3061     if (NtCurrentTeb()->Tib.SubSystemTib)  /* FIXME: hack */
3062         curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
3063     else
3064         curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
3065
3066     if (!(handle = curdir->Handle))
3067     {
3068         UNICODE_STRING dirW;
3069         OBJECT_ATTRIBUTES attr;
3070         IO_STATUS_BLOCK io;
3071
3072         if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
3073         {
3074             status = STATUS_OBJECT_NAME_INVALID;
3075             goto done;
3076         }
3077         attr.Length = sizeof(attr);
3078         attr.RootDirectory = 0;
3079         attr.Attributes = OBJ_CASE_INSENSITIVE;
3080         attr.ObjectName = &dirW;
3081         attr.SecurityDescriptor = NULL;
3082         attr.SecurityQualityOfService = NULL;
3083
3084         status = NtOpenFile( &handle, 0, &attr, &io, 0,
3085                              FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
3086         RtlFreeUnicodeString( &dirW );
3087         if (status != STATUS_SUCCESS) goto done;
3088     }
3089
3090     if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
3091     {
3092         RtlEnterCriticalSection( &dir_section );
3093
3094         if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
3095         {
3096             unsigned int size = 512;
3097
3098             for (;;)
3099             {
3100                 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
3101                 {
3102                     status = STATUS_NO_MEMORY;
3103                     break;
3104                 }
3105                 if (getcwd( *cwd, size )) break;
3106                 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
3107                 if (errno != ERANGE)
3108                 {
3109                     status = STATUS_OBJECT_PATH_INVALID;
3110                     break;
3111                 }
3112                 size *= 2;
3113             }
3114             if (fchdir( old_cwd ) == -1) chdir( "/" );
3115         }
3116         else status = FILE_GetNtStatus();
3117
3118         RtlLeaveCriticalSection( &dir_section );
3119         if (old_cwd != -1) close( old_cwd );
3120         if (needs_close) close( unix_fd );
3121     }
3122     if (!curdir->Handle) NtClose( handle );
3123
3124 done:
3125     RtlReleasePebLock();
3126     return status;
3127 }
3128
3129 struct read_changes_info
3130 {
3131     HANDLE FileHandle;
3132     PVOID Buffer;
3133     ULONG BufferSize;
3134     PIO_APC_ROUTINE apc;
3135     void           *apc_arg;
3136 };
3137
3138 /* callback for ioctl user APC */
3139 static void WINAPI read_changes_user_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
3140 {
3141     struct read_changes_info *info = arg;
3142     if (info->apc) info->apc( info->apc_arg, io, reserved );
3143     RtlFreeHeap( GetProcessHeap(), 0, info );
3144 }
3145
3146 static NTSTATUS read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc )
3147 {
3148     struct read_changes_info *info = user;
3149     char data[PATH_MAX];
3150     NTSTATUS ret;
3151     int size;
3152
3153     SERVER_START_REQ( read_change )
3154     {
3155         req->handle = wine_server_obj_handle( info->FileHandle );
3156         wine_server_set_reply( req, data, PATH_MAX );
3157         ret = wine_server_call( req );
3158         size = wine_server_reply_size( reply );
3159     }
3160     SERVER_END_REQ;
3161
3162     if (ret == STATUS_SUCCESS && info->Buffer)
3163     {
3164         PFILE_NOTIFY_INFORMATION pfni = info->Buffer;
3165         int i, left = info->BufferSize;
3166         DWORD *last_entry_offset = NULL;
3167         struct filesystem_event *event = (struct filesystem_event*)data;
3168
3169         while (size && left >= sizeof(*pfni))
3170         {
3171             /* convert to an NT style path */
3172             for (i=0; i<event->len; i++)
3173                 if (event->name[i] == '/')
3174                     event->name[i] = '\\';
3175
3176             pfni->Action = event->action;
3177             pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
3178                     (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
3179             last_entry_offset = &pfni->NextEntryOffset;
3180
3181             if(pfni->FileNameLength == -1 || pfni->FileNameLength == -2)
3182                 break;
3183
3184             i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
3185             pfni->FileNameLength *= sizeof(WCHAR);
3186             pfni->NextEntryOffset = i;
3187             pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
3188             left -= i;
3189
3190             i = (offsetof(struct filesystem_event, name[event->len])
3191                     + sizeof(int)-1) / sizeof(int) * sizeof(int);
3192             event = (struct filesystem_event*)((char*)event + i);
3193             size -= i;
3194         }
3195
3196         if (size)
3197         {
3198             ret = STATUS_NOTIFY_ENUM_DIR;
3199             size = 0;
3200         }
3201         else
3202         {
3203             *last_entry_offset = 0;
3204             size = info->BufferSize - left;
3205         }
3206     }
3207     else
3208     {
3209         ret = STATUS_NOTIFY_ENUM_DIR;
3210         size = 0;
3211     }
3212
3213     iosb->u.Status = ret;
3214     iosb->Information = size;
3215     *apc = read_changes_user_apc;
3216     return ret;
3217 }
3218
3219 #define FILE_NOTIFY_ALL        (  \
3220  FILE_NOTIFY_CHANGE_FILE_NAME   | \
3221  FILE_NOTIFY_CHANGE_DIR_NAME    | \
3222  FILE_NOTIFY_CHANGE_ATTRIBUTES  | \
3223  FILE_NOTIFY_CHANGE_SIZE        | \
3224  FILE_NOTIFY_CHANGE_LAST_WRITE  | \
3225  FILE_NOTIFY_CHANGE_LAST_ACCESS | \
3226  FILE_NOTIFY_CHANGE_CREATION    | \
3227  FILE_NOTIFY_CHANGE_SECURITY   )
3228
3229 /******************************************************************************
3230  *  NtNotifyChangeDirectoryFile [NTDLL.@]
3231  */
3232 NTSTATUS WINAPI
3233 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
3234         PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
3235         PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
3236         ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
3237 {
3238     struct read_changes_info *info;
3239     NTSTATUS status;
3240     ULONG_PTR cvalue = ApcRoutine ? 0 : (ULONG_PTR)ApcContext;
3241
3242     TRACE("%p %p %p %p %p %p %u %u %d\n",
3243           FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
3244           Buffer, BufferSize, CompletionFilter, WatchTree );
3245
3246     if (!IoStatusBlock)
3247         return STATUS_ACCESS_VIOLATION;
3248
3249     if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
3250         return STATUS_INVALID_PARAMETER;
3251
3252     info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
3253     if (!info)
3254         return STATUS_NO_MEMORY;
3255
3256     info->FileHandle = FileHandle;
3257     info->Buffer     = Buffer;
3258     info->BufferSize = BufferSize;
3259     info->apc        = ApcRoutine;
3260     info->apc_arg    = ApcContext;
3261
3262     SERVER_START_REQ( read_directory_changes )
3263     {
3264         req->filter     = CompletionFilter;
3265         req->want_data  = (Buffer != NULL);
3266         req->subtree    = WatchTree;
3267         req->async.handle   = wine_server_obj_handle( FileHandle );
3268         req->async.callback = wine_server_client_ptr( read_changes_apc );
3269         req->async.iosb     = wine_server_client_ptr( IoStatusBlock );
3270         req->async.arg      = wine_server_client_ptr( info );
3271         req->async.event    = wine_server_obj_handle( Event );
3272         req->async.cvalue   = cvalue;
3273         status = wine_server_call( req );
3274     }
3275     SERVER_END_REQ;
3276
3277     if (status != STATUS_PENDING)
3278         RtlFreeHeap( GetProcessHeap(), 0, info );
3279
3280     return status;
3281 }