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