Cygwin's mntent.h requires stdio.h to be included first.
[wine] / dlls / ntdll / directory.c
1 /*
2  * NTDLL directory functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 2003 Eric Pouech
6  * Copyright 1996, 2004 Alexandre Julliard
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
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 #ifdef HAVE_MNTENT_H
35 #include <mntent.h>
36 #endif
37 #include <sys/stat.h>
38 #ifdef HAVE_SYS_IOCTL_H
39 #include <sys/ioctl.h>
40 #endif
41 #ifdef HAVE_LINUX_IOCTL_H
42 #include <linux/ioctl.h>
43 #endif
44 #include <time.h>
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48
49 #define NONAMELESSUNION
50 #define NONAMELESSSTRUCT
51 #include "windef.h"
52 #include "winbase.h"
53 #include "winnt.h"
54 #include "winreg.h"
55 #include "ntstatus.h"
56 #include "winternl.h"
57 #include "ntdll_misc.h"
58 #include "wine/unicode.h"
59 #include "wine/server.h"
60 #include "wine/library.h"
61 #include "wine/debug.h"
62
63 WINE_DEFAULT_DEBUG_CHANNEL(file);
64
65 /* Define the VFAT ioctl to get both short and long file names */
66 /* FIXME: is it possible to get this to work on other systems? */
67 #ifdef linux
68 /* We want the real kernel dirent structure, not the libc one */
69 typedef struct
70 {
71     long d_ino;
72     long d_off;
73     unsigned short d_reclen;
74     char d_name[256];
75 } KERNEL_DIRENT;
76
77 #define VFAT_IOCTL_READDIR_BOTH  _IOR('r', 1, KERNEL_DIRENT [2] )
78
79 #ifndef O_DIRECTORY
80 # define O_DIRECTORY 0200000 /* must be directory */
81 #endif
82
83 /* Using the same seekdir value across multiple directories is not portable,  */
84 /* but it works on Linux, and it's a major performance gain so we want to use */
85 /* it if possible. */
86 /* FIXME: do some sort of runtime check instead */
87 #define USE_SEEKDIR
88
89 #else   /* linux */
90 #undef VFAT_IOCTL_READDIR_BOTH  /* just in case... */
91 #undef USE_SEEKDIR
92 #endif  /* linux */
93
94 #define IS_OPTION_TRUE(ch) ((ch) == 'y' || (ch) == 'Y' || (ch) == 't' || (ch) == 'T' || (ch) == '1')
95 #define IS_SEPARATOR(ch)   ((ch) == '\\' || (ch) == '/')
96
97 #define INVALID_NT_CHARS   '*','?','<','>','|','"'
98 #define INVALID_DOS_CHARS  INVALID_NT_CHARS,'+','=',',',';','[',']',' ','\345'
99
100 #define MAX_DIR_ENTRY_LEN 255  /* max length of a directory entry in chars */
101
102 static int show_dir_symlinks = -1;
103 static int show_dot_files;
104
105 /* at some point we may want to allow Winelib apps to set this */
106 static const int is_case_sensitive = FALSE;
107
108 static CRITICAL_SECTION dir_section;
109 static CRITICAL_SECTION_DEBUG critsect_debug =
110 {
111     0, 0, &dir_section,
112     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
113       0, 0, { 0, (DWORD)(__FILE__ ": dir_section") }
114 };
115 static CRITICAL_SECTION dir_section = { &critsect_debug, -1, 0, 0, 0, 0 };
116
117
118 /***********************************************************************
119  *           seekdir_wrapper
120  *
121  * Wrapper for supporting seekdir across multiple directory objects.
122  */
123 static inline void seekdir_wrapper( DIR *dir, off_t pos )
124 {
125 #ifdef USE_SEEKDIR
126     seekdir( dir, pos );
127 #else
128     while (pos-- > 0) if (!readdir( dir )) break;
129 #endif
130 }
131
132 /***********************************************************************
133  *           telldir_wrapper
134  *
135  * Wrapper for supporting telldir across multiple directory objects.
136  */
137 static inline off_t telldir_wrapper( DIR *dir, off_t pos, int count )
138 {
139 #ifdef USE_SEEKDIR
140     return telldir( dir );
141 #else
142     return pos + count;
143 #endif
144 }
145
146
147 /***********************************************************************
148  *           get_default_com_device
149  *
150  * Return the default device to use for serial ports.
151  */
152 static char *get_default_com_device( int num )
153 {
154     char *ret = NULL;
155
156     if (!num || num > 9) return ret;
157 #ifdef linux
158     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/ttyS0") );
159     if (ret)
160     {
161         strcpy( ret, "/dev/ttyS0" );
162         ret[strlen(ret) - 1] = '0' + num - 1;
163     }
164 #else
165     FIXME( "no known default for device com%d\n", num );
166 #endif
167     return ret;
168 }
169
170
171 /***********************************************************************
172  *           get_default_lpt_device
173  *
174  * Return the default device to use for parallel ports.
175  */
176 static char *get_default_lpt_device( int num )
177 {
178     char *ret = NULL;
179
180     if (!num || num > 9) return ret;
181 #ifdef linux
182     ret = RtlAllocateHeap( GetProcessHeap(), 0, sizeof("/dev/lp0") );
183     if (ret)
184     {
185         strcpy( ret, "/dev/lp0" );
186         ret[strlen(ret) - 1] = '0' + num - 1;
187     }
188 #else
189     FIXME( "no known default for device lpt%d\n", num );
190 #endif
191     return ret;
192 }
193
194
195 /***********************************************************************
196  *           parse_mount_entries
197  *
198  * Parse mount entries looking for a given device. Helper for get_default_drive_device.
199  */
200 #ifdef linux
201 static char *parse_mount_entries( FILE *f, dev_t dev, ino_t ino )
202 {
203     struct mntent *entry;
204     struct stat st;
205     char *device;
206
207     while ((entry = getmntent( f )))
208     {
209         if (stat( entry->mnt_dir, &st ) == -1) continue;
210         if (st.st_dev != dev || st.st_ino != ino) continue;
211         if (!strcmp( entry->mnt_type, "supermount" ))
212         {
213             if ((device = strstr( entry->mnt_opts, "dev=" )))
214             {
215                 char *p = strchr( device + 4, ',' );
216                 if (p) *p = 0;
217                 return device + 4;
218             }
219         }
220         else
221             return entry->mnt_fsname;
222     }
223     return NULL;
224 }
225 #endif
226
227 /***********************************************************************
228  *           get_default_drive_device
229  *
230  * Return the default device to use for a given drive mount point.
231  */
232 static char *get_default_drive_device( const char *root )
233 {
234     char *ret = NULL;
235
236 #ifdef linux
237     FILE *f;
238     char *device = NULL;
239     int fd, res = -1;
240     struct stat st;
241
242     /* try to open it first to force it to get mounted */
243     if ((fd = open( root, O_RDONLY | O_DIRECTORY )) != -1)
244     {
245         res = fstat( fd, &st );
246         close( fd );
247     }
248     /* now try normal stat just in case */
249     if (res == -1) res = stat( root, &st );
250     if (res == -1) return NULL;
251
252     RtlEnterCriticalSection( &dir_section );
253
254     if ((f = fopen( "/etc/mtab", "r" )))
255     {
256         device = parse_mount_entries( f, st.st_dev, st.st_ino );
257         endmntent( f );
258     }
259     /* look through fstab too in case it's not mounted (for instance if it's an audio CD) */
260     if (!device && (f = fopen( "/etc/fstab", "r" )))
261     {
262         device = parse_mount_entries( f, st.st_dev, st.st_ino );
263         endmntent( f );
264     }
265     if (device)
266     {
267         ret = RtlAllocateHeap( GetProcessHeap(), 0, strlen(device) + 1 );
268         if (ret) strcpy( ret, device );
269     }
270     RtlLeaveCriticalSection( &dir_section );
271 #else
272     static int warned;
273     if (!warned++) FIXME( "auto detection of DOS devices not supported on this platform\n" );
274 #endif
275     return ret;
276 }
277
278
279 /***********************************************************************
280  *           init_options
281  *
282  * Initialize the show_dir_symlinks and show_dot_files options.
283  */
284 static void init_options(void)
285 {
286     static const WCHAR WineW[] = {'M','a','c','h','i','n','e','\\',
287                                   'S','o','f','t','w','a','r','e','\\',
288                                   'W','i','n','e','\\','W','i','n','e','\\',
289                                   'C','o','n','f','i','g','\\','W','i','n','e',0};
290     static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
291     static const WCHAR ShowDirSymlinksW[] = {'S','h','o','w','D','i','r','S','y','m','l','i','n','k','s',0};
292     char tmp[80];
293     HKEY hkey;
294     DWORD dummy;
295     OBJECT_ATTRIBUTES attr;
296     UNICODE_STRING nameW;
297
298     show_dot_files = show_dir_symlinks = 0;
299
300     attr.Length = sizeof(attr);
301     attr.RootDirectory = 0;
302     attr.ObjectName = &nameW;
303     attr.Attributes = 0;
304     attr.SecurityDescriptor = NULL;
305     attr.SecurityQualityOfService = NULL;
306     RtlInitUnicodeString( &nameW, WineW );
307
308     if (!NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ))
309     {
310         RtlInitUnicodeString( &nameW, ShowDotFilesW );
311         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
312         {
313             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
314             show_dot_files = IS_OPTION_TRUE( str[0] );
315         }
316         RtlInitUnicodeString( &nameW, ShowDirSymlinksW );
317         if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
318         {
319             WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
320             show_dir_symlinks = IS_OPTION_TRUE( str[0] );
321         }
322         NtClose( hkey );
323     }
324 }
325
326
327 /***********************************************************************
328  *           DIR_is_hidden_file
329  *
330  * Check if the specified file should be hidden based on its name and the show dot files option.
331  */
332 BOOL DIR_is_hidden_file( const UNICODE_STRING *name )
333 {
334     WCHAR *p, *end;
335
336     if (show_dir_symlinks == -1) init_options();
337     if (show_dot_files) return FALSE;
338
339     end = p = name->Buffer + name->Length/sizeof(WCHAR);
340     while (p > name->Buffer && IS_SEPARATOR(p[-1])) p--;
341     while (p > name->Buffer && !IS_SEPARATOR(p[-1])) p--;
342     if (p == end || *p != '.') return FALSE;
343     /* make sure it isn't '.' or '..' */
344     if (p + 1 == end) return FALSE;
345     if (p[1] == '.' && p + 2 == end) return FALSE;
346     return TRUE;
347 }
348
349
350 /***********************************************************************
351  *           hash_short_file_name
352  *
353  * Transform a Unix file name into a hashed DOS name. If the name is a valid
354  * DOS name, it is converted to upper-case; otherwise it is replaced by a
355  * hashed version that fits in 8.3 format.
356  * 'buffer' must be at least 12 characters long.
357  * Returns length of short name in bytes; short name is NOT null-terminated.
358  */
359 static ULONG hash_short_file_name( const UNICODE_STRING *name, LPWSTR buffer )
360 {
361     static const WCHAR invalid_chars[] = { INVALID_DOS_CHARS,'~','.',0 };
362     static const char hash_chars[32] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
363
364     LPCWSTR p, ext, end = name->Buffer + name->Length / sizeof(WCHAR);
365     LPWSTR dst;
366     unsigned short hash;
367     int i;
368
369     /* Compute the hash code of the file name */
370     /* If you know something about hash functions, feel free to */
371     /* insert a better algorithm here... */
372     if (!is_case_sensitive)
373     {
374         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
375             hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p) ^ (tolowerW(p[1]) << 8);
376         hash = (hash<<3) ^ (hash>>5) ^ tolowerW(*p); /* Last character */
377     }
378     else
379     {
380         for (p = name->Buffer, hash = 0xbeef; p < end - 1; p++)
381             hash = (hash << 3) ^ (hash >> 5) ^ *p ^ (p[1] << 8);
382         hash = (hash << 3) ^ (hash >> 5) ^ *p;  /* Last character */
383     }
384
385     /* Find last dot for start of the extension */
386     for (p = name->Buffer + 1, ext = NULL; p < end - 1; p++) if (*p == '.') ext = p;
387
388     /* Copy first 4 chars, replacing invalid chars with '_' */
389     for (i = 4, p = name->Buffer, dst = buffer; i > 0; i--, p++)
390     {
391         if (p == end || p == ext) break;
392         *dst++ = strchrW( invalid_chars, *p ) ? '_' : toupperW(*p);
393     }
394     /* Pad to 5 chars with '~' */
395     while (i-- >= 0) *dst++ = '~';
396
397     /* Insert hash code converted to 3 ASCII chars */
398     *dst++ = hash_chars[(hash >> 10) & 0x1f];
399     *dst++ = hash_chars[(hash >> 5) & 0x1f];
400     *dst++ = hash_chars[hash & 0x1f];
401
402     /* Copy the first 3 chars of the extension (if any) */
403     if (ext)
404     {
405         *dst++ = '.';
406         for (i = 3, ext++; (i > 0) && ext < end; i--, ext++)
407             *dst++ = strchrW( invalid_chars, *ext ) ? '_' : toupperW(*ext);
408     }
409     return dst - buffer;
410 }
411
412
413 /***********************************************************************
414  *           match_filename
415  *
416  * Check a long file name against a mask.
417  *
418  * Tests (done in W95 DOS shell - case insensitive):
419  * *.txt                        test1.test.txt                          *
420  * *st1*                        test1.txt                               *
421  * *.t??????.t*                 test1.ta.tornado.txt                    *
422  * *tornado*                    test1.ta.tornado.txt                    *
423  * t*t                          test1.ta.tornado.txt                    *
424  * ?est*                        test1.txt                               *
425  * ?est???                      test1.txt                               -
426  * *test1.txt*                  test1.txt                               *
427  * h?l?o*t.dat                  hellothisisatest.dat                    *
428  */
429 static BOOLEAN match_filename( const UNICODE_STRING *name_str, const UNICODE_STRING *mask_str )
430 {
431     int mismatch;
432     const WCHAR *name = name_str->Buffer;
433     const WCHAR *mask = mask_str->Buffer;
434     const WCHAR *name_end = name + name_str->Length / sizeof(WCHAR);
435     const WCHAR *mask_end = mask + mask_str->Length / sizeof(WCHAR);
436     const WCHAR *lastjoker = NULL;
437     const WCHAR *next_to_retry = NULL;
438
439     TRACE("(%s, %s)\n", debugstr_us(name_str), debugstr_us(mask_str));
440
441     while (name < name_end && mask < mask_end)
442     {
443         switch(*mask)
444         {
445         case '*':
446             mask++;
447             while (mask < mask_end && *mask == '*') mask++;  /* Skip consecutive '*' */
448             if (mask == mask_end) return TRUE; /* end of mask is all '*', so match */
449             lastjoker = mask;
450
451             /* skip to the next match after the joker(s) */
452             if (is_case_sensitive)
453                 while (name < name_end && (*name != *mask)) name++;
454             else
455                 while (name < name_end && (toupperW(*name) != toupperW(*mask))) name++;
456             next_to_retry = name;
457             break;
458         case '?':
459             mask++;
460             name++;
461             break;
462         default:
463             if (is_case_sensitive) mismatch = (*mask != *name);
464             else mismatch = (toupperW(*mask) != toupperW(*name));
465
466             if (!mismatch)
467             {
468                 mask++;
469                 name++;
470                 if (mask == mask_end)
471                 {
472                     if (name == name_end) return TRUE;
473                     if (lastjoker) mask = lastjoker;
474                 }
475             }
476             else /* mismatch ! */
477             {
478                 if (lastjoker) /* we had an '*', so we can try unlimitedly */
479                 {
480                     mask = lastjoker;
481
482                     /* this scan sequence was a mismatch, so restart
483                      * 1 char after the first char we checked last time */
484                     next_to_retry++;
485                     name = next_to_retry;
486                 }
487                 else return FALSE; /* bad luck */
488             }
489             break;
490         }
491     }
492     while (mask < mask_end && ((*mask == '.') || (*mask == '*')))
493         mask++;  /* Ignore trailing '.' or '*' in mask */
494     return (name == name_end && mask == mask_end);
495 }
496
497
498 /***********************************************************************
499  *           append_entry
500  *
501  * helper for NtQueryDirectoryFile
502  */
503 static FILE_BOTH_DIR_INFORMATION *append_entry( void *info_ptr, ULONG *pos, ULONG max_length,
504                                                 const char *long_name, const char *short_name,
505                                                 const UNICODE_STRING *mask )
506 {
507     FILE_BOTH_DIR_INFORMATION *info;
508     int i, long_len, short_len, total_len;
509     struct stat st;
510     WCHAR long_nameW[MAX_DIR_ENTRY_LEN];
511     WCHAR short_nameW[12];
512     UNICODE_STRING str;
513
514     long_len = ntdll_umbstowcs( 0, long_name, strlen(long_name), long_nameW, MAX_DIR_ENTRY_LEN );
515     if (long_len == -1) return NULL;
516
517     str.Buffer = long_nameW;
518     str.Length = long_len * sizeof(WCHAR);
519     str.MaximumLength = sizeof(long_nameW);
520
521     if (short_name)
522     {
523         short_len = ntdll_umbstowcs( 0, short_name, strlen(short_name),
524                                      short_nameW, sizeof(short_nameW) / sizeof(WCHAR) );
525         if (short_len == -1) short_len = sizeof(short_nameW) / sizeof(WCHAR);
526     }
527     else  /* generate a short name if necessary */
528     {
529         BOOLEAN spaces;
530
531         short_len = 0;
532         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
533             short_len = hash_short_file_name( &str, short_nameW );
534     }
535
536     TRACE( "long %s short %s mask %s\n",
537            debugstr_us(&str), debugstr_wn(short_nameW, short_len), debugstr_us(mask) );
538
539     if (mask && !match_filename( &str, mask ))
540     {
541         if (!short_len) return NULL;  /* no short name to match */
542         str.Buffer = short_nameW;
543         str.Length = short_len * sizeof(WCHAR);
544         str.MaximumLength = sizeof(short_nameW);
545         if (!match_filename( &str, mask )) return NULL;
546     }
547
548     total_len = (sizeof(*info) - sizeof(info->FileName) + long_len*sizeof(WCHAR) + 3) & ~3;
549     info = (FILE_BOTH_DIR_INFORMATION *)((char *)info_ptr + *pos);
550
551     if (*pos + total_len > max_length) total_len = max_length - *pos;
552
553     if (lstat( long_name, &st ) == -1) return NULL;
554     if (S_ISLNK( st.st_mode ))
555     {
556         if (stat( long_name, &st ) == -1) return NULL;
557         if (S_ISDIR( st.st_mode ) && !show_dir_symlinks) return NULL;
558     }
559
560     info->NextEntryOffset = total_len;
561     info->FileIndex = 0;  /* NTFS always has 0 here, so let's not bother with it */
562
563     RtlSecondsSince1970ToTime( st.st_mtime, &info->CreationTime );
564     RtlSecondsSince1970ToTime( st.st_mtime, &info->LastWriteTime );
565     RtlSecondsSince1970ToTime( st.st_atime, &info->LastAccessTime );
566     RtlSecondsSince1970ToTime( st.st_ctime, &info->ChangeTime );
567
568     if (S_ISDIR(st.st_mode))
569     {
570         info->EndOfFile.QuadPart = info->AllocationSize.QuadPart = 0;
571         info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
572     }
573     else
574     {
575         info->EndOfFile.QuadPart = st.st_size;
576         info->AllocationSize.QuadPart = (ULONGLONG)st.st_blocks * 512;
577         info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
578     }
579
580     if (!(st.st_mode & S_IWUSR))
581         info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
582
583     if (!show_dot_files && long_name[0] == '.' && long_name[1] && (long_name[1] != '.' || long_name[2]))
584         info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
585
586     info->EaSize = 0; /* FIXME */
587     info->ShortNameLength = short_len * sizeof(WCHAR);
588     for (i = 0; i < short_len; i++) info->ShortName[i] = toupperW(short_nameW[i]);
589     info->FileNameLength = long_len * sizeof(WCHAR);
590     memcpy( info->FileName, long_nameW,
591             min( info->FileNameLength, total_len-sizeof(*info)+sizeof(info->FileName) ));
592
593     *pos += total_len;
594     return info;
595 }
596
597
598 /******************************************************************************
599  *  NtQueryDirectoryFile        [NTDLL.@]
600  *  ZwQueryDirectoryFile        [NTDLL.@]
601  */
602 NTSTATUS WINAPI NtQueryDirectoryFile( HANDLE handle, HANDLE event,
603                                       PIO_APC_ROUTINE apc_routine, PVOID apc_context,
604                                       PIO_STATUS_BLOCK io,
605                                       PVOID buffer, ULONG length,
606                                       FILE_INFORMATION_CLASS info_class,
607                                       BOOLEAN single_entry,
608                                       PUNICODE_STRING mask,
609                                       BOOLEAN restart_scan )
610 {
611     int cwd, fd;
612     FILE_BOTH_DIR_INFORMATION *info, *last_info = NULL;
613     static const int max_dir_info_size = sizeof(*info) + (MAX_DIR_ENTRY_LEN-1) * sizeof(WCHAR);
614
615     TRACE("(%p %p %p %p %p %p 0x%08lx 0x%08x 0x%08x %s 0x%08x\n",
616           handle, event, apc_routine, apc_context, io, buffer,
617           length, info_class, single_entry, debugstr_us(mask),
618           restart_scan);
619
620     if (length < sizeof(*info)) return STATUS_INFO_LENGTH_MISMATCH;
621
622     if (event || apc_routine)
623     {
624         FIXME( "Unsupported yet option\n" );
625         return io->u.Status = STATUS_NOT_IMPLEMENTED;
626     }
627     if (info_class != FileBothDirectoryInformation)
628     {
629         FIXME( "Unsupported file info class %d\n", info_class );
630         return io->u.Status = STATUS_NOT_IMPLEMENTED;
631     }
632
633     if ((io->u.Status = wine_server_handle_to_fd( handle, GENERIC_READ,
634                                                   &fd, NULL, NULL )) != STATUS_SUCCESS)
635         return io->u.Status;
636
637     io->Information = 0;
638
639     RtlEnterCriticalSection( &dir_section );
640
641     if (show_dir_symlinks == -1) init_options();
642
643     if ((cwd = open(".", O_RDONLY)) != -1 && fchdir( fd ) != -1)
644     {
645         off_t old_pos = 0;
646
647 #ifdef VFAT_IOCTL_READDIR_BOTH
648         KERNEL_DIRENT de[2];
649
650         io->u.Status = STATUS_SUCCESS;
651
652         /* Check if the VFAT ioctl is supported on this directory */
653
654         if (restart_scan) lseek( fd, 0, SEEK_SET );
655         else old_pos = lseek( fd, 0, SEEK_CUR );
656
657         if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
658         {
659             if (length < max_dir_info_size)  /* we may have to return a partial entry here */
660             {
661                 for (;;)
662                 {
663                     if (!de[0].d_reclen) break;
664                     if (de[1].d_name[0])
665                         info = append_entry( buffer, &io->Information, length,
666                                              de[1].d_name, de[0].d_name, mask );
667                     else
668                         info = append_entry( buffer, &io->Information, length,
669                                              de[0].d_name, NULL, mask );
670                     if (info)
671                     {
672                         last_info = info;
673                         if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
674                         {
675                             io->u.Status = STATUS_BUFFER_OVERFLOW;
676                             lseek( fd, old_pos, SEEK_SET );  /* restore pos to previous entry */
677                         }
678                         break;
679                     }
680                     old_pos = lseek( fd, 0, SEEK_CUR );
681                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
682                 }
683             }
684             else  /* we'll only return full entries, no need to worry about overflow */
685             {
686                 for (;;)
687                 {
688                     if (!de[0].d_reclen) break;
689                     if (de[1].d_name[0])
690                         info = append_entry( buffer, &io->Information, length,
691                                              de[1].d_name, de[0].d_name, mask );
692                     else
693                         info = append_entry( buffer, &io->Information, length,
694                                              de[0].d_name, NULL, mask );
695                     if (info)
696                     {
697                         last_info = info;
698                         if (single_entry) break;
699                         /* check if we still have enough space for the largest possible entry */
700                         if (io->Information + max_dir_info_size > length) break;
701                     }
702                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1) break;
703                 }
704             }
705         }
706         else if (errno != ENOENT)
707 #endif  /* VFAT_IOCTL_READDIR_BOTH */
708         {
709             DIR *dir;
710             struct dirent *de;
711
712             if (!(dir = opendir( "." )))
713             {
714                 io->u.Status = FILE_GetNtStatus();
715                 goto done;
716             }
717             if (!restart_scan)
718             {
719                 old_pos = lseek( fd, 0, SEEK_CUR );
720                 seekdir_wrapper( dir, old_pos );
721             }
722             io->u.Status = STATUS_SUCCESS;
723
724             if (length < max_dir_info_size)  /* we may have to return a partial entry here */
725             {
726                 while ((de = readdir( dir )))
727                 {
728                     info = append_entry( buffer, &io->Information, length,
729                                          de->d_name, NULL, mask );
730                     if (info)
731                     {
732                         last_info = info;
733                         if ((char *)info->FileName + info->FileNameLength > (char *)buffer + length)
734                             io->u.Status = STATUS_BUFFER_OVERFLOW;
735                         else
736                             old_pos = telldir_wrapper( dir, old_pos, 1 );
737                         break;
738                     }
739                     old_pos = telldir_wrapper( dir, old_pos, 1 );
740                 }
741             }
742             else  /* we'll only return full entries, no need to worry about overflow */
743             {
744                 int count = 0;
745                 while ((de = readdir( dir )))
746                 {
747                     count++;
748                     info = append_entry( buffer, &io->Information, length,
749                                          de->d_name, NULL, mask );
750                     if (info)
751                     {
752                         last_info = info;
753                         if (single_entry) break;
754                         /* check if we still have enough space for the largest possible entry */
755                         if (io->Information + max_dir_info_size > length) break;
756                     }
757                 }
758                 old_pos = telldir_wrapper( dir, old_pos, count );
759             }
760             lseek( fd, old_pos, SEEK_SET );  /* store dir offset as filepos for fd */
761             closedir( dir );
762         }
763
764         if (last_info) last_info->NextEntryOffset = 0;
765         else io->u.Status = restart_scan ? STATUS_NO_SUCH_FILE : STATUS_NO_MORE_FILES;
766
767     done:
768         if (fchdir( cwd ) == -1) chdir( "/" );
769     }
770     else io->u.Status = FILE_GetNtStatus();
771
772     RtlLeaveCriticalSection( &dir_section );
773
774     wine_server_release_fd( handle, fd );
775     if (cwd != -1) close( cwd );
776     TRACE( "=> %lx (%ld)\n", io->u.Status, io->Information );
777     return io->u.Status;
778 }
779
780
781 /***********************************************************************
782  *           find_file_in_dir
783  *
784  * Find a file in a directory the hard way, by doing a case-insensitive search.
785  * The file found is appended to unix_name at pos.
786  * There must be at least MAX_DIR_ENTRY_LEN+2 chars available at pos.
787  */
788 static NTSTATUS find_file_in_dir( char *unix_name, int pos, const WCHAR *name, int length,
789                                   int check_case )
790 {
791     WCHAR buffer[MAX_DIR_ENTRY_LEN];
792     UNICODE_STRING str;
793     BOOLEAN spaces;
794     DIR *dir;
795     struct dirent *de;
796     struct stat st;
797     int ret, used_default, is_name_8_dot_3;
798
799     /* try a shortcut for this directory */
800
801     unix_name[pos++] = '/';
802     ret = ntdll_wcstoumbs( 0, name, length, unix_name + pos, MAX_DIR_ENTRY_LEN,
803                            NULL, &used_default );
804     /* if we used the default char, the Unix name won't round trip properly back to Unicode */
805     /* so it cannot match the file we are looking for */
806     if (ret >= 0 && !used_default)
807     {
808         unix_name[pos + ret] = 0;
809         if (!stat( unix_name, &st )) return STATUS_SUCCESS;
810     }
811     if (check_case) goto not_found;  /* we want an exact match */
812
813     if (pos > 1) unix_name[pos - 1] = 0;
814     else unix_name[1] = 0;  /* keep the initial slash */
815
816     /* check if it fits in 8.3 so that we don't look for short names if we won't need them */
817
818     str.Buffer = (WCHAR *)name;
819     str.Length = length * sizeof(WCHAR);
820     str.MaximumLength = str.Length;
821     is_name_8_dot_3 = RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) && !spaces;
822
823     /* now look for it through the directory */
824
825 #ifdef VFAT_IOCTL_READDIR_BOTH
826     if (is_name_8_dot_3)
827     {
828         int fd = open( unix_name, O_RDONLY | O_DIRECTORY );
829         if (fd != -1)
830         {
831             KERNEL_DIRENT de[2];
832
833             if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) != -1)
834             {
835                 unix_name[pos - 1] = '/';
836                 for (;;)
837                 {
838                     if (!de[0].d_reclen) break;
839
840                     if (de[1].d_name[0])
841                     {
842                         ret = ntdll_umbstowcs( 0, de[1].d_name, strlen(de[1].d_name),
843                                                buffer, MAX_DIR_ENTRY_LEN );
844                         if (ret == length && !memicmpW( buffer, name, length))
845                         {
846                             strcpy( unix_name + pos, de[1].d_name );
847                             close( fd );
848                             return STATUS_SUCCESS;
849                         }
850                     }
851                     ret = ntdll_umbstowcs( 0, de[0].d_name, strlen(de[0].d_name),
852                                            buffer, MAX_DIR_ENTRY_LEN );
853                     if (ret == length && !memicmpW( buffer, name, length))
854                     {
855                         strcpy( unix_name + pos,
856                                 de[1].d_name[0] ? de[1].d_name : de[0].d_name );
857                         close( fd );
858                         return STATUS_SUCCESS;
859                     }
860                     if (ioctl( fd, VFAT_IOCTL_READDIR_BOTH, (long)de ) == -1)
861                     {
862                         close( fd );
863                         goto not_found;
864                     }
865                 }
866             }
867             close( fd );
868         }
869         /* fall through to normal handling */
870     }
871 #endif /* VFAT_IOCTL_READDIR_BOTH */
872
873     if (!(dir = opendir( unix_name )))
874     {
875         if (errno == ENOENT) return STATUS_OBJECT_PATH_NOT_FOUND;
876         else return FILE_GetNtStatus();
877     }
878     unix_name[pos - 1] = '/';
879     str.Buffer = buffer;
880     str.MaximumLength = sizeof(buffer);
881     while ((de = readdir( dir )))
882     {
883         ret = ntdll_umbstowcs( 0, de->d_name, strlen(de->d_name), buffer, MAX_DIR_ENTRY_LEN );
884         if (ret == length && !memicmpW( buffer, name, length ))
885         {
886             strcpy( unix_name + pos, de->d_name );
887             closedir( dir );
888             return STATUS_SUCCESS;
889         }
890
891         if (!is_name_8_dot_3) continue;
892
893         str.Length = ret * sizeof(WCHAR);
894         if (!RtlIsNameLegalDOS8Dot3( &str, NULL, &spaces ) || spaces)
895         {
896             WCHAR short_nameW[12];
897             ret = hash_short_file_name( &str, short_nameW );
898             if (ret == length && !memicmpW( short_nameW, name, length ))
899             {
900                 strcpy( unix_name + pos, de->d_name );
901                 closedir( dir );
902                 return STATUS_SUCCESS;
903             }
904         }
905     }
906     closedir( dir );
907     goto not_found;  /* avoid warning */
908
909 not_found:
910     unix_name[pos - 1] = 0;
911     return STATUS_OBJECT_PATH_NOT_FOUND;
912 }
913
914
915 /******************************************************************************
916  *           get_dos_device
917  *
918  * Get the Unix path of a DOS device.
919  */
920 static NTSTATUS get_dos_device( const WCHAR *name, UINT name_len, ANSI_STRING *unix_name_ret )
921 {
922     const char *config_dir = wine_get_config_dir();
923     struct stat st;
924     char *unix_name, *new_name, *dev;
925     int i, unix_len;
926
927     /* make sure the device name is ASCII */
928     for (i = 0; i < name_len; i++)
929         if (name[i] <= 32 || name[i] >= 127) return STATUS_OBJECT_NAME_NOT_FOUND;
930
931     unix_len = strlen(config_dir) + sizeof("/dosdevices/") + name_len + 1;
932
933     if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
934         return STATUS_NO_MEMORY;
935
936     strcpy( unix_name, config_dir );
937     strcat( unix_name, "/dosdevices/" );
938     dev = unix_name + strlen(unix_name);
939
940     for (i = 0; i < name_len; i++) dev[i] = (char)tolowerW(name[i]);
941     dev[i] = 0;
942
943     /* special case for drive devices */
944     if (name_len == 2 && dev[1] == ':')
945     {
946         dev[i++] = ':';
947         dev[i] = 0;
948     }
949
950     for (;;)
951     {
952         if (!stat( unix_name, &st ))
953         {
954             TRACE( "%s -> %s\n", debugstr_wn(name,name_len), debugstr_a(unix_name) );
955             unix_name_ret->Buffer = unix_name;
956             unix_name_ret->Length = strlen(unix_name);
957             unix_name_ret->MaximumLength = unix_len;
958             return STATUS_SUCCESS;
959         }
960         if (!dev) break;
961
962         /* now try some defaults for it */
963         if (!strcmp( dev, "aux" ))
964         {
965             strcpy( dev, "com1" );
966             continue;
967         }
968         if (!strcmp( dev, "prn" ))
969         {
970             strcpy( dev, "lpt1" );
971             continue;
972         }
973         if (!strcmp( dev, "nul" ))
974         {
975             strcpy( unix_name, "/dev/null" );
976             dev = NULL; /* last try */
977             continue;
978         }
979
980         new_name = NULL;
981         if (dev[1] == ':' && dev[2] == ':')  /* drive device */
982         {
983             dev[2] = 0;  /* remove last ':' to get the drive mount point symlink */
984             new_name = get_default_drive_device( unix_name );
985         }
986         else if (!strncmp( dev, "com", 3 )) new_name = get_default_com_device( dev[3] - '0' );
987         else if (!strncmp( dev, "lpt", 3 )) new_name = get_default_lpt_device( dev[3] - '0' );
988
989         if (!new_name) break;
990
991         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
992         unix_name = new_name;
993         unix_len = strlen(unix_name) + 1;
994         dev = NULL; /* last try */
995     }
996     RtlFreeHeap( GetProcessHeap(), 0, unix_name );
997     return STATUS_OBJECT_NAME_NOT_FOUND;
998 }
999
1000
1001 /* return the length of the DOS namespace prefix if any */
1002 static inline int get_dos_prefix_len( const UNICODE_STRING *name )
1003 {
1004     static const WCHAR nt_prefixW[] = {'\\','?','?','\\'};
1005     static const WCHAR dosdev_prefixW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1006
1007     if (name->Length > sizeof(nt_prefixW) &&
1008         !memcmp( name->Buffer, nt_prefixW, sizeof(nt_prefixW) ))
1009         return sizeof(nt_prefixW) / sizeof(WCHAR);
1010
1011     if (name->Length > sizeof(dosdev_prefixW) &&
1012         !memicmpW( name->Buffer, dosdev_prefixW, sizeof(dosdev_prefixW)/sizeof(WCHAR) ))
1013         return sizeof(dosdev_prefixW) / sizeof(WCHAR);
1014
1015     return 0;
1016 }
1017
1018
1019 /******************************************************************************
1020  *           wine_nt_to_unix_file_name  (NTDLL.@) Not a Windows API
1021  *
1022  * Convert a file name from NT namespace to Unix namespace.
1023  *
1024  * If disposition is not FILE_OPEN or FILE_OVERWRITTE, the last path
1025  * element doesn't have to exist; in that case STATUS_NO_SUCH_FILE is
1026  * returned, but the unix name is still filled in properly.
1027  */
1028 NTSTATUS wine_nt_to_unix_file_name( const UNICODE_STRING *nameW, ANSI_STRING *unix_name_ret,
1029                                     UINT disposition, BOOLEAN check_case )
1030 {
1031     static const WCHAR uncW[] = {'U','N','C','\\'};
1032     static const WCHAR invalid_charsW[] = { INVALID_NT_CHARS, 0 };
1033
1034     NTSTATUS status = STATUS_SUCCESS;
1035     const char *config_dir = wine_get_config_dir();
1036     const WCHAR *name, *p;
1037     struct stat st;
1038     char *unix_name;
1039     int pos, ret, name_len, unix_len, used_default;
1040
1041     name     = nameW->Buffer;
1042     name_len = nameW->Length / sizeof(WCHAR);
1043
1044     if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_PATH_SYNTAX_BAD;
1045
1046     if ((pos = get_dos_prefix_len( nameW )))
1047     {
1048         BOOLEAN is_unc = FALSE;
1049
1050         name += pos;
1051         name_len -= pos;
1052
1053         /* check for UNC prefix */
1054         if (name_len > 4 && !memicmpW( name, uncW, 4 ))
1055         {
1056             name += 3;
1057             name_len -= 3;
1058             is_unc = TRUE;
1059         }
1060         else
1061         {
1062             /* check for a drive letter with path */
1063             if (name_len < 3 || !isalphaW(name[0]) || name[1] != ':' || !IS_SEPARATOR(name[2]))
1064             {
1065                 /* not a drive with path, try other DOS devices */
1066                 return get_dos_device( name, name_len, unix_name_ret );
1067             }
1068             name += 2;  /* skip drive letter */
1069             name_len -= 2;
1070         }
1071
1072         /* check for invalid characters */
1073         for (p = name; p < name + name_len; p++)
1074             if (*p < 32 || strchrW( invalid_charsW, *p )) return STATUS_OBJECT_NAME_INVALID;
1075
1076         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1077         unix_len += MAX_DIR_ENTRY_LEN + 3;
1078         unix_len += strlen(config_dir) + sizeof("/dosdevices/") + 3;
1079         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1080             return STATUS_NO_MEMORY;
1081         strcpy( unix_name, config_dir );
1082         strcat( unix_name, "/dosdevices/" );
1083         pos = strlen(unix_name);
1084         if (is_unc)
1085         {
1086             strcpy( unix_name + pos, "unc" );
1087             pos += 3;
1088         }
1089         else
1090         {
1091             unix_name[pos++] = tolowerW( name[-2] );
1092             unix_name[pos++] = ':';
1093             unix_name[pos] = 0;
1094         }
1095     }
1096     else  /* no DOS prefix, assume NT native name, map directly to Unix */
1097     {
1098         if (!name_len || !IS_SEPARATOR(name[0])) return STATUS_OBJECT_NAME_INVALID;
1099         unix_len = ntdll_wcstoumbs( 0, name, name_len, NULL, 0, NULL, NULL );
1100         unix_len += MAX_DIR_ENTRY_LEN + 3;
1101         if (!(unix_name = RtlAllocateHeap( GetProcessHeap(), 0, unix_len )))
1102             return STATUS_NO_MEMORY;
1103         pos = 0;
1104     }
1105
1106     /* try a shortcut first */
1107
1108     ret = ntdll_wcstoumbs( 0, name, name_len, unix_name + pos, unix_len - pos - 1,
1109                            NULL, &used_default );
1110
1111     while (name_len && IS_SEPARATOR(*name))
1112     {
1113         name++;
1114         name_len--;
1115     }
1116
1117     if (ret > 0 && !used_default)  /* if we used the default char the name didn't convert properly */
1118     {
1119         char *p;
1120         unix_name[pos + ret] = 0;
1121         for (p = unix_name + pos ; *p; p++) if (*p == '\\') *p = '/';
1122         if (!stat( unix_name, &st ))
1123         {
1124             /* creation fails with STATUS_ACCESS_DENIED for the root of the drive */
1125             if (disposition == FILE_CREATE)
1126                 return name_len ? STATUS_OBJECT_NAME_COLLISION : STATUS_ACCESS_DENIED;
1127             goto done;
1128         }
1129     }
1130
1131     if (!name_len)  /* empty name -> drive root doesn't exist */
1132     {
1133         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1134         return STATUS_OBJECT_PATH_NOT_FOUND;
1135     }
1136     if (check_case && (disposition == FILE_OPEN || disposition == FILE_OVERWRITE))
1137     {
1138         RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1139         return STATUS_OBJECT_NAME_NOT_FOUND;
1140     }
1141
1142     /* now do it component by component */
1143
1144     while (name_len)
1145     {
1146         const WCHAR *end, *next;
1147
1148         end = name;
1149         while (end < name + name_len && !IS_SEPARATOR(*end)) end++;
1150         next = end;
1151         while (next < name + name_len && IS_SEPARATOR(*next)) next++;
1152         name_len -= next - name;
1153
1154         /* grow the buffer if needed */
1155
1156         if (unix_len - pos < MAX_DIR_ENTRY_LEN + 2)
1157         {
1158             char *new_name;
1159             unix_len += 2 * MAX_DIR_ENTRY_LEN;
1160             if (!(new_name = RtlReAllocateHeap( GetProcessHeap(), 0, unix_name, unix_len )))
1161             {
1162                 RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1163                 return STATUS_NO_MEMORY;
1164             }
1165             unix_name = new_name;
1166         }
1167
1168         status = find_file_in_dir( unix_name, pos, name, end - name, check_case );
1169
1170         /* if this is the last element, not finding it is not necessarily fatal */
1171         if (!name_len)
1172         {
1173             if (status == STATUS_OBJECT_PATH_NOT_FOUND)
1174             {
1175                 status = STATUS_OBJECT_NAME_NOT_FOUND;
1176                 if (disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
1177                 {
1178                     ret = ntdll_wcstoumbs( 0, name, end - name, unix_name + pos + 1,
1179                                            MAX_DIR_ENTRY_LEN, NULL, &used_default );
1180                     if (ret > 0 && !used_default)
1181                     {
1182                         unix_name[pos] = '/';
1183                         unix_name[pos + 1 + ret] = 0;
1184                         status = STATUS_NO_SUCH_FILE;
1185                         break;
1186                     }
1187                 }
1188             }
1189             else if (status == STATUS_SUCCESS && disposition == FILE_CREATE)
1190             {
1191                 status = STATUS_OBJECT_NAME_COLLISION;
1192             }
1193         }
1194
1195         if (status != STATUS_SUCCESS)
1196         {
1197             /* couldn't find it at all, fail */
1198             WARN( "%s not found in %s\n", debugstr_w(name), unix_name );
1199             RtlFreeHeap( GetProcessHeap(), 0, unix_name );
1200             return status;
1201         }
1202
1203         pos += strlen( unix_name + pos );
1204         name = next;
1205     }
1206
1207     WARN( "%s -> %s required a case-insensitive search\n",
1208           debugstr_us(nameW), debugstr_a(unix_name) );
1209
1210 done:
1211     TRACE( "%s -> %s\n", debugstr_us(nameW), debugstr_a(unix_name) );
1212     unix_name_ret->Buffer = unix_name;
1213     unix_name_ret->Length = strlen(unix_name);
1214     unix_name_ret->MaximumLength = unix_len;
1215     return status;
1216 }
1217
1218
1219 /******************************************************************
1220  *              RtlDoesFileExists_U   (NTDLL.@)
1221  */
1222 BOOLEAN WINAPI RtlDoesFileExists_U(LPCWSTR file_name)
1223 {
1224     UNICODE_STRING nt_name;
1225     ANSI_STRING unix_name;
1226     BOOLEAN ret;
1227
1228     if (!RtlDosPathNameToNtPathName_U( file_name, &nt_name, NULL, NULL )) return FALSE;
1229     ret = (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ) == STATUS_SUCCESS);
1230     if (ret) RtlFreeAnsiString( &unix_name );
1231     RtlFreeUnicodeString( &nt_name );
1232     return ret;
1233 }