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