Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / ntdll / directory.c
blob5e3eca6cdeb565093ad1779f21bb207d4d19b1b8
1 /*
2 * NTDLL directory functions
4 * Copyright 1993 Erik Bos
5 * Copyright 2003 Eric Pouech
6 * Copyright 1996, 2004 Alexandre Julliard
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.
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.
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
23 #include "config.h"
24 #include "wine/port.h"
26 #include <sys/types.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <stdarg.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <limits.h>
35 #ifdef HAVE_MNTENT_H
36 #include <mntent.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_IOCTL_H
42 #include <sys/ioctl.h>
43 #endif
44 #ifdef HAVE_LINUX_IOCTL_H
45 #include <linux/ioctl.h>
46 #endif
47 #ifdef HAVE_LINUX_MAJOR_H
48 # include <linux/major.h>
49 #endif
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
52 #endif
53 #ifdef HAVE_SYS_MOUNT_H
54 #include <sys/mount.h>
55 #endif
56 #include <time.h>
57 #ifdef HAVE_UNISTD_H
58 # include <unistd.h>
59 #endif
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
63 #include "ntstatus.h"
64 #define WIN32_NO_STATUS
65 #include "windef.h"
66 #include "winnt.h"
67 #include "thread.h"
68 #include "winternl.h"
69 #include "ntdll_misc.h"
70 #include "wine/unicode.h"
71 #include "wine/server.h"
72 #include "wine/library.h"
73 #include "wine/debug.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(file);
77 /* just in case... */
78 #undef VFAT_IOCTL_READDIR_BOTH
79 #undef USE_GETDENTS
81 #ifdef linux
83 /* We want the real kernel dirent structure, not the libc one */
84 typedef struct
86 long d_ino;
87 long d_off;
88 unsigned short d_reclen;
89 char d_name[256];
90 } KERNEL_DIRENT;
92 /* Define the VFAT ioctl to get both short and long file names */
93 #define VFAT_IOCTL_READDIR_BOTH _IOR('r', 1, KERNEL_DIRENT [2] )
95 #ifndef O_DIRECTORY
96 # define O_DIRECTORY 0200000 /* must be directory */
97 #endif
99 #ifdef __i386__
101 typedef struct
103 ULONG64 d_ino;
104 LONG64 d_off;
105 unsigned short d_reclen;
106 unsigned char d_type;
107 char d_name[256];
108 } KERNEL_DIRENT64;
110 static inline int getdents64( int fd, char *de, unsigned int size )
112 int ret;
113 __asm__( "pushl %%ebx; movl %2,%%ebx; int $0x80; popl %%ebx"
114 : "=a" (ret)
115 : "0" (220 /*NR_getdents64*/), "r" (fd), "c" (de), "d" (size)
116 : "memory" );
117 if (ret < 0)
119 errno = -ret;
120 ret = -1;
122 return ret;
124 #define USE_GETDENTS
126 #endif /* i386 */
128 #endif /* linux */
130 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
131 #define IS_SEPARATOR(ch) ((ch) == '\\' || (ch) == '/')
133 #define INVALID_NT_CHARS '*','?','<','>','|','"'
134 #define INVALID_DOS_CHARS INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
136 #define MAX_DIR_ENTRY_LEN 255 /* max length of a directory entry in chars */
138 static const unsigned int max_dir_info_size = FIELD_OFFSET( FILE_BOTH_DIR_INFORMATION, FileName[MAX_DIR_ENTRY_LEN] );
140 static int show_dot_files = -1;
142 /* at some point we may want to allow Winelib apps to set this */
143 static const int is_case_sensitive = FALSE;
145 static RTL_CRITICAL_SECTION dir_section;
146 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
148 0, 0, &dir_section,
149 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
150 0, 0, { (DWORD_PTR)(__FILE__ ": dir_section") }
152 static RTL_CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
155 /* check if a given Unicode char is OK in a DOS short name */
156 static inline BOOL is_invalid_dos_char( WCHAR ch )
158 static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
159 if (ch > 0x7f) return TRUE;
160 return strchrW( invalid_chars, ch ) != NULL;
163 /* check if the device can be a mounted volume */
164 static inline int is_valid_mounted_device( struct stat *st )
166 #if defined(linux) || defined(__sun__)
167 return S_ISBLK( st->st_mode );
168 #else
169 /* disks are char devices on *BSD */
170 return S_ISCHR( st->st_mode );
171 #endif
174 /***********************************************************************
175 * get_default_com_device
177 * Return the default device to use for serial ports.
179 static char *get_default_com_device( int num )
181 char *ret = NULL;
183 if (!num || num > 9) return ret;
184 #ifdef linux
185 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
186 if (ret)
188 strcpy( ret, "/dev/ttyS0" );
189 ret[strlen(ret) - 1] = '0' + num - 1;
191 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
192 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/cuad0") );
193 if (ret)
195 strcpy( ret, "/dev/cuad0" );
196 ret[strlen(ret) - 1] = '0' + num - 1;
198 #else
199 FIXME( "no known default for device com%d\n", num );
200 #endif
201 return ret;
205 /***********************************************************************
206 * get_default_lpt_device
208 * Return the default device to use for parallel ports.
210 static char *get_default_lpt_device( int num )
212 char *ret = NULL;
214 if (!num || num > 9) return ret;
215 #ifdef linux
216 ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
217 if (ret)
219 strcpy( ret, "/dev/lp0" );
220 ret[strlen(ret) - 1] = '0' + num - 1;
222 #else
223 FIXME( "no known default for device lpt%d\n", num );
224 #endif
225 return ret;
229 /***********************************************************************
230 * parse_mount_entries
232 * Parse mount entries looking for a given device. Helper for get_default_drive_device.
235 #ifdef sun
236 #include <sys/vfstab.h>
237 static char *parse_vfstab_entries( FILE *f, dev_t dev, ino_t ino)
239 struct vfstab entry;
240 struct stat st;
241 char *device;
243 while (! getvfsent( f, &entry ))
245 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
246 if (!strcmp( entry.vfs_fstype, "nfs" ) ||
247 !strcmp( entry.vfs_fstype, "smbfs" ) ||
248 !strcmp( entry.vfs_fstype, "ncpfs" )) continue;
250 if (stat( entry.vfs_mountp, &st ) == -1) continue;
251 if (st.st_dev != dev || st.st_ino != ino) continue;
252 if (!strcmp( entry.vfs_fstype, "fd" ))
254 if ((device = strstr( entry.vfs_mntopts, "dev=" )))
256 char *p = strchr( device + 4, ',' );
257 if (p) *p = 0;
258 return device + 4;
261 else
262 return entry.vfs_special;
264 return NULL;
266 #endif
268 #ifdef linux
269 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
271 struct mntent *entry;
272 struct stat st;
273 char *device;
275 while ((entry = getmntent( f )))
277 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
278 if (!strcmp( entry->mnt_type, "nfs" ) ||
279 !strcmp( entry->mnt_type, "smbfs" ) ||
280 !strcmp( entry->mnt_type, "ncpfs" )) continue;
282 if (stat( entry->mnt_dir, &st ) == -1) continue;
283 if (st.st_dev != dev || st.st_ino != ino) continue;
284 if (!strcmp( entry->mnt_type, "supermount" ))
286 if ((device = strstr( entry->mnt_opts, "dev=" )))
288 char *p = strchr( device + 4, ',' );
289 if (p) *p = 0;
290 return device + 4;
293 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
295 /* if device is a regular file check for a loop mount */
296 if ((device = strstr( entry->mnt_opts, "loop=" )))
298 char *p = strchr( device + 5, ',' );
299 if (p) *p = 0;
300 return device + 5;
303 else
304 return entry->mnt_fsname;
306 return NULL;
308 #endif
310 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
311 #include <fstab.h>
312 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
314 struct fstab *entry;
315 struct stat st;
317 while ((entry = getfsent()))
319 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
320 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
321 !strcmp( entry->fs_vfstype, "smbfs" ) ||
322 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
324 if (stat( entry->fs_file, &st ) == -1) continue;
325 if (st.st_dev != dev || st.st_ino != ino) continue;
326 return entry->fs_spec;
328 return NULL;
330 #endif
332 #ifdef sun
333 #include <sys/mnttab.h>
334 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
336 struct mnttab entry;
337 struct stat st;
338 char *device;
341 while (( ! getmntent( f, &entry) ))
343 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
344 if (!strcmp( entry.mnt_fstype, "nfs" ) ||
345 !strcmp( entry.mnt_fstype, "smbfs" ) ||
346 !strcmp( entry.mnt_fstype, "ncpfs" )) continue;
348 if (stat( entry.mnt_mountp, &st ) == -1) continue;
349 if (st.st_dev != dev || st.st_ino != ino) continue;
350 if (!strcmp( entry.mnt_fstype, "fd" ))
352 if ((device = strstr( entry.mnt_mntopts, "dev=" )))
354 char *p = strchr( device + 4, ',' );
355 if (p) *p = 0;
356 return device + 4;
359 else
360 return entry.mnt_special;
362 return NULL;
364 #endif
366 /***********************************************************************
367 * get_default_drive_device
369 * Return the default device to use for a given drive mount point.
371 static char *get_default_drive_device( const char *root )
373 char *ret = NULL;
375 #ifdef linux
376 FILE *f;
377 char *device = NULL;
378 int fd, res = -1;
379 struct stat st;
381 /* try to open it first to force it to get mounted */
382 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
384 res = fstat( fd, &st );
385 close( fd );
387 /* now try normal stat just in case */
388 if (res == -1) res = stat( root, &st );
389 if (res == -1) return NULL;
391 RtlEnterCriticalSection( &dir_section );
393 if ((f = fopen( "/etc/mtab", "r" )))
395 device = parse_mount_entries( f, st.st_dev, st.st_ino );
396 endmntent( f );
398 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
399 if (!device && (f = fopen( "/etc/fstab", "r" )))
401 device = parse_mount_entries( f, st.st_dev, st.st_ino );
402 endmntent( f );
404 if (device)
406 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
407 if (ret) strcpy( ret, device );
409 RtlLeaveCriticalSection( &dir_section );
411 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
412 char *device = NULL;
413 int fd, res = -1;
414 struct stat st;
416 /* try to open it first to force it to get mounted */
417 if ((fd = open( root, O_RDONLY )) != -1)
419 res = fstat( fd, &st );
420 close( fd );
422 /* now try normal stat just in case */
423 if (res == -1) res = stat( root, &st );
424 if (res == -1) return NULL;
426 RtlEnterCriticalSection( &dir_section );
428 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
429 * pass NULL. Leave the argument in for symmetry.
431 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
432 if (device)
434 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
435 if (ret) strcpy( ret, device );
437 RtlLeaveCriticalSection( &dir_section );
439 #elif defined( sun )
440 FILE *f;
441 char *device = NULL;
442 int fd, res = -1;
443 struct stat st;
445 /* try to open it first to force it to get mounted */
446 if ((fd = open( root, O_RDONLY )) != -1)
448 res = fstat( fd, &st );
449 close( fd );
451 /* now try normal stat just in case */
452 if (res == -1) res = stat( root, &st );
453 if (res == -1) return NULL;
455 RtlEnterCriticalSection( &dir_section );
457 if ((f = fopen( "/etc/mnttab", "r" )))
459 device = parse_mount_entries( f, st.st_dev, st.st_ino);
460 fclose( f );
462 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
463 if (!device && (f = fopen( "/etc/vfstab", "r" )))
465 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
466 fclose( f );
468 if (device)
470 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
471 if (ret) strcpy( ret, device );
473 RtlLeaveCriticalSection( &dir_section );
475 #elif defined(__APPLE__)
476 struct statfs *mntStat;
477 struct stat st;
478 int i;
479 int mntSize;
480 dev_t dev;
481 ino_t ino;
482 static const char path_bsd_device[] = "/dev/disk";
483 int res;
485 res = stat( root, &st );
486 if (res == -1) return NULL;
488 dev = st.st_dev;
489 ino = st.st_ino;
491 RtlEnterCriticalSection( &dir_section );
493 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
495 for (i = 0; i < mntSize && !ret; i++)
497 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
498 if (st.st_dev != dev || st.st_ino != ino) continue;
500 /* FIXME add support for mounted network drive */
501 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
503 /* set return value to the corresponding raw BSD node */
504 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
505 if (ret)
507 strcpy(ret, "/dev/r");
508 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
512 RtlLeaveCriticalSection( &dir_section );
513 #else
514 static int warned;
515 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
516 #endif
517 return ret;
521 /***********************************************************************
522 * get_device_mount_point
524 * Return the current mount point for a device.
526 static char *get_device_mount_point( dev_t dev )
528 char *ret = NULL;
530 #ifdef linux
531 FILE *f;
533 RtlEnterCriticalSection( &dir_section );
535 if ((f = fopen( "/etc/mtab", "r" )))
537 struct mntent *entry;
538 struct stat st;
539 char *p, *device;
541 while ((entry = getmntent( f )))
543 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
544 if (!strcmp( entry->mnt_type, "nfs" ) ||
545 !strcmp( entry->mnt_type, "smbfs" ) ||
546 !strcmp( entry->mnt_type, "ncpfs" )) continue;
548 if (!strcmp( entry->mnt_type, "supermount" ))
550 if ((device = strstr( entry->mnt_opts, "dev=" )))
552 device += 4;
553 if ((p = strchr( device, ',' ))) *p = 0;
556 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
558 /* if device is a regular file check for a loop mount */
559 if ((device = strstr( entry->mnt_opts, "loop=" )))
561 device += 5;
562 if ((p = strchr( device, ',' ))) *p = 0;
565 else device = entry->mnt_fsname;
567 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
569 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
570 if (ret) strcpy( ret, entry->mnt_dir );
571 break;
574 endmntent( f );
576 RtlLeaveCriticalSection( &dir_section );
577 #elif defined(__APPLE__)
578 struct statfs *entry;
579 struct stat st;
580 int i, size;
582 RtlEnterCriticalSection( &dir_section );
584 size = getmntinfo( &entry, MNT_NOWAIT );
585 for (i = 0; i < size; i++)
587 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
588 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
590 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
591 if (ret) strcpy( ret, entry[i].f_mntfromname );
592 break;
595 RtlLeaveCriticalSection( &dir_section );
596 #else
597 static int warned;
598 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
599 #endif
600 return ret;
604 /***********************************************************************
605 * get_autofs_mount_points
607 * Return a list of autofs mount points.
609 static struct drive_info *get_autofs_mount_points( unsigned int *ret_count )
611 struct drive_info *ret = NULL;
613 #ifdef linux
614 unsigned int count, total;
615 struct mntent *entry;
616 struct stat st;
617 FILE *f;
619 if (!(f = fopen( "/etc/mtab", "r" ))) return NULL;
620 count = total = 0;
621 while ((entry = getmntent( f )))
623 if (strcmp( entry->mnt_type, "autofs" )) continue;
624 if (stat( entry->mnt_dir, &st ) == -1) continue;
625 if (count >= total)
627 total += 16;
628 if (!ret) ret = RtlAllocateHeap( GetProcessHeap(), 0, total * sizeof(*ret) );
629 else
631 void *new = RtlReAllocateHeap( GetProcessHeap(), 0, ret, total * sizeof(*ret) );
632 if (!new) RtlFreeHeap( GetProcessHeap(), 0, ret );
633 ret = new;
635 if (!ret) break;
637 ret[count].dev = st.st_dev;
638 ret[count].ino = st.st_ino;
639 count++;
641 *ret_count = count;
642 endmntent( f );
643 #endif
644 return ret;
648 /***********************************************************************
649 * read_drive_symlink
651 * Read the symlink for a given drive and return the resulting full path.
653 static char *read_drive_symlink( char *dos_device, unsigned int *prefix )
655 char *buffer, *p;
656 int ret, size = 128;
658 if (!(p = strrchr( dos_device, '/' ))) p = dos_device;
659 else p++;
661 for (;;)
663 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size + (p - dos_device) )))
665 errno = ENOMEM;
666 return NULL;
668 ret = readlink( dos_device, buffer, size );
669 if (ret == -1)
671 RtlFreeHeap( GetProcessHeap(), 0, buffer );
672 return NULL;
674 if (ret != size)
676 buffer[ret] = 0;
677 break;
679 RtlFreeHeap( GetProcessHeap(), 0, buffer );
680 size *= 2;
682 if (buffer[0] != '/')
684 memmove( buffer + (p - dos_device), buffer, strlen(buffer) + 1 );
685 memcpy( buffer, dos_device, p - dos_device );
686 *prefix = p - dos_device;
688 else *prefix = 0;
689 return buffer;
693 /***********************************************************************
694 * is_drive_automounted
696 * Check if any element of the specified dosdevice is inside an autofs
697 * mount point and isn't currently mounted.
699 static int is_drive_automounted( char *dos_device, struct drive_info *mount_points, unsigned int count )
701 struct stat st;
702 unsigned int i, start;
703 char *symlink, *next, *p;
705 if (!(symlink = read_drive_symlink( dos_device, &start ))) return -1;
707 p = symlink + start;
708 while (*p == '/') p++; /* skip leading slashes */
709 for (;;)
711 while (*p && *p != '/') p++;
712 next = p;
713 while (*next == '/') next++;
714 if (!*next) break; /* don't stat the last element */
715 *p = 0;
716 if (stat( symlink, &st ) != -1)
718 for (i = 0; i < count; i++)
719 if (mount_points[i].dev == st.st_dev && mount_points[i].ino == st.st_ino) break;
720 if (i < count)
722 /* now check if the next path element exists, without triggering a mount */
723 struct dirent *de;
724 DIR *dir = opendir( symlink );
725 if (!dir) break;
726 while ((de = readdir( dir )))
728 unsigned int len = strlen(de->d_name);
729 if (!strncmp( de->d_name, next, len ) && (!next[len] || next[len] == '/'))
730 break;
732 closedir( dir );
733 if (!de) /* not found in the dir -> automounted */
735 TRACE( "%s is automounted under %s\n", dos_device, symlink );
736 RtlFreeHeap( GetProcessHeap(), 0, symlink );
737 return 1;
739 TRACE( "%s found in %s -> already mounted\n", next, symlink );
742 *p = '/';
743 p = next;
745 RtlFreeHeap( GetProcessHeap(), 0, symlink );
746 return 0;
750 /***********************************************************************
751 * get_drives_info
753 * Retrieve device/inode number for all the drives.
755 int DIR_get_drives_info( struct drive_info info[MAX_DOS_DRIVES] )
757 const char *config_dir = wine_get_config_dir();
758 char *buffer, *p;
759 struct stat st;
760 int i, ret;
761 unsigned int count = 0;
762 struct drive_info *mount_points;
764 buffer = RtlAllocateHeap( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") );
765 if (!buffer) return 0;
766 strcpy( buffer, config_dir );
767 strcat( buffer, "/dosdevices/a:" );
768 p = buffer + strlen(buffer) - 2;
770 mount_points = get_autofs_mount_points( &count );
772 for (i = ret = 0; i < MAX_DOS_DRIVES; i++)
774 info[i].dev = 0;
775 info[i].ino = 0;
776 *p = 'a' + i;
777 /* skip the stat for automounted drives to avoid triggering a mount */
778 if (mount_points)
780 int res = is_drive_automounted( buffer, mount_points, count );
781 if (res > 0 || (res == -1 && errno == ENOENT)) continue;
783 if (!stat( buffer, &st ))
785 info[i].dev = st.st_dev;
786 info[i].ino = st.st_ino;
787 ret++;
790 RtlFreeHeap( GetProcessHeap(), 0, mount_points );
791 RtlFreeHeap( GetProcessHeap(), 0, buffer );
792 return ret;
796 /***********************************************************************
797 * init_options
799 * Initialize the show_dot_files options.
801 static void init_options(void)
803 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
804 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
805 char tmp[80];
806 HANDLE root, hkey;
807 DWORD dummy;
808 OBJECT_ATTRIBUTES attr;
809 UNICODE_STRING nameW;
811 show_dot_files = 0;
813 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
814 attr.Length = sizeof(attr);
815 attr.RootDirectory = root;
816 attr.ObjectName = &nameW;
817 attr.Attributes = 0;
818 attr.SecurityDescriptor = NULL;
819 attr.SecurityQualityOfService = NULL;
820 RtlInitUnicodeString( &nameW, WineW );
822 /* @@ Wine registry key: HKCU\Software\Wine */
823 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
825 RtlInitUnicodeString( &nameW, ShowDotFilesW );
826 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
828 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
829 show_dot_files = IS_OPTION_TRUE( str[0] );
831 NtClose( hkey );
833 NtClose( root );
837 /***********************************************************************
838 * DIR_is_hidden_file
840 * Check if the specified file should be hidden based on its name and the show dot files option.
842 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
844 WCHAR *p, *end;
846 if (show_dot_files == -1) init_options();
847 if (show_dot_files) return FALSE;
849 end = p = name->Buffer + name->Length/sizeof(WCHAR);
850 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
851 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
852 if (p == end || *p != '.') return FALSE;
853 /* make sure it isn't '.' or '..' */
854 if (p + 1 == end) return FALSE;
855 if (p[1] == '.' && p + 2 == end) return FALSE;
856 return TRUE;
860 /***********************************************************************
861 * hash_short_file_name
863 * Transform a Unix file name into a hashed DOS name. If the name is a valid
864 * DOS name, it is converted to upper-case; otherwise it is replaced by a
865 * hashed version that fits in 8.3 format.
866 * 'buffer' must be at least 12 characters long.
867 * Returns length of short name in bytes; short name is NOT null-terminated.
869 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
871 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
873 LPCWSTR p, ext, hash_end, end = name->Buffer + name->Length / sizeof(WCHAR);
874 LPWSTR dst;
875 unsigned short hash;
876 int i;
878 /* Find last dot for start of the extension */
879 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
881 /* don't include the standard 3 char .ext in the filename hash */
882 hash_end = end;
883 if (ext && ((end - ext) == 4 ))
886 * FIXME: CodeWeavers hack alert
887 * The next five lines are a nasty hack to only activate this
888 * (more correct behaviour) for Quicken files for the moment.
889 * We don't want to break our install base of programs that have
890 * shortfile names stored in the registry or elsewhere.
892 WCHAR szqdf[]={'.','q','d','f'};
893 WCHAR szqsd[]={'.','q','s','d'};
894 WCHAR szqel[]={'.','q','e','l'};
895 WCHAR szqph[]={'.','q','p','h'};
896 if (!strncmpiW(ext,szqdf,4) || !strncmpiW(ext,szqsd,4) ||
897 !strncmpiW(ext,szqph,4) || !strncmpiW(ext,szqel,4))
898 hash_end = ext;
901 /* Compute the hash code of the file name */
902 /* If you know something about hash functions, feel free to */
903 /* insert a better algorithm here... */
904 if (!is_case_sensitive)
906 for (p = name->Buffer, hash = 0xbeef; p < hash_end - 1; p++)
907 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
908 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
910 else
912 for (p = name->Buffer, hash = 0xbeef; p < hash_end - 1; p++)
913 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
914 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
917 /* Copy first 4 chars, replacing invalid chars with '_' */
918 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
920 if (p == end || p == ext) break;
921 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
923 /* Pad to 5 chars with '~' */
924 while (i-- >= 0) *dst++ = '~';
926 /* Insert hash code converted to 3 ASCII chars */
927 *dst++ = hash_chars[(hash >> 10) & 0x1f];
928 *dst++ = hash_chars[(hash >> 5) & 0x1f];
929 *dst++ = hash_chars[hash & 0x1f];
931 /* Copy the first 3 chars of the extension (if any) */
932 if (ext)
934 *dst++ = '.';
935 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
936 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
938 return dst - buffer;
942 /***********************************************************************
943 * match_filename
945 * Check a long file name against a mask.
947 * Tests (done in W95 DOS shell - case insensitive):
948 * *.txt test1.test.txt *
949 * *st1* test1.txt *
950 * *.t??????.t* test1.ta.tornado.txt *
951 * *tornado* test1.ta.tornado.txt *
952 * t*t test1.ta.tornado.txt *
953 * ?est* test1.txt *
954 * ?est??? test1.txt -
955 * *test1.txt* test1.txt *
956 * h?l?o*t.dat hellothisisatest.dat *
958 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
960 int mismatch;
961 const WCHAR *name = name_str->Buffer;
962 const WCHAR *mask = mask_str->Buffer;
963 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
964 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
965 const WCHAR *lastjoker = NULL;
966 const WCHAR *next_to_retry = NULL;
968 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
970 while (name < name_end && mask < mask_end)
972 switch(*mask)
974 case '*':
975 mask++;
976 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
977 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
978 lastjoker = mask;
980 /* skip to the next match after the joker(s) */
981 if (is_case_sensitive)
982 while (name < name_end && (*name != *mask)) name++;
983 else
984 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
985 next_to_retry = name;
986 break;
987 case '?':
988 mask++;
989 name++;
990 break;
991 default:
992 if (is_case_sensitive) mismatch = (*mask != *name);
993 else mismatch = (toupperW(*mask) != toupperW(*name));
995 if (!mismatch)
997 mask++;
998 name++;
999 if (mask == mask_end)
1001 if (name == name_end) return TRUE;
1002 if (lastjoker) mask = lastjoker;
1005 else /* mismatch ! */
1007 if (lastjoker) /* we had an '*', so we can try unlimitedly */
1009 mask = lastjoker;
1011 /* this scan sequence was a mismatch, so restart
1012 * 1 char after the first char we checked last time */
1013 next_to_retry++;
1014 name = next_to_retry;
1016 else return FALSE; /* bad luck */
1018 break;
1021 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
1022 mask++; /* Ignore trailing '.' or '*' in mask */
1023 return (name == name_end && mask == mask_end);
1027 /***********************************************************************
1028 * append_entry
1030 * helper for NtQueryDirectoryFile
1032 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
1033 const char *long_name, const char *short_name,
1034 const UNICODE_STRING *mask )
1036 FILE_BOTH_DIR_INFORMATION *info;
1037 int i, long_len, short_len, total_len;
1038 struct stat st;
1039 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
1040 WCHAR short_nameW[12];
1041 UNICODE_STRING str;
1043 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
1044 if (long_len == -1) return NULL;
1046 str.Buffer = long_nameW;
1047 str.Length = long_len * sizeof(WCHAR);
1048 str.MaximumLength = sizeof(long_nameW);
1050 if (short_name)
1052 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
1053 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
1054 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
1056 else /* generate a short name if necessary */
1058 BOOLEAN spaces;
1060 short_len = 0;
1061 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1062 short_len = hash_short_file_name( &str, short_nameW );
1065 TRACE( "long %s short %s mask %s\n",
1066 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
1068 if (mask && !match_filename( &str, mask ))
1070 if (!short_len) return NULL; /* no short name to match */
1071 str.Buffer = short_nameW;
1072 str.Length = short_len * sizeof(WCHAR);
1073 str.MaximumLength = sizeof(short_nameW);
1074 if (!match_filename( &str, mask )) return NULL;
1077 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
1078 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
1080 if (*pos + total_len > max_length) total_len = max_length - *pos;
1082 info->FileAttributes = 0;
1083 if (lstat( long_name, &st ) == -1) return NULL;
1084 if (S_ISLNK( st.st_mode ))
1086 if (stat( long_name, &st ) == -1) return NULL;
1087 if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
1090 info->NextEntryOffset = total_len;
1091 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
1093 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
1094 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
1095 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
1096 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
1098 if (S_ISDIR(st.st_mode))
1100 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
1101 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
1103 else
1105 info->EndOfFile.QuadPart = st.st_size;
1106 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
1107 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
1110 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1111 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1113 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
1114 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
1116 info->EaSize = 0; /* FIXME */
1117 info->ShortNameLength = short_len * sizeof(WCHAR);
1118 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
1119 info->FileNameLength = long_len * sizeof(WCHAR);
1120 memcpy( info->FileName, long_nameW,
1121 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
1123 *pos += total_len;
1124 return info;
1128 #ifdef VFAT_IOCTL_READDIR_BOTH
1130 /***********************************************************************
1131 * start_vfat_ioctl
1133 * Wrapper for the VFAT ioctl to work around various kernel bugs.
1134 * dir_section must be held by caller.
1136 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
1138 static KERNEL_DIRENT *de;
1139 int res;
1141 if (!de)
1143 const size_t page_size = getpagesize();
1144 SIZE_T size = 2 * sizeof(*de) + page_size;
1145 void *addr = NULL;
1147 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
1148 return NULL;
1149 /* commit only the size needed for the dir entries */
1150 /* this leaves an extra unaccessible page, which should make the kernel */
1151 /* fail with -EFAULT before it stomps all over our memory */
1152 de = addr;
1153 size = 2 * sizeof(*de);
1154 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
1157 /* set d_reclen to 65535 to work around an AFS kernel bug */
1158 de[0].d_reclen = 65535;
1159 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
1160 if (res == -1)
1162 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
1163 de[0].d_reclen = 0; /* eof */
1165 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
1167 return de;
1171 /***********************************************************************
1172 * read_directory_vfat
1174 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
1176 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1177 BOOLEAN single_entry, const UNICODE_STRING *mask,
1178 BOOLEAN restart_scan )
1181 size_t len;
1182 KERNEL_DIRENT *de;
1183 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1185 io->u.Status = STATUS_SUCCESS;
1187 if (restart_scan) lseek( fd, 0, SEEK_SET );
1189 if (length < max_dir_info_size) /* we may have to return a partial entry here */
1191 off_t old_pos = lseek( fd, 0, SEEK_CUR );
1193 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1195 while (de[0].d_reclen)
1197 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1198 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1199 de[0].d_name[len] = 0;
1200 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1201 de[1].d_name[len] = 0;
1203 if (de[1].d_name[0])
1204 info = append_entry( buffer, &io->Information, length,
1205 de[1].d_name, de[0].d_name, mask );
1206 else
1207 info = append_entry( buffer, &io->Information, length,
1208 de[0].d_name, NULL, mask );
1209 if (info)
1211 last_info = info;
1212 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1214 io->u.Status = STATUS_BUFFER_OVERFLOW;
1215 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1217 break;
1219 old_pos = lseek( fd, 0, SEEK_CUR );
1220 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1223 else /* we'll only return full entries, no need to worry about overflow */
1225 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1227 while (de[0].d_reclen)
1229 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1230 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1231 de[0].d_name[len] = 0;
1232 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1233 de[1].d_name[len] = 0;
1235 if (de[1].d_name[0])
1236 info = append_entry( buffer, &io->Information, length,
1237 de[1].d_name, de[0].d_name, mask );
1238 else
1239 info = append_entry( buffer, &io->Information, length,
1240 de[0].d_name, NULL, mask );
1241 if (info)
1243 last_info = info;
1244 if (single_entry) break;
1245 /* check if we still have enough space for the largest possible entry */
1246 if (io->Information + max_dir_info_size > length) break;
1248 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1252 if (last_info) last_info->NextEntryOffset = 0;
1253 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1254 return 0;
1256 #endif /* VFAT_IOCTL_READDIR_BOTH */
1259 /***********************************************************************
1260 * read_directory_getdents
1262 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1264 #ifdef USE_GETDENTS
1265 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1266 BOOLEAN single_entry, const UNICODE_STRING *mask,
1267 BOOLEAN restart_scan )
1269 off_t old_pos = 0;
1270 size_t size = length;
1271 int res, fake_dot_dot = 1;
1272 char *data, local_buffer[8192];
1273 KERNEL_DIRENT64 *de;
1274 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1276 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1278 size = sizeof(local_buffer);
1279 data = local_buffer;
1282 if (restart_scan) lseek( fd, 0, SEEK_SET );
1283 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
1285 old_pos = lseek( fd, 0, SEEK_CUR );
1286 if (old_pos == -1 && errno == ENOENT)
1288 io->u.Status = STATUS_NO_MORE_FILES;
1289 res = 0;
1290 goto done;
1294 io->u.Status = STATUS_SUCCESS;
1296 res = getdents64( fd, data, size );
1297 if (res == -1)
1299 if (errno != ENOSYS)
1301 io->u.Status = FILE_GetNtStatus();
1302 res = 0;
1304 goto done;
1307 de = (KERNEL_DIRENT64 *)data;
1309 if (restart_scan)
1311 /* check if we got . and .. from getdents */
1312 if (res > 0)
1314 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1316 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1317 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1320 /* make sure we have enough room for both entries */
1321 if (fake_dot_dot)
1323 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1324 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1325 if (length < min_info_size || single_entry)
1327 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1328 fake_dot_dot = 0;
1332 if (fake_dot_dot)
1334 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1335 last_info = info;
1336 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1337 last_info = info;
1339 /* check if we still have enough space for the largest possible entry */
1340 if (last_info && io->Information + max_dir_info_size > length)
1342 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1343 res = 0;
1348 while (res > 0)
1350 res -= de->d_reclen;
1351 if (!(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1352 (info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask )))
1354 last_info = info;
1355 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1357 io->u.Status = STATUS_BUFFER_OVERFLOW;
1358 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1359 break;
1361 /* check if we still have enough space for the largest possible entry */
1362 if (single_entry || io->Information + max_dir_info_size > length)
1364 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1365 break;
1368 old_pos = de->d_off;
1369 /* move on to the next entry */
1370 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1371 else
1373 res = getdents64( fd, data, size );
1374 de = (KERNEL_DIRENT64 *)data;
1378 if (last_info) last_info->NextEntryOffset = 0;
1379 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1380 res = 0;
1381 done:
1382 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1383 return res;
1386 #elif defined HAVE_GETDIRENTRIES
1388 /***********************************************************************
1389 * read_directory_getdirentries
1391 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1393 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1394 BOOLEAN single_entry, const UNICODE_STRING *mask,
1395 BOOLEAN restart_scan )
1397 long restart_pos;
1398 ULONG_PTR restart_info_pos = 0;
1399 size_t size, initial_size = length;
1400 int res, fake_dot_dot = 1;
1401 char *data, local_buffer[8192];
1402 struct dirent *de;
1403 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL, *restart_last_info = NULL;
1405 size = initial_size;
1406 data = local_buffer;
1407 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1409 io->u.Status = STATUS_NO_MEMORY;
1410 return io->u.Status;
1413 if (restart_scan) lseek( fd, 0, SEEK_SET );
1415 io->u.Status = STATUS_SUCCESS;
1417 /* FIXME: should make sure size is larger than filesystem block size */
1418 res = getdirentries( fd, data, size, &restart_pos );
1419 if (res == -1)
1421 io->u.Status = FILE_GetNtStatus();
1422 res = 0;
1423 goto done;
1426 de = (struct dirent *)data;
1428 if (restart_scan)
1430 /* check if we got . and .. from getdirentries */
1431 if (res > 0)
1433 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1435 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1436 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1439 /* make sure we have enough room for both entries */
1440 if (fake_dot_dot)
1442 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1443 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1444 if (length < min_info_size || single_entry)
1446 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1447 fake_dot_dot = 0;
1451 if (fake_dot_dot)
1453 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1454 last_info = info;
1455 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1456 last_info = info;
1458 restart_last_info = last_info;
1459 restart_info_pos = io->Information;
1461 /* check if we still have enough space for the largest possible entry */
1462 if (last_info && io->Information + max_dir_info_size > length)
1464 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1465 res = 0;
1470 while (res > 0)
1472 res -= de->d_reclen;
1473 if (de->d_fileno &&
1474 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1475 ((info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask ))))
1477 last_info = info;
1478 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1480 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1481 if (restart_info_pos) /* if we have a complete read already, return it */
1483 io->Information = restart_info_pos;
1484 last_info = restart_last_info;
1485 break;
1487 /* otherwise restart from the start with a smaller size */
1488 size = (char *)de - data;
1489 if (!size)
1491 io->u.Status = STATUS_BUFFER_OVERFLOW;
1492 break;
1494 io->Information = 0;
1495 last_info = NULL;
1496 goto restart;
1498 /* if we have to return but the buffer contains more data, restart with a smaller size */
1499 if (res > 0 && (single_entry || io->Information + max_dir_info_size > length))
1501 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1502 size = (char *)de - data;
1503 io->Information = restart_info_pos;
1504 last_info = restart_last_info;
1505 goto restart;
1508 /* move on to the next entry */
1509 if (res > 0)
1511 de = (struct dirent *)((char *)de + de->d_reclen);
1512 continue;
1514 if (size < initial_size) break; /* already restarted once, give up now */
1515 size = min( size, length - io->Information );
1516 /* if size is too small don't bother to continue */
1517 if (size < max_dir_info_size && last_info) break;
1518 restart_last_info = last_info;
1519 restart_info_pos = io->Information;
1520 restart:
1521 res = getdirentries( fd, data, size, &restart_pos );
1522 de = (struct dirent *)data;
1525 if (last_info) last_info->NextEntryOffset = 0;
1526 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1527 res = 0;
1528 done:
1529 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1530 return res;
1532 #endif /* HAVE_GETDIRENTRIES */
1535 /***********************************************************************
1536 * read_directory_readdir
1538 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1540 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1541 BOOLEAN single_entry, const UNICODE_STRING *mask,
1542 BOOLEAN restart_scan )
1544 DIR *dir;
1545 off_t i, old_pos = 0;
1546 struct dirent *de;
1547 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1549 if (!(dir = opendir( "." )))
1551 io->u.Status = FILE_GetNtStatus();
1552 return;
1555 if (!restart_scan)
1557 old_pos = lseek( fd, 0, SEEK_CUR );
1558 /* skip the right number of entries */
1559 for (i = 0; i < old_pos - 2; i++)
1561 if (!readdir( dir ))
1563 closedir( dir );
1564 io->u.Status = STATUS_NO_MORE_FILES;
1565 return;
1569 io->u.Status = STATUS_SUCCESS;
1571 for (;;)
1573 if (old_pos == 0)
1574 info = append_entry( buffer, &io->Information, length, ".", NULL, mask );
1575 else if (old_pos == 1)
1576 info = append_entry( buffer, &io->Information, length, "..", NULL, mask );
1577 else if ((de = readdir( dir )))
1579 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1580 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1581 else
1582 info = NULL;
1584 else
1585 break;
1586 old_pos++;
1587 if (info)
1589 last_info = info;
1590 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1592 io->u.Status = STATUS_BUFFER_OVERFLOW;
1593 old_pos--; /* restore pos to previous entry */
1594 break;
1596 if (single_entry) break;
1597 /* check if we still have enough space for the largest possible entry */
1598 if (io->Information + max_dir_info_size > length) break;
1602 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1603 closedir( dir );
1605 if (last_info) last_info->NextEntryOffset = 0;
1606 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1609 /***********************************************************************
1610 * read_directory_stat
1612 * Read a single file from a directory by determining whether the file
1613 * identified by mask exists using stat.
1615 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1616 BOOLEAN single_entry, const UNICODE_STRING *mask,
1617 BOOLEAN restart_scan )
1619 int unix_len, ret, used_default;
1620 char *unix_name;
1621 struct stat st;
1623 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1625 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1626 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1628 io->u.Status = STATUS_NO_MEMORY;
1629 return 0;
1631 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1632 NULL, &used_default );
1633 if (ret > 0 && !used_default)
1635 unix_name[ret] = 0;
1636 if (restart_scan)
1638 lseek( fd, 0, SEEK_SET );
1640 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1642 io->u.Status = STATUS_NO_MORE_FILES;
1643 ret = 0;
1644 goto done;
1647 ret = stat( unix_name, &st );
1648 if (!ret)
1650 FILE_BOTH_DIR_INFORMATION *info = append_entry( buffer, &io->Information, length, unix_name, NULL, mask );
1651 if (info)
1653 info->NextEntryOffset = 0;
1654 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1655 io->u.Status = STATUS_BUFFER_OVERFLOW;
1656 else
1657 lseek( fd, 1, SEEK_CUR );
1661 else ret = -1;
1663 done:
1664 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1666 TRACE("returning %d\n", ret);
1668 return ret;
1672 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1674 const WCHAR *end;
1675 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1676 return NULL;
1679 /******************************************************************************
1680 * NtQueryDirectoryFile [NTDLL.@]
1681 * ZwQueryDirectoryFile [NTDLL.@]
1683 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1684 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1685 PIO_STATUS_BLOCK io,
1686 PVOID buffer, ULONG length,
1687 FILE_INFORMATION_CLASS info_class,
1688 BOOLEAN single_entry,
1689 PUNICODE_STRING mask,
1690 BOOLEAN restart_scan )
1692 int cwd, fd, needs_close;
1693 static const WCHAR wszWildcards[] = { '*','?',0 };
1695 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1696 handle, event, apc_routine, apc_context, io, buffer,
1697 length, info_class, single_entry, debugstr_us(mask),
1698 restart_scan);
1700 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1702 if (event || apc_routine)
1704 FIXME( "Unsupported yet option\n" );
1705 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1707 if (info_class != FileBothDirectoryInformation)
1709 FIXME( "Unsupported file info class %d\n", info_class );
1710 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1713 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1714 return io->u.Status;
1716 io->Information = 0;
1718 RtlEnterCriticalSection( &dir_section );
1720 if (show_dot_files == -1) init_options();
1722 cwd = open( ".", O_RDONLY );
1723 if (fchdir( fd ) != -1)
1725 #ifdef VFAT_IOCTL_READDIR_BOTH
1726 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1727 goto done;
1728 #endif
1729 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1730 read_directory_stat( fd, io, buffer, length, single_entry, mask, restart_scan ) != -1)
1731 goto done;
1732 #ifdef USE_GETDENTS
1733 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1734 goto done;
1735 #elif defined HAVE_GETDIRENTRIES
1736 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1737 goto done;
1738 #endif
1739 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1741 done:
1742 if (cwd == -1 || fchdir( cwd ) == -1) chdir( "/" );
1744 else io->u.Status = FILE_GetNtStatus();
1746 RtlLeaveCriticalSection( &dir_section );
1748 if (needs_close) close( fd );
1749 if (cwd != -1) close( cwd );
1750 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1751 return io->u.Status;
1755 /***********************************************************************
1756 * find_file_in_dir
1758 * Find a file in a directory the hard way, by doing a case-insensitive search.
1759 * The file found is appended to unix_name at pos.
1760 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1762 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1763 int check_case )
1765 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1766 UNICODE_STRING str;
1767 BOOLEAN spaces;
1768 DIR *dir;
1769 struct dirent *de;
1770 struct stat st;
1771 int ret, used_default, is_name_8_dot_3;
1773 /* try a shortcut for this directory */
1775 unix_name[pos++] = '/';
1776 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1777 NULL, &used_default );
1778 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1779 /* so it cannot match the file we are looking for */
1780 if (ret >= 0 && !used_default)
1782 unix_name[pos + ret] = 0;
1783 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1785 if (check_case) goto not_found; /* we want an exact match */
1787 if (pos > 1) unix_name[pos - 1] = 0;
1788 else unix_name[1] = 0; /* keep the initial slash */
1790 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1792 str.Buffer = (WCHAR *)name;
1793 str.Length = length * sizeof(WCHAR);
1794 str.MaximumLength = str.Length;
1795 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1797 /* now look for it through the directory */
1799 #ifdef VFAT_IOCTL_READDIR_BOTH
1800 if (is_name_8_dot_3)
1802 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1803 if (fd != -1)
1805 KERNEL_DIRENT *de;
1807 RtlEnterCriticalSection( &dir_section );
1808 if ((de = start_vfat_ioctl( fd )))
1810 unix_name[pos - 1] = '/';
1811 while (de[0].d_reclen)
1813 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1814 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1815 de[0].d_name[len] = 0;
1816 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1817 de[1].d_name[len] = 0;
1819 if (de[1].d_name[0])
1821 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1822 buffer, MAX_DIR_ENTRY_LEN );
1823 if (ret == length && !memicmpW( buffer, name, length))
1825 strcpy( unix_name + pos, de[1].d_name );
1826 RtlLeaveCriticalSection( &dir_section );
1827 close( fd );
1828 return STATUS_SUCCESS;
1831 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1832 buffer, MAX_DIR_ENTRY_LEN );
1833 if (ret == length && !memicmpW( buffer, name, length))
1835 strcpy( unix_name + pos,
1836 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1837 RtlLeaveCriticalSection( &dir_section );
1838 close( fd );
1839 return STATUS_SUCCESS;
1841 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1843 RtlLeaveCriticalSection( &dir_section );
1844 close( fd );
1845 goto not_found;
1849 RtlLeaveCriticalSection( &dir_section );
1850 close( fd );
1852 /* fall through to normal handling */
1854 #endif /* VFAT_IOCTL_READDIR_BOTH */
1856 if (!(dir = opendir( unix_name )))
1858 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1859 else return FILE_GetNtStatus();
1861 unix_name[pos - 1] = '/';
1862 str.Buffer = buffer;
1863 str.MaximumLength = sizeof(buffer);
1864 while ((de = readdir( dir )))
1866 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1867 if (ret == length && !memicmpW( buffer, name, length ))
1869 strcpy( unix_name + pos, de->d_name );
1870 closedir( dir );
1871 return STATUS_SUCCESS;
1874 if (!is_name_8_dot_3) continue;
1876 str.Length = ret * sizeof(WCHAR);
1877 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1879 WCHAR short_nameW[12];
1880 ret = hash_short_file_name( &str, short_nameW );
1881 if (ret == length && !memicmpW( short_nameW, name, length ))
1883 strcpy( unix_name + pos, de->d_name );
1884 closedir( dir );
1885 return STATUS_SUCCESS;
1889 closedir( dir );
1890 goto not_found; /* avoid warning */
1892 not_found:
1893 unix_name[pos - 1] = 0;
1894 return STATUS_OBJECT_PATH_NOT_FOUND;
1898 /******************************************************************************
1899 * get_dos_device
1901 * Get the Unix path of a DOS device.
1903 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1905 const char *config_dir = wine_get_config_dir();
1906 struct stat st;
1907 char *unix_name, *new_name, *dev;
1908 unsigned int i;
1909 int unix_len;
1911 /* make sure the device name is ASCII */
1912 for (i = 0; i < name_len; i++)
1913 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1915 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1917 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1918 return STATUS_NO_MEMORY;
1920 strcpy( unix_name, config_dir );
1921 strcat( unix_name, "/dosdevices/" );
1922 dev = unix_name + strlen(unix_name);
1924 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1925 dev[i] = 0;
1927 /* special case for drive devices */
1928 if (name_len == 2 && dev[1] == ':')
1930 dev[i++] = ':';
1931 dev[i] = 0;
1934 for (;;)
1936 if (!stat( unix_name, &st ))
1938 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1939 unix_name_ret->Buffer = unix_name;
1940 unix_name_ret->Length = strlen(unix_name);
1941 unix_name_ret->MaximumLength = unix_len;
1942 return STATUS_SUCCESS;
1944 if (!dev) break;
1946 /* now try some defaults for it */
1947 if (!strcmp( dev, "aux" ))
1949 strcpy( dev, "com1" );
1950 continue;
1952 if (!strcmp( dev, "prn" ))
1954 strcpy( dev, "lpt1" );
1955 continue;
1957 if (!strcmp( dev, "nul" ))
1959 strcpy( unix_name, "/dev/null" );
1960 dev = NULL; /* last try */
1961 continue;
1964 new_name = NULL;
1965 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1967 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1968 new_name = get_default_drive_device( unix_name );
1970 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1971 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1973 if (!new_name) break;
1975 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1976 unix_name = new_name;
1977 unix_len = strlen(unix_name) + 1;
1978 dev = NULL; /* last try */
1980 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1981 return STATUS_BAD_DEVICE_TYPE;
1985 /* return the length of the DOS namespace prefix if any */
1986 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1988 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1989 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1991 if (name->Length > sizeof(nt_prefixW) &&
1992 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1993 return sizeof(nt_prefixW) / sizeof(WCHAR);
1995 if (name->Length > sizeof(dosdev_prefixW) &&
1996 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1997 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1999 return 0;
2003 /******************************************************************************
2004 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
2006 * Convert a file name from NT namespace to Unix namespace.
2008 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
2009 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
2010 * returned, but the unix name is still filled in properly.
2012 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
2013 UINT disposition, BOOLEAN check_case )
2015 static const WCHAR unixW[] = {'u','n','i','x'};
2016 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
2018 NTSTATUS status = STATUS_SUCCESS;
2019 const char *config_dir = wine_get_config_dir();
2020 const WCHAR *name, *p;
2021 struct stat st;
2022 char *unix_name;
2023 int pos, ret, name_len, unix_len, prefix_len, used_default;
2024 WCHAR prefix[MAX_DIR_ENTRY_LEN];
2025 BOOLEAN is_unix = FALSE;
2027 name = nameW->Buffer;
2028 name_len = nameW->Length / sizeof(WCHAR);
2030 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
2032 if (!(pos = get_dos_prefix_len( nameW )))
2033 return STATUS_BAD_DEVICE_TYPE; /* no DOS prefix, assume NT native name */
2035 name += pos;
2036 name_len -= pos;
2038 /* check for sub-directory */
2039 for (pos = 0; pos < name_len; pos++)
2041 if (IS_SEPARATOR(name[pos])) break;
2042 if (name[pos] < 32 || strchrW( invalid_charsW, name[pos] ))
2043 return STATUS_OBJECT_NAME_INVALID;
2045 if (pos > MAX_DIR_ENTRY_LEN)
2046 return STATUS_OBJECT_NAME_INVALID;
2048 if (pos == name_len) /* no subdir, plain DOS device */
2049 return get_dos_device( name, name_len, unix_name_ret );
2051 for (prefix_len = 0; prefix_len < pos; prefix_len++)
2052 prefix[prefix_len] = tolowerW(name[prefix_len]);
2054 name += prefix_len;
2055 name_len -= prefix_len;
2057 /* check for invalid characters (all chars except 0 are valid for unix) */
2058 is_unix = (prefix_len == 4 && !memcmp( prefix, unixW, sizeof(unixW) ));
2059 if (is_unix)
2061 for (p = name; p < name + name_len; p++)
2062 if (!*p) return STATUS_OBJECT_NAME_INVALID;
2063 check_case = TRUE;
2065 else
2067 for (p = name; p < name + name_len; p++)
2068 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
2071 unix_len = ntdll_wcstoumbs( 0, prefix, prefix_len, NULL, 0, NULL, NULL );
2072 unix_len += ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
2073 unix_len += MAX_DIR_ENTRY_LEN + 3;
2074 unix_len += strlen(config_dir) + sizeof("/dosdevices/");
2075 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
2076 return STATUS_NO_MEMORY;
2077 strcpy( unix_name, config_dir );
2078 strcat( unix_name, "/dosdevices/" );
2079 pos = strlen(unix_name);
2081 ret = ntdll_wcstoumbs( 0, prefix, prefix_len, unix_name + pos, unix_len - pos - 1,
2082 NULL, &used_default );
2083 if (!ret || used_default)
2085 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2086 return STATUS_OBJECT_NAME_INVALID;
2088 pos += ret;
2090 /* check if prefix exists (except for DOS drives to avoid extra stat calls) */
2092 if (prefix_len != 2 || prefix[1] != ':')
2094 unix_name[pos] = 0;
2095 if (lstat( unix_name, &st ) == -1 && errno == ENOENT)
2097 if (!is_unix)
2099 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2100 return STATUS_BAD_DEVICE_TYPE;
2102 pos = 0; /* fall back to unix root */
2106 /* try a shortcut first */
2108 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
2109 NULL, &used_default );
2111 while (name_len && IS_SEPARATOR(*name))
2113 name++;
2114 name_len--;
2117 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
2119 char *p;
2120 unix_name[pos + ret] = 0;
2121 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
2122 if (!stat( unix_name, &st ))
2124 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
2125 if (disposition == FILE_CREATE)
2127 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2128 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
2130 goto done;
2134 if (!name_len) /* empty name -> drive root doesn't exist */
2136 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2137 return STATUS_OBJECT_PATH_NOT_FOUND;
2139 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
2141 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2142 return STATUS_OBJECT_NAME_NOT_FOUND;
2145 /* now do it component by component */
2147 while (name_len)
2149 const WCHAR *end, *next;
2151 end = name;
2152 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
2153 next = end;
2154 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
2155 name_len -= next - name;
2157 /* grow the buffer if needed */
2159 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
2161 char *new_name;
2162 unix_len += 2 * MAX_DIR_ENTRY_LEN;
2163 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
2165 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2166 return STATUS_NO_MEMORY;
2168 unix_name = new_name;
2171 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
2173 /* if this is the last element, not finding it is not necessarily fatal */
2174 if (!name_len)
2176 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
2178 status = STATUS_OBJECT_NAME_NOT_FOUND;
2179 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
2181 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
2182 MAX_DIR_ENTRY_LEN, NULL, &used_default );
2183 if (ret > 0 && !used_default)
2185 unix_name[pos] = '/';
2186 unix_name[pos + 1 + ret] = 0;
2187 status = STATUS_NO_SUCH_FILE;
2188 break;
2192 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
2194 status = STATUS_OBJECT_NAME_COLLISION;
2198 if (status != STATUS_SUCCESS)
2200 /* couldn't find it at all, fail */
2201 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
2202 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
2203 return status;
2206 pos += strlen( unix_name + pos );
2207 name = next;
2210 WARN( "%s -> %s required a case-insensitive search\n",
2211 debugstr_us(nameW), debugstr_a(unix_name) );
2213 done:
2214 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
2215 unix_name_ret->Buffer = unix_name;
2216 unix_name_ret->Length = strlen(unix_name);
2217 unix_name_ret->MaximumLength = unix_len;
2218 return status;
2222 /******************************************************************
2223 * RtlDoesFileExists_U (NTDLL.@)
2225 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2227 UNICODE_STRING nt_name;
2228 ANSI_STRING unix_name;
2229 BOOLEAN ret;
2231 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2232 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
2233 if (ret) RtlFreeAnsiString( &unix_name );
2234 RtlFreeUnicodeString( &nt_name );
2235 return ret;
2239 /***********************************************************************
2240 * DIR_unmount_device
2242 * Unmount the specified device.
2244 NTSTATUS DIR_unmount_device( HANDLE handle )
2246 NTSTATUS status;
2247 int unix_fd, needs_close;
2249 SERVER_START_REQ( unmount_device )
2251 req->handle = handle;
2252 status = wine_server_call( req );
2254 SERVER_END_REQ;
2255 if (status) return status;
2257 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2259 struct stat st;
2260 char *mount_point = NULL;
2262 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2263 status = STATUS_INVALID_PARAMETER;
2264 else
2266 if ((mount_point = get_device_mount_point( st.st_rdev )))
2268 #ifdef __APPLE__
2269 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2270 #else
2271 static const char umount[] = "umount >/dev/null 2>&1 ";
2272 #endif
2273 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2274 if (cmd)
2276 strcpy( cmd, umount );
2277 strcat( cmd, mount_point );
2278 system( cmd );
2279 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2280 #ifdef linux
2281 /* umount will fail to release the loop device since we still have
2282 a handle to it, so we release it here */
2283 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2284 #endif
2286 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2289 if (needs_close) close( unix_fd );
2291 return status;
2295 /******************************************************************************
2296 * DIR_get_unix_cwd
2298 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2299 * Returned value must be freed by caller.
2301 NTSTATUS DIR_get_unix_cwd( char **cwd )
2303 int old_cwd, unix_fd, needs_close;
2304 CURDIR *curdir;
2305 HANDLE handle;
2306 NTSTATUS status;
2308 RtlAcquirePebLock();
2310 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2311 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2312 else
2313 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2315 if (!(handle = curdir->Handle))
2317 UNICODE_STRING dirW;
2318 OBJECT_ATTRIBUTES attr;
2319 IO_STATUS_BLOCK io;
2321 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2323 status = STATUS_OBJECT_NAME_INVALID;
2324 goto done;
2326 attr.Length = sizeof(attr);
2327 attr.RootDirectory = 0;
2328 attr.Attributes = OBJ_CASE_INSENSITIVE;
2329 attr.ObjectName = &dirW;
2330 attr.SecurityDescriptor = NULL;
2331 attr.SecurityQualityOfService = NULL;
2333 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2334 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2335 RtlFreeUnicodeString( &dirW );
2336 if (status != STATUS_SUCCESS) goto done;
2339 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2341 RtlEnterCriticalSection( &dir_section );
2343 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2345 unsigned int size = 512;
2347 for (;;)
2349 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2351 status = STATUS_NO_MEMORY;
2352 break;
2354 if (getcwd( *cwd, size )) break;
2355 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2356 if (errno != ERANGE)
2358 status = STATUS_OBJECT_PATH_INVALID;
2359 break;
2361 size *= 2;
2363 if (fchdir( old_cwd ) == -1) chdir( "/" );
2365 else status = FILE_GetNtStatus();
2367 RtlLeaveCriticalSection( &dir_section );
2368 if (needs_close) close( unix_fd );
2370 if (!curdir->Handle) NtClose( handle );
2372 done:
2373 RtlReleasePebLock();
2374 return status;
2377 struct read_changes_info
2379 HANDLE FileHandle;
2380 PVOID Buffer;
2381 ULONG BufferSize;
2384 static void WINAPI read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, ULONG status )
2386 struct read_changes_info *info = user;
2387 char path[PATH_MAX];
2388 NTSTATUS ret = STATUS_SUCCESS;
2389 int len, action, i;
2391 TRACE("%p %p %08x\n", info, iosb, status);
2394 * FIXME: race me!
2396 * hEvent/hDir is set before the output buffer and iosb is updated.
2397 * Since the thread that called NtNotifyChangeDirectoryFile is usually
2398 * waiting, we'll be safe since we're called in that thread's context.
2399 * If a different thread is waiting on our hEvent/hDir we're going to be
2400 * in trouble...
2402 SERVER_START_REQ( read_change )
2404 req->handle = info->FileHandle;
2405 wine_server_set_reply( req, path, PATH_MAX );
2406 ret = wine_server_call( req );
2407 action = reply->action;
2408 len = wine_server_reply_size( reply );
2410 SERVER_END_REQ;
2412 if (ret == STATUS_SUCCESS && info->Buffer &&
2413 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2415 PFILE_NOTIFY_INFORMATION pfni;
2417 pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
2419 /* convert to an NT style path */
2420 for (i=0; i<len; i++)
2421 if (path[i] == '/')
2422 path[i] = '\\';
2424 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2425 info->BufferSize - sizeof (*pfni) );
2427 pfni->NextEntryOffset = 0;
2428 pfni->Action = action;
2429 pfni->FileNameLength = len * sizeof (WCHAR);
2430 pfni->FileName[len] = 0;
2432 TRACE("action = %d name = %s\n", pfni->Action,
2433 debugstr_w(pfni->FileName) );
2434 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2436 else
2438 ret = STATUS_NOTIFY_ENUM_DIR;
2439 len = 0;
2442 iosb->u.Status = ret;
2443 iosb->Information = len;
2445 RtlFreeHeap( GetProcessHeap(), 0, info );
2448 #define FILE_NOTIFY_ALL ( \
2449 FILE_NOTIFY_CHANGE_FILE_NAME | \
2450 FILE_NOTIFY_CHANGE_DIR_NAME | \
2451 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2452 FILE_NOTIFY_CHANGE_SIZE | \
2453 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2454 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2455 FILE_NOTIFY_CHANGE_CREATION | \
2456 FILE_NOTIFY_CHANGE_SECURITY )
2458 /******************************************************************************
2459 * NtNotifyChangeDirectoryFile [NTDLL.@]
2461 NTSTATUS WINAPI
2462 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2463 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2464 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2465 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2467 struct read_changes_info *info;
2468 NTSTATUS status;
2470 TRACE("%p %p %p %p %p %p %u %u %d\n",
2471 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2472 Buffer, BufferSize, CompletionFilter, WatchTree );
2474 if (!IoStatusBlock)
2475 return STATUS_ACCESS_VIOLATION;
2477 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2478 return STATUS_INVALID_PARAMETER;
2480 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2481 if (!info)
2482 return STATUS_NO_MEMORY;
2484 info->FileHandle = FileHandle;
2485 info->Buffer = Buffer;
2486 info->BufferSize = BufferSize;
2488 SERVER_START_REQ( read_directory_changes )
2490 req->handle = FileHandle;
2491 req->filter = CompletionFilter;
2492 req->want_data = (Buffer != NULL);
2493 req->subtree = WatchTree;
2494 req->async.callback = read_changes_apc;
2495 req->async.iosb = IoStatusBlock;
2496 req->async.arg = info;
2497 req->async.apc = ApcRoutine;
2498 req->async.apc_arg = ApcContext;
2499 req->async.event = Event;
2500 status = wine_server_call( req );
2502 SERVER_END_REQ;
2504 if (status != STATUS_PENDING)
2505 RtlFreeHeap( GetProcessHeap(), 0, info );
2507 return status;