widl: Convert expression lists to standard Wine lists.
[wine/hacks.git] / dlls / ntdll / directory.c
blobc0933bcb406343f0e2331f9a039b82bffff1ade3
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)
240 struct vfstab vfs_entry;
241 struct vfstab *entry=&vfs_entry;
242 struct stat st;
243 char *device;
245 while (! getvfsent( f, entry ))
247 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
248 if (!strcmp( entry->vfs_fstype, "nfs" ) ||
249 !strcmp( entry->vfs_fstype, "smbfs" ) ||
250 !strcmp( entry->vfs_fstype, "ncpfs" )) continue;
252 if (stat( entry->vfs_mountp, &st ) == -1) continue;
253 if (st.st_dev != dev || st.st_ino != ino) continue;
254 if (!strcmp( entry->vfs_fstype, "fd" ))
256 if ((device = strstr( entry->vfs_mntopts, "dev=" )))
258 char *p = strchr( device + 4, ',' );
259 if (p) *p = 0;
260 return device + 4;
263 else
264 return entry->vfs_special;
266 return NULL;
268 #endif
270 #ifdef linux
271 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
273 struct mntent *entry;
274 struct stat st;
275 char *device;
277 while ((entry = getmntent( f )))
279 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
280 if (!strcmp( entry->mnt_type, "nfs" ) ||
281 !strcmp( entry->mnt_type, "smbfs" ) ||
282 !strcmp( entry->mnt_type, "ncpfs" )) continue;
284 if (stat( entry->mnt_dir, &st ) == -1) continue;
285 if (st.st_dev != dev || st.st_ino != ino) continue;
286 if (!strcmp( entry->mnt_type, "supermount" ))
288 if ((device = strstr( entry->mnt_opts, "dev=" )))
290 char *p = strchr( device + 4, ',' );
291 if (p) *p = 0;
292 return device + 4;
295 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
297 /* if device is a regular file check for a loop mount */
298 if ((device = strstr( entry->mnt_opts, "loop=" )))
300 char *p = strchr( device + 5, ',' );
301 if (p) *p = 0;
302 return device + 5;
305 else
306 return entry->mnt_fsname;
308 return NULL;
310 #endif
312 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
313 #include <fstab.h>
314 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
316 struct fstab *entry;
317 struct stat st;
319 while ((entry = getfsent()))
321 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
322 if (!strcmp( entry->fs_vfstype, "nfs" ) ||
323 !strcmp( entry->fs_vfstype, "smbfs" ) ||
324 !strcmp( entry->fs_vfstype, "ncpfs" )) continue;
326 if (stat( entry->fs_file, &st ) == -1) continue;
327 if (st.st_dev != dev || st.st_ino != ino) continue;
328 return entry->fs_spec;
330 return NULL;
332 #endif
334 #ifdef sun
335 #include <sys/mnttab.h>
336 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
339 volatile struct mnttab mntentry;
340 struct mnttab *entry=&mntentry;
341 struct stat st;
342 char *device;
345 while (( ! getmntent( f , entry) ))
347 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
348 if (!strcmp( entry->mnt_fstype, "nfs" ) ||
349 !strcmp( entry->mnt_fstype, "smbfs" ) ||
350 !strcmp( entry->mnt_fstype, "ncpfs" )) continue;
352 if (stat( entry->mnt_mountp, &st ) == -1) continue;
353 if (st.st_dev != dev || st.st_ino != ino) continue;
354 if (!strcmp( entry->mnt_fstype, "fd" ))
356 if ((device = strstr( entry->mnt_mntopts, "dev=" )))
358 char *p = strchr( device + 4, ',' );
359 if (p) *p = 0;
360 return device + 4;
363 else
364 return entry->mnt_special;
366 return NULL;
368 #endif
370 /***********************************************************************
371 * get_default_drive_device
373 * Return the default device to use for a given drive mount point.
375 static char *get_default_drive_device( const char *root )
377 char *ret = NULL;
379 #ifdef linux
380 FILE *f;
381 char *device = NULL;
382 int fd, res = -1;
383 struct stat st;
385 /* try to open it first to force it to get mounted */
386 if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
388 res = fstat( fd, &st );
389 close( fd );
391 /* now try normal stat just in case */
392 if (res == -1) res = stat( root, &st );
393 if (res == -1) return NULL;
395 RtlEnterCriticalSection( &dir_section );
397 if ((f = fopen( "/etc/mtab", "r" )))
399 device = parse_mount_entries( f, st.st_dev, st.st_ino );
400 endmntent( f );
402 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
403 if (!device && (f = fopen( "/etc/fstab", "r" )))
405 device = parse_mount_entries( f, st.st_dev, st.st_ino );
406 endmntent( f );
408 if (device)
410 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
411 if (ret) strcpy( ret, device );
413 RtlLeaveCriticalSection( &dir_section );
415 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__ )
416 char *device = NULL;
417 int fd, res = -1;
418 struct stat st;
420 /* try to open it first to force it to get mounted */
421 if ((fd = open( root, O_RDONLY )) != -1)
423 res = fstat( fd, &st );
424 close( fd );
426 /* now try normal stat just in case */
427 if (res == -1) res = stat( root, &st );
428 if (res == -1) return NULL;
430 RtlEnterCriticalSection( &dir_section );
432 /* The FreeBSD parse_mount_entries doesn't require a file argument, so just
433 * pass NULL. Leave the argument in for symmetry.
435 device = parse_mount_entries( NULL, st.st_dev, st.st_ino );
436 if (device)
438 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
439 if (ret) strcpy( ret, device );
441 RtlLeaveCriticalSection( &dir_section );
443 #elif defined( sun )
444 FILE *f;
445 char *device = NULL;
446 int fd, res = -1;
447 struct stat st;
449 /* try to open it first to force it to get mounted */
450 if ((fd = open( root, O_RDONLY )) != -1)
452 res = fstat( fd, &st );
453 close( fd );
455 /* now try normal stat just in case */
456 if (res == -1) res = stat( root, &st );
457 if (res == -1) return NULL;
459 RtlEnterCriticalSection( &dir_section );
461 if ((f = fopen( "/etc/mnttab", "r" )))
463 device = parse_mount_entries( f, st.st_dev, st.st_ino);
464 fclose( f );
466 /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
467 if (!device && (f = fopen( "/etc/vfstab", "r" )))
469 device = parse_vfstab_entries( f, st.st_dev, st.st_ino );
470 fclose( f );
472 if (device)
474 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
475 if (ret) strcpy( ret, device );
477 RtlLeaveCriticalSection( &dir_section );
479 #elif defined(__APPLE__)
480 struct statfs *mntStat;
481 struct stat st;
482 int i;
483 int mntSize;
484 dev_t dev;
485 ino_t ino;
486 static const char path_bsd_device[] = "/dev/disk";
487 int res;
489 res = stat( root, &st );
490 if (res == -1) return NULL;
492 dev = st.st_dev;
493 ino = st.st_ino;
495 RtlEnterCriticalSection( &dir_section );
497 mntSize = getmntinfo(&mntStat, MNT_NOWAIT);
499 for (i = 0; i < mntSize && !ret; i++)
501 if (stat(mntStat[i].f_mntonname, &st ) == -1) continue;
502 if (st.st_dev != dev || st.st_ino != ino) continue;
504 /* FIXME add support for mounted network drive */
505 if ( strncmp(mntStat[i].f_mntfromname, path_bsd_device, strlen(path_bsd_device)) == 0)
507 /* set return value to the corresponding raw BSD node */
508 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mntStat[i].f_mntfromname) + 2 /* 2 : r and \0 */ );
509 if (ret)
511 strcpy(ret, "/dev/r");
512 strcat(ret, mntStat[i].f_mntfromname+sizeof("/dev/")-1);
516 RtlLeaveCriticalSection( &dir_section );
517 #else
518 static int warned;
519 if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
520 #endif
521 return ret;
525 /***********************************************************************
526 * get_device_mount_point
528 * Return the current mount point for a device.
530 static char *get_device_mount_point( dev_t dev )
532 char *ret = NULL;
534 #ifdef linux
535 FILE *f;
537 RtlEnterCriticalSection( &dir_section );
539 if ((f = fopen( "/etc/mtab", "r" )))
541 struct mntent *entry;
542 struct stat st;
543 char *p, *device;
545 while ((entry = getmntent( f )))
547 /* don't even bother stat'ing network mounts, there's no meaningful device anyway */
548 if (!strcmp( entry->mnt_type, "nfs" ) ||
549 !strcmp( entry->mnt_type, "smbfs" ) ||
550 !strcmp( entry->mnt_type, "ncpfs" )) continue;
552 if (!strcmp( entry->mnt_type, "supermount" ))
554 if ((device = strstr( entry->mnt_opts, "dev=" )))
556 device += 4;
557 if ((p = strchr( device, ',' ))) *p = 0;
560 else if (!stat( entry->mnt_fsname, &st ) && S_ISREG(st.st_mode))
562 /* if device is a regular file check for a loop mount */
563 if ((device = strstr( entry->mnt_opts, "loop=" )))
565 device += 5;
566 if ((p = strchr( device, ',' ))) *p = 0;
569 else device = entry->mnt_fsname;
571 if (device && !stat( device, &st ) && S_ISBLK(st.st_mode) && st.st_rdev == dev)
573 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry->mnt_dir) + 1 );
574 if (ret) strcpy( ret, entry->mnt_dir );
575 break;
578 endmntent( f );
580 RtlLeaveCriticalSection( &dir_section );
581 #elif defined(__APPLE__)
582 struct statfs *entry;
583 struct stat st;
584 int i, size;
586 RtlEnterCriticalSection( &dir_section );
588 size = getmntinfo( &entry, MNT_NOWAIT );
589 for (i = 0; i < size; i++)
591 if (stat( entry[i].f_mntfromname, &st ) == -1) continue;
592 if (S_ISBLK(st.st_mode) && st.st_rdev == dev)
594 ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(entry[i].f_mntfromname) + 1 );
595 if (ret) strcpy( ret, entry[i].f_mntfromname );
596 break;
599 RtlLeaveCriticalSection( &dir_section );
600 #else
601 static int warned;
602 if (!warned++) FIXME( "unmounting devices not supported on this platform\n" );
603 #endif
604 return ret;
608 /***********************************************************************
609 * init_options
611 * Initialize the show_dot_files options.
613 static void init_options(void)
615 static const WCHAR WineW[] = {'S','o','f','t','w','a','r','e','\\','W','i','n','e',0};
616 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
617 char tmp[80];
618 HANDLE root, hkey;
619 DWORD dummy;
620 OBJECT_ATTRIBUTES attr;
621 UNICODE_STRING nameW;
623 show_dot_files = 0;
625 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
626 attr.Length = sizeof(attr);
627 attr.RootDirectory = root;
628 attr.ObjectName = &nameW;
629 attr.Attributes = 0;
630 attr.SecurityDescriptor = NULL;
631 attr.SecurityQualityOfService = NULL;
632 RtlInitUnicodeString( &nameW, WineW );
634 /* @@ Wine registry key: HKCU\Software\Wine */
635 if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
637 RtlInitUnicodeString( &nameW, ShowDotFilesW );
638 if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
640 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
641 show_dot_files = IS_OPTION_TRUE( str[0] );
643 NtClose( hkey );
645 NtClose( root );
649 /***********************************************************************
650 * DIR_is_hidden_file
652 * Check if the specified file should be hidden based on its name and the show dot files option.
654 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
656 WCHAR *p, *end;
658 if (show_dot_files == -1) init_options();
659 if (show_dot_files) return FALSE;
661 end = p = name->Buffer + name->Length/sizeof(WCHAR);
662 while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
663 while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
664 if (p == end || *p != '.') return FALSE;
665 /* make sure it isn't '.' or '..' */
666 if (p + 1 == end) return FALSE;
667 if (p[1] == '.' && p + 2 == end) return FALSE;
668 return TRUE;
672 /***********************************************************************
673 * hash_short_file_name
675 * Transform a Unix file name into a hashed DOS name. If the name is a valid
676 * DOS name, it is converted to upper-case; otherwise it is replaced by a
677 * hashed version that fits in 8.3 format.
678 * 'buffer' must be at least 12 characters long.
679 * Returns length of short name in bytes; short name is NOT null-terminated.
681 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
683 static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
685 LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
686 LPWSTR dst;
687 unsigned short hash;
688 int i;
690 /* Compute the hash code of the file name */
691 /* If you know something about hash functions, feel free to */
692 /* insert a better algorithm here... */
693 if (!is_case_sensitive)
695 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
696 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
697 hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
699 else
701 for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
702 hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
703 hash = (hash << 3) ^ (hash >> 5) ^ *p; /* Last character */
706 /* Find last dot for start of the extension */
707 for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
709 /* Copy first 4 chars, replacing invalid chars with '_' */
710 for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
712 if (p == end || p == ext) break;
713 *dst++ = is_invalid_dos_char(*p) ? '_' : toupperW(*p);
715 /* Pad to 5 chars with '~' */
716 while (i-- >= 0) *dst++ = '~';
718 /* Insert hash code converted to 3 ASCII chars */
719 *dst++ = hash_chars[(hash >> 10) & 0x1f];
720 *dst++ = hash_chars[(hash >> 5) & 0x1f];
721 *dst++ = hash_chars[hash & 0x1f];
723 /* Copy the first 3 chars of the extension (if any) */
724 if (ext)
726 *dst++ = '.';
727 for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
728 *dst++ = is_invalid_dos_char(*ext) ? '_' : toupperW(*ext);
730 return dst - buffer;
734 /***********************************************************************
735 * match_filename
737 * Check a long file name against a mask.
739 * Tests (done in W95 DOS shell - case insensitive):
740 * *.txt test1.test.txt *
741 * *st1* test1.txt *
742 * *.t??????.t* test1.ta.tornado.txt *
743 * *tornado* test1.ta.tornado.txt *
744 * t*t test1.ta.tornado.txt *
745 * ?est* test1.txt *
746 * ?est??? test1.txt -
747 * *test1.txt* test1.txt *
748 * h?l?o*t.dat hellothisisatest.dat *
750 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
752 int mismatch;
753 const WCHAR *name = name_str->Buffer;
754 const WCHAR *mask = mask_str->Buffer;
755 const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
756 const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
757 const WCHAR *lastjoker = NULL;
758 const WCHAR *next_to_retry = NULL;
760 TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
762 while (name < name_end && mask < mask_end)
764 switch(*mask)
766 case '*':
767 mask++;
768 while (mask < mask_end && *mask == '*') mask++; /* Skip consecutive '*' */
769 if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
770 lastjoker = mask;
772 /* skip to the next match after the joker(s) */
773 if (is_case_sensitive)
774 while (name < name_end && (*name != *mask)) name++;
775 else
776 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
777 next_to_retry = name;
778 break;
779 case '?':
780 mask++;
781 name++;
782 break;
783 default:
784 if (is_case_sensitive) mismatch = (*mask != *name);
785 else mismatch = (toupperW(*mask) != toupperW(*name));
787 if (!mismatch)
789 mask++;
790 name++;
791 if (mask == mask_end)
793 if (name == name_end) return TRUE;
794 if (lastjoker) mask = lastjoker;
797 else /* mismatch ! */
799 if (lastjoker) /* we had an '*', so we can try unlimitedly */
801 mask = lastjoker;
803 /* this scan sequence was a mismatch, so restart
804 * 1 char after the first char we checked last time */
805 next_to_retry++;
806 name = next_to_retry;
808 else return FALSE; /* bad luck */
810 break;
813 while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
814 mask++; /* Ignore trailing '.' or '*' in mask */
815 return (name == name_end && mask == mask_end);
819 /***********************************************************************
820 * append_entry
822 * helper for NtQueryDirectoryFile
824 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG_PTR *pos, ULONG max_length,
825 const char *long_name, const char *short_name,
826 const UNICODE_STRING *mask )
828 FILE_BOTH_DIR_INFORMATION *info;
829 int i, long_len, short_len, total_len;
830 struct stat st;
831 WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
832 WCHAR short_nameW[12];
833 UNICODE_STRING str;
835 long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
836 if (long_len == -1) return NULL;
838 str.Buffer = long_nameW;
839 str.Length = long_len * sizeof(WCHAR);
840 str.MaximumLength = sizeof(long_nameW);
842 if (short_name)
844 short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
845 short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
846 if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
848 else /* generate a short name if necessary */
850 BOOLEAN spaces;
852 short_len = 0;
853 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
854 short_len = hash_short_file_name( &str, short_nameW );
857 TRACE( "long %s short %s mask %s\n",
858 debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
860 if (mask && !match_filename( &str, mask ))
862 if (!short_len) return NULL; /* no short name to match */
863 str.Buffer = short_nameW;
864 str.Length = short_len * sizeof(WCHAR);
865 str.MaximumLength = sizeof(short_nameW);
866 if (!match_filename( &str, mask )) return NULL;
869 total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
870 info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
872 if (*pos + total_len > max_length) total_len = max_length - *pos;
874 info->FileAttributes = 0;
875 if (lstat( long_name, &st ) == -1) return NULL;
876 if (S_ISLNK( st.st_mode ))
878 if (stat( long_name, &st ) == -1) return NULL;
879 if (S_ISDIR( st.st_mode )) info->FileAttributes |= FILE_ATTRIBUTE_REPARSE_POINT;
882 info->NextEntryOffset = total_len;
883 info->FileIndex = 0; /* NTFS always has 0 here, so let's not bother with it */
885 RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
886 RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
887 RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
888 RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
890 if (S_ISDIR(st.st_mode))
892 info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
893 info->FileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
895 else
897 info->EndOfFile.QuadPart = st.st_size;
898 info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
899 info->FileAttributes |= FILE_ATTRIBUTE_ARCHIVE;
902 if (!(st.st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
903 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
905 if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
906 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
908 info->EaSize = 0; /* FIXME */
909 info->ShortNameLength = short_len * sizeof(WCHAR);
910 for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
911 info->FileNameLength = long_len * sizeof(WCHAR);
912 memcpy( info->FileName, long_nameW,
913 min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
915 *pos += total_len;
916 return info;
920 #ifdef VFAT_IOCTL_READDIR_BOTH
922 /***********************************************************************
923 * start_vfat_ioctl
925 * Wrapper for the VFAT ioctl to work around various kernel bugs.
926 * dir_section must be held by caller.
928 static KERNEL_DIRENT *start_vfat_ioctl( int fd )
930 static KERNEL_DIRENT *de;
931 int res;
933 if (!de)
935 const size_t page_size = getpagesize();
936 SIZE_T size = 2 * sizeof(*de) + page_size;
937 void *addr = NULL;
939 if (NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_RESERVE, PAGE_READWRITE ))
940 return NULL;
941 /* commit only the size needed for the dir entries */
942 /* this leaves an extra unaccessible page, which should make the kernel */
943 /* fail with -EFAULT before it stomps all over our memory */
944 de = addr;
945 size = 2 * sizeof(*de);
946 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, 1, &size, MEM_COMMIT, PAGE_READWRITE );
949 /* set d_reclen to 65535 to work around an AFS kernel bug */
950 de[0].d_reclen = 65535;
951 res = ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de );
952 if (res == -1)
954 if (errno != ENOENT) return NULL; /* VFAT ioctl probably not supported */
955 de[0].d_reclen = 0; /* eof */
957 else if (!res && de[0].d_reclen == 65535) return NULL; /* AFS bug */
959 return de;
963 /***********************************************************************
964 * read_directory_vfat
966 * Read a directory using the VFAT ioctl; helper for NtQueryDirectoryFile.
968 static int read_directory_vfat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
969 BOOLEAN single_entry, const UNICODE_STRING *mask,
970 BOOLEAN restart_scan )
973 size_t len;
974 KERNEL_DIRENT *de;
975 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
977 io->u.Status = STATUS_SUCCESS;
979 if (restart_scan) lseek( fd, 0, SEEK_SET );
981 if (length < max_dir_info_size) /* we may have to return a partial entry here */
983 off_t old_pos = lseek( fd, 0, SEEK_CUR );
985 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
987 while (de[0].d_reclen)
989 /* make sure names are null-terminated to work around an x86-64 kernel bug */
990 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
991 de[0].d_name[len] = 0;
992 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
993 de[1].d_name[len] = 0;
995 if (de[1].d_name[0])
996 info = append_entry( buffer, &io->Information, length,
997 de[1].d_name, de[0].d_name, mask );
998 else
999 info = append_entry( buffer, &io->Information, length,
1000 de[0].d_name, NULL, mask );
1001 if (info)
1003 last_info = info;
1004 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1006 io->u.Status = STATUS_BUFFER_OVERFLOW;
1007 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1009 break;
1011 old_pos = lseek( fd, 0, SEEK_CUR );
1012 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1015 else /* we'll only return full entries, no need to worry about overflow */
1017 if (!(de = start_vfat_ioctl( fd ))) return -1; /* not supported */
1019 while (de[0].d_reclen)
1021 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1022 len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1023 de[0].d_name[len] = 0;
1024 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1025 de[1].d_name[len] = 0;
1027 if (de[1].d_name[0])
1028 info = append_entry( buffer, &io->Information, length,
1029 de[1].d_name, de[0].d_name, mask );
1030 else
1031 info = append_entry( buffer, &io->Information, length,
1032 de[0].d_name, NULL, mask );
1033 if (info)
1035 last_info = info;
1036 if (single_entry) break;
1037 /* check if we still have enough space for the largest possible entry */
1038 if (io->Information + max_dir_info_size > length) break;
1040 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
1044 if (last_info) last_info->NextEntryOffset = 0;
1045 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1046 return 0;
1048 #endif /* VFAT_IOCTL_READDIR_BOTH */
1051 /***********************************************************************
1052 * read_directory_getdents
1054 * Read a directory using the Linux getdents64 system call; helper for NtQueryDirectoryFile.
1056 #ifdef USE_GETDENTS
1057 static int read_directory_getdents( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1058 BOOLEAN single_entry, const UNICODE_STRING *mask,
1059 BOOLEAN restart_scan )
1061 off_t old_pos = 0;
1062 size_t size = length;
1063 int res, fake_dot_dot = 1;
1064 char *data, local_buffer[8192];
1065 KERNEL_DIRENT64 *de;
1066 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1068 if (size <= sizeof(local_buffer) || !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1070 size = sizeof(local_buffer);
1071 data = local_buffer;
1074 if (restart_scan) lseek( fd, 0, SEEK_SET );
1075 else if (length < max_dir_info_size) /* we may have to return a partial entry here */
1077 old_pos = lseek( fd, 0, SEEK_CUR );
1078 if (old_pos == -1 && errno == ENOENT)
1080 io->u.Status = STATUS_NO_MORE_FILES;
1081 res = 0;
1082 goto done;
1086 io->u.Status = STATUS_SUCCESS;
1088 res = getdents64( fd, data, size );
1089 if (res == -1)
1091 if (errno != ENOSYS)
1093 io->u.Status = FILE_GetNtStatus();
1094 res = 0;
1096 goto done;
1099 de = (KERNEL_DIRENT64 *)data;
1101 if (restart_scan)
1103 /* check if we got . and .. from getdents */
1104 if (res > 0)
1106 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1108 KERNEL_DIRENT64 *next_de = (KERNEL_DIRENT64 *)(data + de->d_reclen);
1109 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1112 /* make sure we have enough room for both entries */
1113 if (fake_dot_dot)
1115 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1116 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1117 if (length < min_info_size || single_entry)
1119 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1120 fake_dot_dot = 0;
1124 if (fake_dot_dot)
1126 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1127 last_info = info;
1128 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1129 last_info = info;
1131 /* check if we still have enough space for the largest possible entry */
1132 if (last_info && io->Information + max_dir_info_size > length)
1134 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1135 res = 0;
1140 while (res > 0)
1142 res -= de->d_reclen;
1143 if (!(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1144 (info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask )))
1146 last_info = info;
1147 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1149 io->u.Status = STATUS_BUFFER_OVERFLOW;
1150 lseek( fd, old_pos, SEEK_SET ); /* restore pos to previous entry */
1151 break;
1153 /* check if we still have enough space for the largest possible entry */
1154 if (single_entry || io->Information + max_dir_info_size > length)
1156 if (res > 0) lseek( fd, de->d_off, SEEK_SET ); /* set pos to next entry */
1157 break;
1160 old_pos = de->d_off;
1161 /* move on to the next entry */
1162 if (res > 0) de = (KERNEL_DIRENT64 *)((char *)de + de->d_reclen);
1163 else
1165 res = getdents64( fd, data, size );
1166 de = (KERNEL_DIRENT64 *)data;
1170 if (last_info) last_info->NextEntryOffset = 0;
1171 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1172 res = 0;
1173 done:
1174 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1175 return res;
1178 #elif defined HAVE_GETDIRENTRIES
1180 /***********************************************************************
1181 * read_directory_getdirentries
1183 * Read a directory using the BSD getdirentries system call; helper for NtQueryDirectoryFile.
1185 static int read_directory_getdirentries( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1186 BOOLEAN single_entry, const UNICODE_STRING *mask,
1187 BOOLEAN restart_scan )
1189 long restart_pos;
1190 ULONG_PTR restart_info_pos = 0;
1191 size_t size, initial_size = length;
1192 int res, fake_dot_dot = 1;
1193 char *data, local_buffer[8192];
1194 struct dirent *de;
1195 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL, *restart_last_info = NULL;
1197 size = initial_size;
1198 data = local_buffer;
1199 if (size > sizeof(local_buffer) && !(data = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1201 io->u.Status = STATUS_NO_MEMORY;
1202 return io->u.Status;
1205 if (restart_scan) lseek( fd, 0, SEEK_SET );
1207 io->u.Status = STATUS_SUCCESS;
1209 /* FIXME: should make sure size is larger than filesystem block size */
1210 res = getdirentries( fd, data, size, &restart_pos );
1211 if (res == -1)
1213 io->u.Status = FILE_GetNtStatus();
1214 res = 0;
1215 goto done;
1218 de = (struct dirent *)data;
1220 if (restart_scan)
1222 /* check if we got . and .. from getdirentries */
1223 if (res > 0)
1225 if (!strcmp( de->d_name, "." ) && res > de->d_reclen)
1227 struct dirent *next_de = (struct dirent *)(data + de->d_reclen);
1228 if (!strcmp( next_de->d_name, ".." )) fake_dot_dot = 0;
1231 /* make sure we have enough room for both entries */
1232 if (fake_dot_dot)
1234 static const ULONG min_info_size = (FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[1]) +
1235 FIELD_OFFSET(FILE_BOTH_DIR_INFORMATION, FileName[2]) + 3) & ~3;
1236 if (length < min_info_size || single_entry)
1238 FIXME( "not enough room %u/%u for fake . and .. entries\n", length, single_entry );
1239 fake_dot_dot = 0;
1243 if (fake_dot_dot)
1245 if ((info = append_entry( buffer, &io->Information, length, ".", NULL, mask )))
1246 last_info = info;
1247 if ((info = append_entry( buffer, &io->Information, length, "..", NULL, mask )))
1248 last_info = info;
1250 restart_last_info = last_info;
1251 restart_info_pos = io->Information;
1253 /* check if we still have enough space for the largest possible entry */
1254 if (last_info && io->Information + max_dir_info_size > length)
1256 lseek( fd, 0, SEEK_SET ); /* reset pos to first entry */
1257 res = 0;
1262 while (res > 0)
1264 res -= de->d_reclen;
1265 if (de->d_fileno &&
1266 !(fake_dot_dot && (!strcmp( de->d_name, "." ) || !strcmp( de->d_name, ".." ))) &&
1267 ((info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask ))))
1269 last_info = info;
1270 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1272 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1273 if (restart_info_pos) /* if we have a complete read already, return it */
1275 io->Information = restart_info_pos;
1276 last_info = restart_last_info;
1277 break;
1279 /* otherwise restart from the start with a smaller size */
1280 size = (char *)de - data;
1281 if (!size)
1283 io->u.Status = STATUS_BUFFER_OVERFLOW;
1284 break;
1286 io->Information = 0;
1287 last_info = NULL;
1288 goto restart;
1290 /* if we have to return but the buffer contains more data, restart with a smaller size */
1291 if (res > 0 && (single_entry || io->Information + max_dir_info_size > length))
1293 lseek( fd, (unsigned long)restart_pos, SEEK_SET );
1294 size = (char *)de - data;
1295 io->Information = restart_info_pos;
1296 last_info = restart_last_info;
1297 goto restart;
1300 /* move on to the next entry */
1301 if (res > 0)
1303 de = (struct dirent *)((char *)de + de->d_reclen);
1304 continue;
1306 if (size < initial_size) break; /* already restarted once, give up now */
1307 size = min( size, length - io->Information );
1308 /* if size is too small don't bother to continue */
1309 if (size < max_dir_info_size && last_info) break;
1310 restart_last_info = last_info;
1311 restart_info_pos = io->Information;
1312 restart:
1313 res = getdirentries( fd, data, size, &restart_pos );
1314 de = (struct dirent *)data;
1317 if (last_info) last_info->NextEntryOffset = 0;
1318 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1319 res = 0;
1320 done:
1321 if (data != local_buffer) RtlFreeHeap( GetProcessHeap(), 0, data );
1322 return res;
1324 #endif /* HAVE_GETDIRENTRIES */
1327 /***********************************************************************
1328 * read_directory_readdir
1330 * Read a directory using the POSIX readdir interface; helper for NtQueryDirectoryFile.
1332 static void read_directory_readdir( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1333 BOOLEAN single_entry, const UNICODE_STRING *mask,
1334 BOOLEAN restart_scan )
1336 DIR *dir;
1337 off_t i, old_pos = 0;
1338 struct dirent *de;
1339 FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
1341 if (!(dir = opendir( "." )))
1343 io->u.Status = FILE_GetNtStatus();
1344 return;
1347 if (!restart_scan)
1349 old_pos = lseek( fd, 0, SEEK_CUR );
1350 /* skip the right number of entries */
1351 for (i = 0; i < old_pos - 2; i++)
1353 if (!readdir( dir ))
1355 closedir( dir );
1356 io->u.Status = STATUS_NO_MORE_FILES;
1357 return;
1361 io->u.Status = STATUS_SUCCESS;
1363 for (;;)
1365 if (old_pos == 0)
1366 info = append_entry( buffer, &io->Information, length, ".", NULL, mask );
1367 else if (old_pos == 1)
1368 info = append_entry( buffer, &io->Information, length, "..", NULL, mask );
1369 else if ((de = readdir( dir )))
1371 if (strcmp( de->d_name, "." ) && strcmp( de->d_name, ".." ))
1372 info = append_entry( buffer, &io->Information, length, de->d_name, NULL, mask );
1373 else
1374 info = NULL;
1376 else
1377 break;
1378 old_pos++;
1379 if (info)
1381 last_info = info;
1382 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1384 io->u.Status = STATUS_BUFFER_OVERFLOW;
1385 old_pos--; /* restore pos to previous entry */
1386 break;
1388 if (single_entry) break;
1389 /* check if we still have enough space for the largest possible entry */
1390 if (io->Information + max_dir_info_size > length) break;
1394 lseek( fd, old_pos, SEEK_SET ); /* store dir offset as filepos for fd */
1395 closedir( dir );
1397 if (last_info) last_info->NextEntryOffset = 0;
1398 else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
1401 /***********************************************************************
1402 * read_directory_stat
1404 * Read a single file from a directory by determining whether the file
1405 * identified by mask exists using stat.
1407 static int read_directory_stat( int fd, IO_STATUS_BLOCK *io, void *buffer, ULONG length,
1408 BOOLEAN single_entry, const UNICODE_STRING *mask,
1409 BOOLEAN restart_scan )
1411 int unix_len, ret, used_default;
1412 char *unix_name;
1413 struct stat st;
1415 TRACE("trying optimisation for file %s\n", debugstr_us( mask ));
1417 unix_len = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), NULL, 0, NULL, NULL );
1418 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len + 1)))
1420 io->u.Status = STATUS_NO_MEMORY;
1421 return 0;
1423 ret = ntdll_wcstoumbs( 0, mask->Buffer, mask->Length / sizeof(WCHAR), unix_name, unix_len,
1424 NULL, &used_default );
1425 if (ret > 0 && !used_default)
1427 unix_name[ret] = 0;
1428 if (restart_scan)
1430 lseek( fd, 0, SEEK_SET );
1432 else if (lseek( fd, 0, SEEK_CUR ) != 0)
1434 io->u.Status = STATUS_NO_MORE_FILES;
1435 ret = 0;
1436 goto done;
1439 ret = stat( unix_name, &st );
1440 if (!ret)
1442 FILE_BOTH_DIR_INFORMATION *info = append_entry( buffer, &io->Information, length, unix_name, NULL, mask );
1443 if (info)
1445 info->NextEntryOffset = 0;
1446 if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
1447 io->u.Status = STATUS_BUFFER_OVERFLOW;
1448 else
1449 lseek( fd, 1, SEEK_CUR );
1453 else ret = -1;
1455 done:
1456 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1458 TRACE("returning %d\n", ret);
1460 return ret;
1464 static inline WCHAR *mempbrkW( const WCHAR *ptr, const WCHAR *accept, size_t n )
1466 const WCHAR *end;
1467 for (end = ptr + n; ptr < end; ptr++) if (strchrW( accept, *ptr )) return (WCHAR *)ptr;
1468 return NULL;
1471 /******************************************************************************
1472 * NtQueryDirectoryFile [NTDLL.@]
1473 * ZwQueryDirectoryFile [NTDLL.@]
1475 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
1476 PIO_APC_ROUTINE apc_routine, PVOID apc_context,
1477 PIO_STATUS_BLOCK io,
1478 PVOID buffer, ULONG length,
1479 FILE_INFORMATION_CLASS info_class,
1480 BOOLEAN single_entry,
1481 PUNICODE_STRING mask,
1482 BOOLEAN restart_scan )
1484 int cwd, fd, needs_close;
1485 static const WCHAR wszWildcards[] = { '*','?',0 };
1487 TRACE("(%p %p %p %p %p %p 0x%08x 0x%08x 0x%08x %s 0x%08x\n",
1488 handle, event, apc_routine, apc_context, io, buffer,
1489 length, info_class, single_entry, debugstr_us(mask),
1490 restart_scan);
1492 if (length < sizeof(FILE_BOTH_DIR_INFORMATION)) return STATUS_INFO_LENGTH_MISMATCH;
1494 if (event || apc_routine)
1496 FIXME( "Unsupported yet option\n" );
1497 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1499 if (info_class != FileBothDirectoryInformation)
1501 FIXME( "Unsupported file info class %d\n", info_class );
1502 return io->u.Status = STATUS_NOT_IMPLEMENTED;
1505 if ((io->u.Status = server_get_unix_fd( handle, FILE_LIST_DIRECTORY, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
1506 return io->u.Status;
1508 io->Information = 0;
1510 RtlEnterCriticalSection( &dir_section );
1512 if (show_dot_files == -1) init_options();
1514 if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
1516 #ifdef VFAT_IOCTL_READDIR_BOTH
1517 if ((read_directory_vfat( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1518 goto done;
1519 #endif
1520 if (mask && !mempbrkW( mask->Buffer, wszWildcards, mask->Length / sizeof(WCHAR) ) &&
1521 read_directory_stat( fd, io, buffer, length, single_entry, mask, restart_scan ) != -1)
1522 goto done;
1523 #ifdef USE_GETDENTS
1524 if ((read_directory_getdents( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1525 goto done;
1526 #elif defined HAVE_GETDIRENTRIES
1527 if ((read_directory_getdirentries( fd, io, buffer, length, single_entry, mask, restart_scan )) != -1)
1528 goto done;
1529 #endif
1530 read_directory_readdir( fd, io, buffer, length, single_entry, mask, restart_scan );
1532 done:
1533 if (fchdir( cwd ) == -1) chdir( "/" );
1535 else io->u.Status = FILE_GetNtStatus();
1537 RtlLeaveCriticalSection( &dir_section );
1539 if (needs_close) close( fd );
1540 if (cwd != -1) close( cwd );
1541 TRACE( "=> %x (%ld)\n", io->u.Status, io->Information );
1542 return io->u.Status;
1546 /***********************************************************************
1547 * find_file_in_dir
1549 * Find a file in a directory the hard way, by doing a case-insensitive search.
1550 * The file found is appended to unix_name at pos.
1551 * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
1553 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
1554 int check_case )
1556 WCHAR buffer[MAX_DIR_ENTRY_LEN];
1557 UNICODE_STRING str;
1558 BOOLEAN spaces;
1559 DIR *dir;
1560 struct dirent *de;
1561 struct stat st;
1562 int ret, used_default, is_name_8_dot_3;
1564 /* try a shortcut for this directory */
1566 unix_name[pos++] = '/';
1567 ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
1568 NULL, &used_default );
1569 /* if we used the default char, the Unix name won't round trip properly back to Unicode */
1570 /* so it cannot match the file we are looking for */
1571 if (ret >= 0 && !used_default)
1573 unix_name[pos + ret] = 0;
1574 if (!stat( unix_name, &st )) return STATUS_SUCCESS;
1576 if (check_case) goto not_found; /* we want an exact match */
1578 if (pos > 1) unix_name[pos - 1] = 0;
1579 else unix_name[1] = 0; /* keep the initial slash */
1581 /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
1583 str.Buffer = (WCHAR *)name;
1584 str.Length = length * sizeof(WCHAR);
1585 str.MaximumLength = str.Length;
1586 is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
1588 /* now look for it through the directory */
1590 #ifdef VFAT_IOCTL_READDIR_BOTH
1591 if (is_name_8_dot_3)
1593 int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
1594 if (fd != -1)
1596 KERNEL_DIRENT *de;
1598 RtlEnterCriticalSection( &dir_section );
1599 if ((de = start_vfat_ioctl( fd )))
1601 unix_name[pos - 1] = '/';
1602 while (de[0].d_reclen)
1604 /* make sure names are null-terminated to work around an x86-64 kernel bug */
1605 size_t len = min(de[0].d_reclen, sizeof(de[0].d_name) - 1 );
1606 de[0].d_name[len] = 0;
1607 len = min(de[1].d_reclen, sizeof(de[1].d_name) - 1 );
1608 de[1].d_name[len] = 0;
1610 if (de[1].d_name[0])
1612 ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
1613 buffer, MAX_DIR_ENTRY_LEN );
1614 if (ret == length && !memicmpW( buffer, name, length))
1616 strcpy( unix_name + pos, de[1].d_name );
1617 RtlLeaveCriticalSection( &dir_section );
1618 close( fd );
1619 return STATUS_SUCCESS;
1622 ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
1623 buffer, MAX_DIR_ENTRY_LEN );
1624 if (ret == length && !memicmpW( buffer, name, length))
1626 strcpy( unix_name + pos,
1627 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
1628 RtlLeaveCriticalSection( &dir_section );
1629 close( fd );
1630 return STATUS_SUCCESS;
1632 if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
1634 RtlLeaveCriticalSection( &dir_section );
1635 close( fd );
1636 goto not_found;
1640 RtlLeaveCriticalSection( &dir_section );
1641 close( fd );
1643 /* fall through to normal handling */
1645 #endif /* VFAT_IOCTL_READDIR_BOTH */
1647 if (!(dir = opendir( unix_name )))
1649 if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
1650 else return FILE_GetNtStatus();
1652 unix_name[pos - 1] = '/';
1653 str.Buffer = buffer;
1654 str.MaximumLength = sizeof(buffer);
1655 while ((de = readdir( dir )))
1657 ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
1658 if (ret == length && !memicmpW( buffer, name, length ))
1660 strcpy( unix_name + pos, de->d_name );
1661 closedir( dir );
1662 return STATUS_SUCCESS;
1665 if (!is_name_8_dot_3) continue;
1667 str.Length = ret * sizeof(WCHAR);
1668 if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
1670 WCHAR short_nameW[12];
1671 ret = hash_short_file_name( &str, short_nameW );
1672 if (ret == length && !memicmpW( short_nameW, name, length ))
1674 strcpy( unix_name + pos, de->d_name );
1675 closedir( dir );
1676 return STATUS_SUCCESS;
1680 closedir( dir );
1681 goto not_found; /* avoid warning */
1683 not_found:
1684 unix_name[pos - 1] = 0;
1685 return STATUS_OBJECT_PATH_NOT_FOUND;
1689 /******************************************************************************
1690 * get_dos_device
1692 * Get the Unix path of a DOS device.
1694 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
1696 const char *config_dir = wine_get_config_dir();
1697 struct stat st;
1698 char *unix_name, *new_name, *dev;
1699 unsigned int i;
1700 int unix_len;
1702 /* make sure the device name is ASCII */
1703 for (i = 0; i < name_len; i++)
1704 if (name[i] <= 32 || name[i] >= 127) return STATUS_BAD_DEVICE_TYPE;
1706 unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
1708 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1709 return STATUS_NO_MEMORY;
1711 strcpy( unix_name, config_dir );
1712 strcat( unix_name, "/dosdevices/" );
1713 dev = unix_name + strlen(unix_name);
1715 for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
1716 dev[i] = 0;
1718 /* special case for drive devices */
1719 if (name_len == 2 && dev[1] == ':')
1721 dev[i++] = ':';
1722 dev[i] = 0;
1725 for (;;)
1727 if (!stat( unix_name, &st ))
1729 TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
1730 unix_name_ret->Buffer = unix_name;
1731 unix_name_ret->Length = strlen(unix_name);
1732 unix_name_ret->MaximumLength = unix_len;
1733 return STATUS_SUCCESS;
1735 if (!dev) break;
1737 /* now try some defaults for it */
1738 if (!strcmp( dev, "aux" ))
1740 strcpy( dev, "com1" );
1741 continue;
1743 if (!strcmp( dev, "prn" ))
1745 strcpy( dev, "lpt1" );
1746 continue;
1748 if (!strcmp( dev, "nul" ))
1750 strcpy( unix_name, "/dev/null" );
1751 dev = NULL; /* last try */
1752 continue;
1755 new_name = NULL;
1756 if (dev[1] == ':' && dev[2] == ':') /* drive device */
1758 dev[2] = 0; /* remove last ':' to get the drive mount point symlink */
1759 new_name = get_default_drive_device( unix_name );
1761 else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
1762 else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
1764 if (!new_name) break;
1766 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1767 unix_name = new_name;
1768 unix_len = strlen(unix_name) + 1;
1769 dev = NULL; /* last try */
1771 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1772 return STATUS_BAD_DEVICE_TYPE;
1776 /* return the length of the DOS namespace prefix if any */
1777 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1779 static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1780 static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1782 if (name->Length > sizeof(nt_prefixW) &&
1783 !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1784 return sizeof(nt_prefixW) / sizeof(WCHAR);
1786 if (name->Length > sizeof(dosdev_prefixW) &&
1787 !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1788 return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1790 return 0;
1794 /******************************************************************************
1795 * wine_nt_to_unix_file_name (NTDLL.@) Not a Windows API
1797 * Convert a file name from NT namespace to Unix namespace.
1799 * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1800 * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1801 * returned, but the unix name is still filled in properly.
1803 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1804 UINT disposition, BOOLEAN check_case )
1806 static const WCHAR uncW[] = {'U','N','C','\\'};
1807 static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1809 NTSTATUS status = STATUS_SUCCESS;
1810 const char *config_dir = wine_get_config_dir();
1811 const WCHAR *name, *p;
1812 struct stat st;
1813 char *unix_name;
1814 int pos, ret, name_len, unix_len, used_default;
1816 name = nameW->Buffer;
1817 name_len = nameW->Length / sizeof(WCHAR);
1819 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1821 if ((pos = get_dos_prefix_len( nameW )))
1823 BOOLEAN is_unc = FALSE;
1825 name += pos;
1826 name_len -= pos;
1828 /* check for UNC prefix */
1829 if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1831 name += 3;
1832 name_len -= 3;
1833 is_unc = TRUE;
1835 else
1837 /* check for a drive letter with path */
1838 if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1840 /* not a drive with path, try other DOS devices */
1841 return get_dos_device( name, name_len, unix_name_ret );
1843 name += 2; /* skip drive letter */
1844 name_len -= 2;
1847 /* check for invalid characters */
1848 for (p = name; p < name + name_len; p++)
1849 if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1851 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1852 unix_len += MAX_DIR_ENTRY_LEN + 3;
1853 unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1854 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1855 return STATUS_NO_MEMORY;
1856 strcpy( unix_name, config_dir );
1857 strcat( unix_name, "/dosdevices/" );
1858 pos = strlen(unix_name);
1859 if (is_unc)
1861 strcpy( unix_name + pos, "unc" );
1862 pos += 3;
1864 else
1866 unix_name[pos++] = tolowerW( name[-2] );
1867 unix_name[pos++] = ':';
1868 unix_name[pos] = 0;
1871 else /* no DOS prefix, assume NT native name, map directly to Unix */
1873 if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1874 unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1875 unix_len += MAX_DIR_ENTRY_LEN + 3;
1876 if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1877 return STATUS_NO_MEMORY;
1878 pos = 0;
1881 /* try a shortcut first */
1883 ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1884 NULL, &used_default );
1886 while (name_len && IS_SEPARATOR(*name))
1888 name++;
1889 name_len--;
1892 if (ret > 0 && !used_default) /* if we used the default char the name didn't convert properly */
1894 char *p;
1895 unix_name[pos + ret] = 0;
1896 for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1897 if (!stat( unix_name, &st ))
1899 /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1900 if (disposition == FILE_CREATE)
1902 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1903 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1905 goto done;
1909 if (!name_len) /* empty name -> drive root doesn't exist */
1911 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1912 return STATUS_OBJECT_PATH_NOT_FOUND;
1914 if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1916 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1917 return STATUS_OBJECT_NAME_NOT_FOUND;
1920 /* now do it component by component */
1922 while (name_len)
1924 const WCHAR *end, *next;
1926 end = name;
1927 while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1928 next = end;
1929 while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1930 name_len -= next - name;
1932 /* grow the buffer if needed */
1934 if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1936 char *new_name;
1937 unix_len += 2 * MAX_DIR_ENTRY_LEN;
1938 if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1940 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1941 return STATUS_NO_MEMORY;
1943 unix_name = new_name;
1946 status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1948 /* if this is the last element, not finding it is not necessarily fatal */
1949 if (!name_len)
1951 if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1953 status = STATUS_OBJECT_NAME_NOT_FOUND;
1954 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1956 ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1957 MAX_DIR_ENTRY_LEN, NULL, &used_default );
1958 if (ret > 0 && !used_default)
1960 unix_name[pos] = '/';
1961 unix_name[pos + 1 + ret] = 0;
1962 status = STATUS_NO_SUCH_FILE;
1963 break;
1967 else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1969 status = STATUS_OBJECT_NAME_COLLISION;
1973 if (status != STATUS_SUCCESS)
1975 /* couldn't find it at all, fail */
1976 WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1977 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1978 return status;
1981 pos += strlen( unix_name + pos );
1982 name = next;
1985 WARN( "%s -> %s required a case-insensitive search\n",
1986 debugstr_us(nameW), debugstr_a(unix_name) );
1988 done:
1989 TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1990 unix_name_ret->Buffer = unix_name;
1991 unix_name_ret->Length = strlen(unix_name);
1992 unix_name_ret->MaximumLength = unix_len;
1993 return status;
1997 /******************************************************************
1998 * RtlDoesFileExists_U (NTDLL.@)
2000 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
2002 UNICODE_STRING nt_name;
2003 ANSI_STRING unix_name;
2004 BOOLEAN ret;
2006 if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
2007 ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
2008 if (ret) RtlFreeAnsiString( &unix_name );
2009 RtlFreeUnicodeString( &nt_name );
2010 return ret;
2014 /***********************************************************************
2015 * DIR_unmount_device
2017 * Unmount the specified device.
2019 NTSTATUS DIR_unmount_device( HANDLE handle )
2021 NTSTATUS status;
2022 int unix_fd, needs_close;
2024 SERVER_START_REQ( unmount_device )
2026 req->handle = handle;
2027 status = wine_server_call( req );
2029 SERVER_END_REQ;
2030 if (status) return status;
2032 if (!(status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )))
2034 struct stat st;
2035 char *mount_point = NULL;
2037 if (fstat( unix_fd, &st ) == -1 || !is_valid_mounted_device( &st ))
2038 status = STATUS_INVALID_PARAMETER;
2039 else
2041 if ((mount_point = get_device_mount_point( st.st_rdev )))
2043 #ifdef __APPLE__
2044 static const char umount[] = "diskutil unmount >/dev/null 2>&1 ";
2045 #else
2046 static const char umount[] = "umount >/dev/null 2>&1 ";
2047 #endif
2048 char *cmd = RtlAllocateHeap( GetProcessHeap(), 0, strlen(mount_point)+sizeof(umount));
2049 if (cmd)
2051 strcpy( cmd, umount );
2052 strcat( cmd, mount_point );
2053 system( cmd );
2054 RtlFreeHeap( GetProcessHeap(), 0, cmd );
2055 #ifdef linux
2056 /* umount will fail to release the loop device since we still have
2057 a handle to it, so we release it here */
2058 if (major(st.st_rdev) == LOOP_MAJOR) ioctl( unix_fd, 0x4c01 /*LOOP_CLR_FD*/, 0 );
2059 #endif
2061 RtlFreeHeap( GetProcessHeap(), 0, mount_point );
2064 if (needs_close) close( unix_fd );
2066 return status;
2070 /******************************************************************************
2071 * DIR_get_unix_cwd
2073 * Retrieve the Unix name of the current directory; helper for wine_unix_to_nt_file_name.
2074 * Returned value must be freed by caller.
2076 NTSTATUS DIR_get_unix_cwd( char **cwd )
2078 int old_cwd, unix_fd, needs_close;
2079 CURDIR *curdir;
2080 HANDLE handle;
2081 NTSTATUS status;
2083 RtlAcquirePebLock();
2085 if (NtCurrentTeb()->Tib.SubSystemTib) /* FIXME: hack */
2086 curdir = &((WIN16_SUBSYSTEM_TIB *)NtCurrentTeb()->Tib.SubSystemTib)->curdir;
2087 else
2088 curdir = &NtCurrentTeb()->Peb->ProcessParameters->CurrentDirectory;
2090 if (!(handle = curdir->Handle))
2092 UNICODE_STRING dirW;
2093 OBJECT_ATTRIBUTES attr;
2094 IO_STATUS_BLOCK io;
2096 if (!RtlDosPathNameToNtPathName_U( curdir->DosPath.Buffer, &dirW, NULL, NULL ))
2098 status = STATUS_OBJECT_NAME_INVALID;
2099 goto done;
2101 attr.Length = sizeof(attr);
2102 attr.RootDirectory = 0;
2103 attr.Attributes = OBJ_CASE_INSENSITIVE;
2104 attr.ObjectName = &dirW;
2105 attr.SecurityDescriptor = NULL;
2106 attr.SecurityQualityOfService = NULL;
2108 status = NtOpenFile( &handle, 0, &attr, &io, 0,
2109 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
2110 RtlFreeUnicodeString( &dirW );
2111 if (status != STATUS_SUCCESS) goto done;
2114 if ((status = server_get_unix_fd( handle, 0, &unix_fd, &needs_close, NULL, NULL )) == STATUS_SUCCESS)
2116 RtlEnterCriticalSection( &dir_section );
2118 if ((old_cwd = open(".", O_RDONLY)) != -1 && fchdir( unix_fd ) != -1)
2120 unsigned int size = 512;
2122 for (;;)
2124 if (!(*cwd = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2126 status = STATUS_NO_MEMORY;
2127 break;
2129 if (getcwd( *cwd, size )) break;
2130 RtlFreeHeap( GetProcessHeap(), 0, *cwd );
2131 if (errno != ERANGE)
2133 status = STATUS_OBJECT_PATH_INVALID;
2134 break;
2136 size *= 2;
2138 if (fchdir( old_cwd ) == -1) chdir( "/" );
2140 else status = FILE_GetNtStatus();
2142 RtlLeaveCriticalSection( &dir_section );
2143 if (needs_close) close( unix_fd );
2145 if (!curdir->Handle) NtClose( handle );
2147 done:
2148 RtlReleasePebLock();
2149 return status;
2152 struct read_changes_info
2154 HANDLE FileHandle;
2155 HANDLE Event;
2156 PIO_APC_ROUTINE ApcRoutine;
2157 PVOID ApcContext;
2158 PVOID Buffer;
2159 ULONG BufferSize;
2162 static void WINAPI read_changes_apc( void *user, PIO_STATUS_BLOCK iosb, ULONG status )
2164 struct read_changes_info *info = user;
2165 char path[PATH_MAX];
2166 NTSTATUS ret = STATUS_SUCCESS;
2167 int len, action, i;
2169 TRACE("%p %p %p %08x\n", info, info->ApcContext, iosb, status);
2172 * FIXME: race me!
2174 * hEvent/hDir is set before the output buffer and iosb is updated.
2175 * Since the thread that called NtNotifyChangeDirectoryFile is usually
2176 * waiting, we'll be safe since we're called in that thread's context.
2177 * If a different thread is waiting on our hEvent/hDir we're going to be
2178 * in trouble...
2180 SERVER_START_REQ( read_change )
2182 req->handle = info->FileHandle;
2183 wine_server_set_reply( req, path, PATH_MAX );
2184 ret = wine_server_call( req );
2185 action = reply->action;
2186 len = wine_server_reply_size( reply );
2188 SERVER_END_REQ;
2190 if (ret == STATUS_SUCCESS && info->Buffer &&
2191 (info->BufferSize > (sizeof (FILE_NOTIFY_INFORMATION) + len*sizeof(WCHAR))))
2193 PFILE_NOTIFY_INFORMATION pfni;
2195 pfni = (PFILE_NOTIFY_INFORMATION) info->Buffer;
2197 /* convert to an NT style path */
2198 for (i=0; i<len; i++)
2199 if (path[i] == '/')
2200 path[i] = '\\';
2202 len = ntdll_umbstowcs( 0, path, len, pfni->FileName,
2203 info->BufferSize - sizeof (*pfni) );
2205 pfni->NextEntryOffset = 0;
2206 pfni->Action = action;
2207 pfni->FileNameLength = len * sizeof (WCHAR);
2208 pfni->FileName[len] = 0;
2210 TRACE("action = %d name = %s\n", pfni->Action,
2211 debugstr_w(pfni->FileName) );
2212 len = sizeof (*pfni) - sizeof (DWORD) + pfni->FileNameLength;
2214 else
2216 ret = STATUS_NOTIFY_ENUM_DIR;
2217 len = 0;
2220 iosb->u.Status = ret;
2221 iosb->Information = len;
2223 RtlFreeHeap( GetProcessHeap(), 0, info );
2226 #define FILE_NOTIFY_ALL ( \
2227 FILE_NOTIFY_CHANGE_FILE_NAME | \
2228 FILE_NOTIFY_CHANGE_DIR_NAME | \
2229 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
2230 FILE_NOTIFY_CHANGE_SIZE | \
2231 FILE_NOTIFY_CHANGE_LAST_WRITE | \
2232 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
2233 FILE_NOTIFY_CHANGE_CREATION | \
2234 FILE_NOTIFY_CHANGE_SECURITY )
2236 /******************************************************************************
2237 * NtNotifyChangeDirectoryFile [NTDLL.@]
2239 NTSTATUS WINAPI
2240 NtNotifyChangeDirectoryFile( HANDLE FileHandle, HANDLE Event,
2241 PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext,
2242 PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer,
2243 ULONG BufferSize, ULONG CompletionFilter, BOOLEAN WatchTree )
2245 struct read_changes_info *info;
2246 NTSTATUS status;
2248 TRACE("%p %p %p %p %p %p %u %u %d\n",
2249 FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock,
2250 Buffer, BufferSize, CompletionFilter, WatchTree );
2252 if (!IoStatusBlock)
2253 return STATUS_ACCESS_VIOLATION;
2255 if (CompletionFilter == 0 || (CompletionFilter & ~FILE_NOTIFY_ALL))
2256 return STATUS_INVALID_PARAMETER;
2258 if (ApcRoutine)
2259 FIXME("parameters ignored %p %p\n", ApcRoutine, ApcContext );
2261 info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof *info );
2262 if (!info)
2263 return STATUS_NO_MEMORY;
2265 info->FileHandle = FileHandle;
2266 info->Event = Event;
2267 info->Buffer = Buffer;
2268 info->BufferSize = BufferSize;
2269 info->ApcRoutine = ApcRoutine;
2270 info->ApcContext = ApcContext;
2272 SERVER_START_REQ( read_directory_changes )
2274 req->handle = FileHandle;
2275 req->event = Event;
2276 req->filter = CompletionFilter;
2277 req->want_data = (Buffer != NULL);
2278 req->subtree = WatchTree;
2279 req->io_apc = read_changes_apc;
2280 req->io_sb = IoStatusBlock;
2281 req->io_user = info;
2282 status = wine_server_call( req );
2284 SERVER_END_REQ;
2286 if (status != STATUS_PENDING)
2287 RtlFreeHeap( GetProcessHeap(), 0, info );
2289 return status;