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