dinput: Silence incorrect warning and move it to a valid place.
[wine] / dlls / kernel32 / volume.c
1 /*
2  * Volume management functions
3  *
4  * Copyright 1993 Erik Bos
5  * Copyright 1996, 2004 Alexandre Julliard
6  * Copyright 1999 Petr Tomasek
7  * Copyright 2000 Andreas Mohr
8  * Copyright 2003 Eric Pouech
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31
32 #include "ntstatus.h"
33 #define WIN32_NO_STATUS
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winnls.h"
37 #include "winternl.h"
38 #include "winioctl.h"
39 #include "ntddcdrm.h"
40 #include "ddk/mountmgr.h"
41 #include "kernel_private.h"
42 #include "wine/library.h"
43 #include "wine/unicode.h"
44 #include "wine/debug.h"
45
46 WINE_DEFAULT_DEBUG_CHANNEL(volume);
47
48 #define SUPERBLOCK_SIZE 2048
49
50 #define CDFRAMES_PERSEC         75
51 #define CDFRAMES_PERMIN         (CDFRAMES_PERSEC * 60)
52 #define FRAME_OF_ADDR(a)        ((a)[1] * CDFRAMES_PERMIN + (a)[2] * CDFRAMES_PERSEC + (a)[3])
53 #define FRAME_OF_TOC(toc, idx)  FRAME_OF_ADDR((toc)->TrackData[(idx) - (toc)->FirstTrack].Address)
54
55 #define GETWORD(buf,off)  MAKEWORD(buf[(off)],buf[(off+1)])
56 #define GETLONG(buf,off)  MAKELONG(GETWORD(buf,off),GETWORD(buf,off+2))
57
58 enum fs_type
59 {
60     FS_ERROR,    /* error accessing the device */
61     FS_UNKNOWN,  /* unknown file system */
62     FS_FAT1216,
63     FS_FAT32,
64     FS_ISO9660
65 };
66
67 static const WCHAR drive_types[][8] =
68 {
69     { 0 }, /* DRIVE_UNKNOWN */
70     { 0 }, /* DRIVE_NO_ROOT_DIR */
71     {'f','l','o','p','p','y',0}, /* DRIVE_REMOVABLE */
72     {'h','d',0}, /* DRIVE_FIXED */
73     {'n','e','t','w','o','r','k',0}, /* DRIVE_REMOTE */
74     {'c','d','r','o','m',0}, /* DRIVE_CDROM */
75     {'r','a','m','d','i','s','k',0} /* DRIVE_RAMDISK */
76 };
77
78 /* read a Unix symlink; returned buffer must be freed by caller */
79 static char *read_symlink( const char *path )
80 {
81     char *buffer;
82     int ret, size = 128;
83
84     for (;;)
85     {
86         if (!(buffer = HeapAlloc( GetProcessHeap(), 0, size )))
87         {
88             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
89             return 0;
90         }
91         ret = readlink( path, buffer, size );
92         if (ret == -1)
93         {
94             FILE_SetDosError();
95             HeapFree( GetProcessHeap(), 0, buffer );
96             return 0;
97         }
98         if (ret != size)
99         {
100             buffer[ret] = 0;
101             return buffer;
102         }
103         HeapFree( GetProcessHeap(), 0, buffer );
104         size *= 2;
105     }
106 }
107
108 /* get the path of a dos device symlink in the $WINEPREFIX/dosdevices directory */
109 static char *get_dos_device_path( LPCWSTR name )
110 {
111     const char *config_dir = wine_get_config_dir();
112     char *buffer, *dev;
113     int i;
114
115     if (!(buffer = HeapAlloc( GetProcessHeap(), 0,
116                               strlen(config_dir) + sizeof("/dosdevices/") + 5 )))
117     {
118         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
119         return NULL;
120     }
121     strcpy( buffer, config_dir );
122     strcat( buffer, "/dosdevices/" );
123     dev = buffer + strlen(buffer);
124     /* no codepage conversion, DOS device names are ASCII anyway */
125     for (i = 0; i < 5; i++)
126         if (!(dev[i] = (char)tolowerW(name[i]))) break;
127     dev[5] = 0;
128     return buffer;
129 }
130
131
132 /* open a handle to a device root */
133 static BOOL open_device_root( LPCWSTR root, HANDLE *handle )
134 {
135     static const WCHAR default_rootW[] = {'\\',0};
136     UNICODE_STRING nt_name;
137     OBJECT_ATTRIBUTES attr;
138     IO_STATUS_BLOCK io;
139     NTSTATUS status;
140
141     if (!root) root = default_rootW;
142     if (!RtlDosPathNameToNtPathName_U( root, &nt_name, NULL, NULL ))
143     {
144         SetLastError( ERROR_PATH_NOT_FOUND );
145         return FALSE;
146     }
147     attr.Length = sizeof(attr);
148     attr.RootDirectory = 0;
149     attr.Attributes = OBJ_CASE_INSENSITIVE;
150     attr.ObjectName = &nt_name;
151     attr.SecurityDescriptor = NULL;
152     attr.SecurityQualityOfService = NULL;
153
154     status = NtOpenFile( handle, 0, &attr, &io, 0,
155                          FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
156     RtlFreeUnicodeString( &nt_name );
157     if (status != STATUS_SUCCESS)
158     {
159         SetLastError( RtlNtStatusToDosError(status) );
160         return FALSE;
161     }
162     return TRUE;
163 }
164
165 /* get the label by reading it from a file at the root of the filesystem */
166 static void get_filesystem_label( const WCHAR *device, WCHAR *label, DWORD len )
167 {
168     HANDLE handle;
169     WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
170
171     labelW[0] = device[4];
172     handle = CreateFileW( labelW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
173                           OPEN_EXISTING, 0, 0 );
174     if (handle != INVALID_HANDLE_VALUE)
175     {
176         char buffer[256], *p;
177         DWORD size;
178
179         if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
180         CloseHandle( handle );
181         p = buffer + size;
182         while (p > buffer && (p[-1] == ' ' || p[-1] == '\r' || p[-1] == '\n')) p--;
183         *p = 0;
184         if (!MultiByteToWideChar( CP_UNIXCP, 0, buffer, -1, label, len ))
185             label[len-1] = 0;
186     }
187     else label[0] = 0;
188 }
189
190 /* get the serial number by reading it from a file at the root of the filesystem */
191 static DWORD get_filesystem_serial( const WCHAR *device )
192 {
193     HANDLE handle;
194     WCHAR serialW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','s','e','r','i','a','l',0};
195
196     serialW[0] = device[4];
197     handle = CreateFileW( serialW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
198                           OPEN_EXISTING, 0, 0 );
199     if (handle != INVALID_HANDLE_VALUE)
200     {
201         char buffer[32];
202         DWORD size;
203
204         if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
205         CloseHandle( handle );
206         buffer[size] = 0;
207         return strtoul( buffer, NULL, 16 );
208     }
209     else return 0;
210 }
211
212 /* fetch the type of a drive from the registry */
213 static UINT get_registry_drive_type( const WCHAR *root )
214 {
215     static const WCHAR drive_types_keyW[] = {'M','a','c','h','i','n','e','\\',
216                                              'S','o','f','t','w','a','r','e','\\',
217                                              'W','i','n','e','\\',
218                                              'D','r','i','v','e','s',0 };
219     OBJECT_ATTRIBUTES attr;
220     UNICODE_STRING nameW;
221     HANDLE hkey;
222     DWORD dummy;
223     UINT ret = DRIVE_UNKNOWN;
224     char tmp[32 + sizeof(KEY_VALUE_PARTIAL_INFORMATION)];
225     WCHAR driveW[] = {'A',':',0};
226
227     attr.Length = sizeof(attr);
228     attr.RootDirectory = 0;
229     attr.ObjectName = &nameW;
230     attr.Attributes = 0;
231     attr.SecurityDescriptor = NULL;
232     attr.SecurityQualityOfService = NULL;
233     RtlInitUnicodeString( &nameW, drive_types_keyW );
234     /* @@ Wine registry key: HKLM\Software\Wine\Drives */
235     if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr ) != STATUS_SUCCESS) return DRIVE_UNKNOWN;
236
237     if (root) driveW[0] = root[0];
238     else
239     {
240         WCHAR path[MAX_PATH];
241         GetCurrentDirectoryW( MAX_PATH, path );
242         driveW[0] = path[0];
243     }
244
245     RtlInitUnicodeString( &nameW, driveW );
246     if (!NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
247     {
248         unsigned int i;
249         WCHAR *data = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
250
251         for (i = 0; i < sizeof(drive_types)/sizeof(drive_types[0]); i++)
252         {
253             if (!strcmpiW( data, drive_types[i] ))
254             {
255                 ret = i;
256                 break;
257             }
258         }
259     }
260     NtClose( hkey );
261     return ret;
262 }
263
264
265 /******************************************************************
266  *              VOLUME_FindCdRomDataBestVoldesc
267  */
268 static DWORD VOLUME_FindCdRomDataBestVoldesc( HANDLE handle )
269 {
270     BYTE cur_vd_type, max_vd_type = 0;
271     BYTE buffer[0x800];
272     DWORD size, offs, best_offs = 0, extra_offs = 0;
273
274     for (offs = 0x8000; offs <= 0x9800; offs += 0x800)
275     {
276         /* if 'CDROM' occurs at position 8, this is a pre-iso9660 cd, and
277          * the volume label is displaced forward by 8
278          */
279         if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs) break;
280         if (!ReadFile( handle, buffer, sizeof(buffer), &size, NULL )) break;
281         if (size != sizeof(buffer)) break;
282         /* check for non-ISO9660 signature */
283         if (!memcmp( buffer + 11, "ROM", 3 )) extra_offs = 8;
284         cur_vd_type = buffer[extra_offs];
285         if (cur_vd_type == 0xff) /* voldesc set terminator */
286             break;
287         if (cur_vd_type > max_vd_type)
288         {
289             max_vd_type = cur_vd_type;
290             best_offs = offs + extra_offs;
291         }
292     }
293     return best_offs;
294 }
295
296
297 /***********************************************************************
298  *           VOLUME_ReadFATSuperblock
299  */
300 static enum fs_type VOLUME_ReadFATSuperblock( HANDLE handle, BYTE *buff )
301 {
302     DWORD size;
303
304     /* try a fixed disk, with a FAT partition */
305     if (SetFilePointer( handle, 0, NULL, FILE_BEGIN ) != 0 ||
306         !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ))
307         return FS_ERROR;
308
309     if (size < SUPERBLOCK_SIZE) return FS_UNKNOWN;
310
311     /* FIXME: do really all FAT have their name beginning with
312      * "FAT" ? (At least FAT12, FAT16 and FAT32 have :)
313      */
314     if (!memcmp(buff+0x36, "FAT", 3) || !memcmp(buff+0x52, "FAT", 3))
315     {
316         /* guess which type of FAT we have */
317         int reasonable;
318         unsigned int sectors,
319                      sect_per_fat,
320                      total_sectors,
321                      num_boot_sectors,
322                      num_fats,
323                      num_root_dir_ents,
324                      bytes_per_sector,
325                      sectors_per_cluster,
326                      nclust;
327         sect_per_fat = GETWORD(buff, 0x16);
328         if (!sect_per_fat) sect_per_fat = GETLONG(buff, 0x24);
329         total_sectors = GETWORD(buff, 0x13);
330         if (!total_sectors)
331             total_sectors = GETLONG(buff, 0x20);
332         num_boot_sectors = GETWORD(buff, 0x0e);
333         num_fats =  buff[0x10];
334         num_root_dir_ents = GETWORD(buff, 0x11);
335         bytes_per_sector = GETWORD(buff, 0x0b);
336         sectors_per_cluster = buff[0x0d];
337         /* check if the parameters are reasonable and will not cause
338          * arithmetic errors in the calculation */
339         reasonable = num_boot_sectors < 16 &&
340                      num_fats < 16 &&
341                      bytes_per_sector >= 512 && bytes_per_sector % 512 == 0 &&
342                      sectors_per_cluster > 1;
343         if (!reasonable) return FS_UNKNOWN;
344         sectors =  total_sectors - num_boot_sectors - num_fats * sect_per_fat -
345             (num_root_dir_ents * 32 + bytes_per_sector - 1) / bytes_per_sector;
346         nclust = sectors / sectors_per_cluster;
347         if ((buff[0x42] == 0x28 || buff[0x42] == 0x29) &&
348                 !memcmp(buff+0x52, "FAT", 3)) return FS_FAT32;
349         if (nclust < 65525)
350         {
351             if ((buff[0x26] == 0x28 || buff[0x26] == 0x29) &&
352                     !memcmp(buff+0x36, "FAT", 3))
353                 return FS_FAT1216;
354         }
355     }
356     return FS_UNKNOWN;
357 }
358
359
360 /***********************************************************************
361  *           VOLUME_ReadCDSuperblock
362  */
363 static enum fs_type VOLUME_ReadCDSuperblock( HANDLE handle, BYTE *buff )
364 {
365     DWORD size, offs = VOLUME_FindCdRomDataBestVoldesc( handle );
366
367     if (!offs) return FS_UNKNOWN;
368
369     if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs ||
370         !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ) ||
371         size != SUPERBLOCK_SIZE)
372         return FS_ERROR;
373
374     /* check for iso9660 present */
375     if (!memcmp(&buff[1], "CD001", 5)) return FS_ISO9660;
376     return FS_UNKNOWN;
377 }
378
379
380 /**************************************************************************
381  *                              VOLUME_GetSuperblockLabel
382  */
383 static void VOLUME_GetSuperblockLabel( const WCHAR *device, enum fs_type type, const BYTE *superblock,
384                                        WCHAR *label, DWORD len )
385 {
386     const BYTE *label_ptr = NULL;
387     DWORD label_len;
388
389     switch(type)
390     {
391     case FS_ERROR:
392         label_len = 0;
393         break;
394     case FS_UNKNOWN:
395         get_filesystem_label( device, label, len );
396         return;
397     case FS_FAT1216:
398         label_ptr = superblock + 0x2b;
399         label_len = 11;
400         break;
401     case FS_FAT32:
402         label_ptr = superblock + 0x47;
403         label_len = 11;
404         break;
405     case FS_ISO9660:
406         {
407             BYTE ver = superblock[0x5a];
408
409             if (superblock[0x58] == 0x25 && superblock[0x59] == 0x2f &&  /* Unicode ID */
410                 ((ver == 0x40) || (ver == 0x43) || (ver == 0x45)))
411             { /* yippee, unicode */
412                 unsigned int i;
413
414                 if (len > 17) len = 17;
415                 for (i = 0; i < len-1; i++)
416                     label[i] = (superblock[40+2*i] << 8) | superblock[41+2*i];
417                 label[i] = 0;
418                 while (i && label[i-1] == ' ') label[--i] = 0;
419                 return;
420             }
421             label_ptr = superblock + 40;
422             label_len = 32;
423             break;
424         }
425     }
426     if (label_len) RtlMultiByteToUnicodeN( label, (len-1) * sizeof(WCHAR),
427                                            &label_len, (LPCSTR)label_ptr, label_len );
428     label_len /= sizeof(WCHAR);
429     label[label_len] = 0;
430     while (label_len && label[label_len-1] == ' ') label[--label_len] = 0;
431 }
432
433
434 /**************************************************************************
435  *                              VOLUME_GetSuperblockSerial
436  */
437 static DWORD VOLUME_GetSuperblockSerial( const WCHAR *device, enum fs_type type, const BYTE *superblock )
438 {
439     switch(type)
440     {
441     case FS_ERROR:
442         break;
443     case FS_UNKNOWN:
444         return get_filesystem_serial( device );
445     case FS_FAT1216:
446         return GETLONG( superblock, 0x27 );
447     case FS_FAT32:
448         return GETLONG( superblock, 0x33 );
449     case FS_ISO9660:
450         {
451             BYTE sum[4];
452             int i;
453
454             sum[0] = sum[1] = sum[2] = sum[3] = 0;
455             for (i = 0; i < 2048; i += 4)
456             {
457                 /* DON'T optimize this into DWORD !! (breaks overflow) */
458                 sum[0] += superblock[i+0];
459                 sum[1] += superblock[i+1];
460                 sum[2] += superblock[i+2];
461                 sum[3] += superblock[i+3];
462             }
463             /*
464              * OK, another braindead one... argh. Just believe it.
465              * Me$$ysoft chose to reverse the serial number in NT4/W2K.
466              * It's true and nobody will ever be able to change it.
467              */
468             if (GetVersion() & 0x80000000)
469                 return (sum[3] << 24) | (sum[2] << 16) | (sum[1] << 8) | sum[0];
470             else
471                 return (sum[0] << 24) | (sum[1] << 16) | (sum[2] << 8) | sum[3];
472         }
473     }
474     return 0;
475 }
476
477
478 /**************************************************************************
479  *                              VOLUME_GetAudioCDSerial
480  */
481 static DWORD VOLUME_GetAudioCDSerial( const CDROM_TOC *toc )
482 {
483     DWORD serial = 0;
484     int i;
485
486     for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++)
487         serial += ((toc->TrackData[i].Address[1] << 16) |
488                    (toc->TrackData[i].Address[2] << 8) |
489                    toc->TrackData[i].Address[3]);
490
491     /*
492      * dwStart, dwEnd collect the beginning and end of the disc respectively, in
493      * frames.
494      * There it is collected for correcting the serial when there are less than
495      * 3 tracks.
496      */
497     if (toc->LastTrack - toc->FirstTrack + 1 < 3)
498     {
499         DWORD dwStart = FRAME_OF_TOC(toc, toc->FirstTrack);
500         DWORD dwEnd = FRAME_OF_TOC(toc, toc->LastTrack + 1);
501         serial += dwEnd - dwStart;
502     }
503     return serial;
504 }
505
506
507 /***********************************************************************
508  *           GetVolumeInformationW   (KERNEL32.@)
509  */
510 BOOL WINAPI GetVolumeInformationW( LPCWSTR root, LPWSTR label, DWORD label_len,
511                                    DWORD *serial, DWORD *filename_len, DWORD *flags,
512                                    LPWSTR fsname, DWORD fsname_len )
513 {
514     static const WCHAR audiocdW[] = {'A','u','d','i','o',' ','C','D',0};
515     static const WCHAR fatW[] = {'F','A','T',0};
516     static const WCHAR ntfsW[] = {'N','T','F','S',0};
517     static const WCHAR cdfsW[] = {'C','D','F','S',0};
518
519     WCHAR device[] = {'\\','\\','.','\\','A',':',0};
520     HANDLE handle;
521     enum fs_type type = FS_UNKNOWN;
522
523     if (!root)
524     {
525         WCHAR path[MAX_PATH];
526         GetCurrentDirectoryW( MAX_PATH, path );
527         device[4] = path[0];
528     }
529     else
530     {
531         if (!root[0] || root[1] != ':')
532         {
533             SetLastError( ERROR_INVALID_NAME );
534             return FALSE;
535         }
536         device[4] = root[0];
537     }
538
539     /* try to open the device */
540
541     handle = CreateFileW( device, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
542                           NULL, OPEN_EXISTING, 0, 0 );
543     if (handle != INVALID_HANDLE_VALUE)
544     {
545         BYTE superblock[SUPERBLOCK_SIZE];
546         CDROM_TOC toc;
547         DWORD br;
548
549         /* check for audio CD */
550         /* FIXME: we only check the first track for now */
551         if (DeviceIoControl( handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, 0 ))
552         {
553             if (!(toc.TrackData[0].Control & 0x04))  /* audio track */
554             {
555                 TRACE( "%s: found audio CD\n", debugstr_w(device) );
556                 if (label) lstrcpynW( label, audiocdW, label_len );
557                 if (serial) *serial = VOLUME_GetAudioCDSerial( &toc );
558                 CloseHandle( handle );
559                 type = FS_ISO9660;
560                 goto fill_fs_info;
561             }
562             type = VOLUME_ReadCDSuperblock( handle, superblock );
563         }
564         else
565         {
566             type = VOLUME_ReadFATSuperblock( handle, superblock );
567             if (type == FS_UNKNOWN) type = VOLUME_ReadCDSuperblock( handle, superblock );
568         }
569         CloseHandle( handle );
570         TRACE( "%s: found fs type %d\n", debugstr_w(device), type );
571         if (type == FS_ERROR) return FALSE;
572
573         if (label && label_len) VOLUME_GetSuperblockLabel( device, type, superblock, label, label_len );
574         if (serial) *serial = VOLUME_GetSuperblockSerial( device, type, superblock );
575         goto fill_fs_info;
576     }
577     else TRACE( "cannot open device %s: err %d\n", debugstr_w(device), GetLastError() );
578
579     /* we couldn't open the device, fallback to default strategy */
580
581     switch(GetDriveTypeW( root ))
582     {
583     case DRIVE_UNKNOWN:
584     case DRIVE_NO_ROOT_DIR:
585         SetLastError( ERROR_NOT_READY );
586         return FALSE;
587     case DRIVE_REMOVABLE:
588     case DRIVE_FIXED:
589     case DRIVE_REMOTE:
590     case DRIVE_RAMDISK:
591         type = FS_UNKNOWN;
592         break;
593     case DRIVE_CDROM:
594         type = FS_ISO9660;
595         break;
596     }
597
598     if (label && label_len) get_filesystem_label( device, label, label_len );
599     if (serial) *serial = get_filesystem_serial( device );
600
601 fill_fs_info:  /* now fill in the information that depends on the file system type */
602
603     switch(type)
604     {
605     case FS_ISO9660:
606         if (fsname) lstrcpynW( fsname, cdfsW, fsname_len );
607         if (filename_len) *filename_len = 221;
608         if (flags) *flags = FILE_READ_ONLY_VOLUME;
609         break;
610     case FS_FAT1216:
611     case FS_FAT32:
612         if (fsname) lstrcpynW( fsname, fatW, fsname_len );
613         if (filename_len) *filename_len = 255;
614         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;  /* FIXME */
615         break;
616     default:
617         if (fsname) lstrcpynW( fsname, ntfsW, fsname_len );
618         if (filename_len) *filename_len = 255;
619         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;
620         break;
621     }
622     return TRUE;
623 }
624
625
626 /***********************************************************************
627  *           GetVolumeInformationA   (KERNEL32.@)
628  */
629 BOOL WINAPI GetVolumeInformationA( LPCSTR root, LPSTR label,
630                                    DWORD label_len, DWORD *serial,
631                                    DWORD *filename_len, DWORD *flags,
632                                    LPSTR fsname, DWORD fsname_len )
633 {
634     WCHAR *rootW = NULL;
635     LPWSTR labelW, fsnameW;
636     BOOL ret;
637
638     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
639
640     labelW = label ? HeapAlloc(GetProcessHeap(), 0, label_len * sizeof(WCHAR)) : NULL;
641     fsnameW = fsname ? HeapAlloc(GetProcessHeap(), 0, fsname_len * sizeof(WCHAR)) : NULL;
642
643     if ((ret = GetVolumeInformationW(rootW, labelW, label_len, serial,
644                                     filename_len, flags, fsnameW, fsname_len)))
645     {
646         if (label) FILE_name_WtoA( labelW, -1, label, label_len );
647         if (fsname) FILE_name_WtoA( fsnameW, -1, fsname, fsname_len );
648     }
649
650     HeapFree( GetProcessHeap(), 0, labelW );
651     HeapFree( GetProcessHeap(), 0, fsnameW );
652     return ret;
653 }
654
655
656
657 /***********************************************************************
658  *           SetVolumeLabelW   (KERNEL32.@)
659  */
660 BOOL WINAPI SetVolumeLabelW( LPCWSTR root, LPCWSTR label )
661 {
662     WCHAR device[] = {'\\','\\','.','\\','A',':',0};
663     HANDLE handle;
664     enum fs_type type = FS_UNKNOWN;
665
666     if (!root)
667     {
668         WCHAR path[MAX_PATH];
669         GetCurrentDirectoryW( MAX_PATH, path );
670         device[4] = path[0];
671     }
672     else
673     {
674         if (!root[0] || root[1] != ':')
675         {
676             SetLastError( ERROR_INVALID_NAME );
677             return FALSE;
678         }
679         device[4] = root[0];
680     }
681
682     /* try to open the device */
683
684     handle = CreateFileW( device, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
685                           NULL, OPEN_EXISTING, 0, 0 );
686     if (handle != INVALID_HANDLE_VALUE)
687     {
688         BYTE superblock[SUPERBLOCK_SIZE];
689
690         type = VOLUME_ReadFATSuperblock( handle, superblock );
691         if (type == FS_UNKNOWN) type = VOLUME_ReadCDSuperblock( handle, superblock );
692         CloseHandle( handle );
693         if (type != FS_UNKNOWN)
694         {
695             /* we can't set the label on FAT or CDROM file systems */
696             TRACE( "cannot set label on device %s type %d\n", debugstr_w(device), type );
697             SetLastError( ERROR_ACCESS_DENIED );
698             return FALSE;
699         }
700     }
701     else
702     {
703         TRACE( "cannot open device %s: err %d\n", debugstr_w(device), GetLastError() );
704         if (GetLastError() == ERROR_ACCESS_DENIED) return FALSE;
705     }
706
707     /* we couldn't open the device, fallback to default strategy */
708
709     switch(GetDriveTypeW( root ))
710     {
711     case DRIVE_UNKNOWN:
712     case DRIVE_NO_ROOT_DIR:
713         SetLastError( ERROR_NOT_READY );
714         break;
715     case DRIVE_REMOVABLE:
716     case DRIVE_FIXED:
717         {
718             WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
719
720             labelW[0] = device[4];
721             handle = CreateFileW( labelW, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
722                                   CREATE_ALWAYS, 0, 0 );
723             if (handle != INVALID_HANDLE_VALUE)
724             {
725                 char buffer[64];
726                 DWORD size;
727
728                 if (!WideCharToMultiByte( CP_UNIXCP, 0, label, -1, buffer, sizeof(buffer), NULL, NULL ))
729                     buffer[sizeof(buffer)-1] = 0;
730                 WriteFile( handle, buffer, strlen(buffer), &size, NULL );
731                 CloseHandle( handle );
732                 return TRUE;
733             }
734             break;
735         }
736     case DRIVE_REMOTE:
737     case DRIVE_RAMDISK:
738     case DRIVE_CDROM:
739         SetLastError( ERROR_ACCESS_DENIED );
740         break;
741     }
742     return FALSE;
743 }
744
745 /***********************************************************************
746  *           SetVolumeLabelA   (KERNEL32.@)
747  */
748 BOOL WINAPI SetVolumeLabelA(LPCSTR root, LPCSTR volname)
749 {
750     WCHAR *rootW = NULL, *volnameW = NULL;
751     BOOL ret;
752
753     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
754     if (volname && !(volnameW = FILE_name_AtoW( volname, TRUE ))) return FALSE;
755     ret = SetVolumeLabelW( rootW, volnameW );
756     HeapFree( GetProcessHeap(), 0, volnameW );
757     return ret;
758 }
759
760
761 /***********************************************************************
762  *           GetVolumeNameForVolumeMountPointA   (KERNEL32.@)
763  */
764 BOOL WINAPI GetVolumeNameForVolumeMountPointA( LPCSTR path, LPSTR volume, DWORD size )
765 {
766     BOOL ret;
767     WCHAR volumeW[50], *pathW = NULL;
768     DWORD len = min( sizeof(volumeW) / sizeof(WCHAR), size );
769
770     TRACE("(%s, %p, %x)\n", debugstr_a(path), volume, size);
771
772     if (!path || !(pathW = FILE_name_AtoW( path, TRUE )))
773         return FALSE;
774
775     if ((ret = GetVolumeNameForVolumeMountPointW( pathW, volumeW, len )))
776         FILE_name_WtoA( volumeW, -1, volume, len );
777
778     HeapFree( GetProcessHeap(), 0, pathW );
779     return ret;
780 }
781
782 /***********************************************************************
783  *           GetVolumeNameForVolumeMountPointW   (KERNEL32.@)
784  */
785 BOOL WINAPI GetVolumeNameForVolumeMountPointW( LPCWSTR path, LPWSTR volume, DWORD size )
786 {
787     BOOL ret = FALSE;
788     static const WCHAR fmt[] =
789         { '\\','\\','?','\\','V','o','l','u','m','e','{','%','0','2','x','}','\\',0 };
790
791     TRACE("(%s, %p, %x)\n", debugstr_w(path), volume, size);
792
793     if (!path || !path[0]) return FALSE;
794
795     if (size >= sizeof(fmt) / sizeof(WCHAR))
796     {
797         /* FIXME: will break when we support volume mounts */
798         sprintfW( volume, fmt, tolowerW( path[0] ) - 'a' );
799         ret = TRUE;
800     }
801     return ret;
802 }
803
804 /***********************************************************************
805  *           DefineDosDeviceW       (KERNEL32.@)
806  */
807 BOOL WINAPI DefineDosDeviceW( DWORD flags, LPCWSTR devname, LPCWSTR targetpath )
808 {
809     DWORD len, dosdev;
810     BOOL ret = FALSE;
811     char *path = NULL, *target, *p;
812
813     TRACE("%x, %s, %s\n", flags, debugstr_w(devname), debugstr_w(targetpath));
814
815     if (!(flags & DDD_REMOVE_DEFINITION))
816     {
817         if (!(flags & DDD_RAW_TARGET_PATH))
818         {
819             FIXME( "(0x%08x,%s,%s) DDD_RAW_TARGET_PATH flag not set, not supported yet\n",
820                    flags, debugstr_w(devname), debugstr_w(targetpath) );
821             SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
822             return FALSE;
823         }
824
825         len = WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, NULL, 0, NULL, NULL );
826         if ((target = HeapAlloc( GetProcessHeap(), 0, len )))
827         {
828             WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, target, len, NULL, NULL );
829             for (p = target; *p; p++) if (*p == '\\') *p = '/';
830         }
831         else
832         {
833             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
834             return FALSE;
835         }
836     }
837     else target = NULL;
838
839     /* first check for a DOS device */
840
841     if ((dosdev = RtlIsDosDeviceName_U( devname )))
842     {
843         WCHAR name[5];
844
845         memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
846         name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
847         path = get_dos_device_path( name );
848     }
849     else if (isalphaW(devname[0]) && devname[1] == ':' && !devname[2])  /* drive mapping */
850     {
851         path = get_dos_device_path( devname );
852     }
853     else SetLastError( ERROR_FILE_NOT_FOUND );
854
855     if (path)
856     {
857         if (target)
858         {
859             TRACE( "creating symlink %s -> %s\n", path, target );
860             unlink( path );
861             if (!symlink( target, path )) ret = TRUE;
862             else FILE_SetDosError();
863         }
864         else
865         {
866             TRACE( "removing symlink %s\n", path );
867             if (!unlink( path )) ret = TRUE;
868             else FILE_SetDosError();
869         }
870         HeapFree( GetProcessHeap(), 0, path );
871     }
872     HeapFree( GetProcessHeap(), 0, target );
873     return ret;
874 }
875
876
877 /***********************************************************************
878  *           DefineDosDeviceA       (KERNEL32.@)
879  */
880 BOOL WINAPI DefineDosDeviceA(DWORD flags, LPCSTR devname, LPCSTR targetpath)
881 {
882     WCHAR *devW, *targetW = NULL;
883     BOOL ret;
884
885     if (!(devW = FILE_name_AtoW( devname, FALSE ))) return FALSE;
886     if (targetpath && !(targetW = FILE_name_AtoW( targetpath, TRUE ))) return FALSE;
887     ret = DefineDosDeviceW(flags, devW, targetW);
888     HeapFree( GetProcessHeap(), 0, targetW );
889     return ret;
890 }
891
892
893 /***********************************************************************
894  *           QueryDosDeviceW   (KERNEL32.@)
895  *
896  * returns array of strings terminated by \0, terminated by \0
897  */
898 DWORD WINAPI QueryDosDeviceW( LPCWSTR devname, LPWSTR target, DWORD bufsize )
899 {
900     static const WCHAR auxW[] = {'A','U','X',0};
901     static const WCHAR nulW[] = {'N','U','L',0};
902     static const WCHAR prnW[] = {'P','R','N',0};
903     static const WCHAR comW[] = {'C','O','M',0};
904     static const WCHAR lptW[] = {'L','P','T',0};
905     static const WCHAR rootW[] = {'A',':','\\',0};
906     static const WCHAR com0W[] = {'\\','?','?','\\','C','O','M','0',0};
907     static const WCHAR com1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','C','O','M','1',0,0};
908     static const WCHAR lpt1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','L','P','T','1',0,0};
909
910     UNICODE_STRING nt_name;
911     ANSI_STRING unix_name;
912     WCHAR nt_buffer[10];
913     NTSTATUS status;
914
915     if (!bufsize)
916     {
917         SetLastError( ERROR_INSUFFICIENT_BUFFER );
918         return 0;
919     }
920
921     if (devname)
922     {
923         WCHAR *p, name[5];
924         char *path, *link;
925         DWORD dosdev, ret = 0;
926
927         if ((dosdev = RtlIsDosDeviceName_U( devname )))
928         {
929             memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
930             name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
931         }
932         else if (devname[0] && devname[1] == ':' && !devname[2])
933         {
934             memcpy( name, devname, 3 * sizeof(WCHAR) );
935         }
936         else
937         {
938             SetLastError( ERROR_BAD_PATHNAME );
939             return 0;
940         }
941
942         if (!(path = get_dos_device_path( name ))) return 0;
943         link = read_symlink( path );
944         HeapFree( GetProcessHeap(), 0, path );
945
946         if (link)
947         {
948             ret = MultiByteToWideChar( CP_UNIXCP, 0, link, -1, target, bufsize );
949             HeapFree( GetProcessHeap(), 0, link );
950         }
951         else if (dosdev)  /* look for device defaults */
952         {
953             if (!strcmpiW( name, auxW ))
954             {
955                 if (bufsize >= sizeof(com1W)/sizeof(WCHAR))
956                 {
957                     memcpy( target, com1W, sizeof(com1W) );
958                     ret = sizeof(com1W)/sizeof(WCHAR);
959                 }
960                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
961                 return ret;
962             }
963             if (!strcmpiW( name, prnW ))
964             {
965                 if (bufsize >= sizeof(lpt1W)/sizeof(WCHAR))
966                 {
967                     memcpy( target, lpt1W, sizeof(lpt1W) );
968                     ret = sizeof(lpt1W)/sizeof(WCHAR);
969                 }
970                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
971                 return ret;
972             }
973
974             nt_buffer[0] = '\\';
975             nt_buffer[1] = '?';
976             nt_buffer[2] = '?';
977             nt_buffer[3] = '\\';
978             strcpyW( nt_buffer + 4, name );
979             RtlInitUnicodeString( &nt_name, nt_buffer );
980             status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE );
981             if (status) SetLastError( RtlNtStatusToDosError(status) );
982             else
983             {
984                 ret = MultiByteToWideChar( CP_UNIXCP, 0, unix_name.Buffer, -1, target, bufsize );
985                 RtlFreeAnsiString( &unix_name );
986             }
987         }
988
989         if (ret)
990         {
991             if (ret < bufsize) target[ret++] = 0;  /* add an extra null */
992             for (p = target; *p; p++) if (*p == '/') *p = '\\';
993         }
994
995         return ret;
996     }
997     else  /* return a list of all devices */
998     {
999         WCHAR *p = target;
1000         int i;
1001
1002         if (bufsize <= (sizeof(auxW)+sizeof(nulW)+sizeof(prnW))/sizeof(WCHAR))
1003         {
1004             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1005             return 0;
1006         }
1007
1008         memcpy( p, auxW, sizeof(auxW) );
1009         p += sizeof(auxW) / sizeof(WCHAR);
1010         memcpy( p, nulW, sizeof(nulW) );
1011         p += sizeof(nulW) / sizeof(WCHAR);
1012         memcpy( p, prnW, sizeof(prnW) );
1013         p += sizeof(prnW) / sizeof(WCHAR);
1014
1015         strcpyW( nt_buffer, com0W );
1016         RtlInitUnicodeString( &nt_name, nt_buffer );
1017
1018         for (i = 1; i <= 9; i++)
1019         {
1020             nt_buffer[7] = '0' + i;
1021             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1022             {
1023                 RtlFreeAnsiString( &unix_name );
1024                 if (p + 5 >= target + bufsize)
1025                 {
1026                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1027                     return 0;
1028                 }
1029                 strcpyW( p, comW );
1030                 p[3] = '0' + i;
1031                 p[4] = 0;
1032                 p += 5;
1033             }
1034         }
1035         strcpyW( nt_buffer + 4, lptW );
1036         for (i = 1; i <= 9; i++)
1037         {
1038             nt_buffer[7] = '0' + i;
1039             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1040             {
1041                 RtlFreeAnsiString( &unix_name );
1042                 if (p + 5 >= target + bufsize)
1043                 {
1044                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1045                     return 0;
1046                 }
1047                 strcpyW( p, lptW );
1048                 p[3] = '0' + i;
1049                 p[4] = 0;
1050                 p += 5;
1051             }
1052         }
1053
1054         strcpyW( nt_buffer + 4, rootW );
1055         RtlInitUnicodeString( &nt_name, nt_buffer );
1056
1057         for (i = 0; i < 26; i++)
1058         {
1059             nt_buffer[4] = 'a' + i;
1060             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1061             {
1062                 RtlFreeAnsiString( &unix_name );
1063                 if (p + 3 >= target + bufsize)
1064                 {
1065                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1066                     return 0;
1067                 }
1068                 *p++ = 'A' + i;
1069                 *p++ = ':';
1070                 *p++ = 0;
1071             }
1072         }
1073         *p++ = 0;  /* terminating null */
1074         return p - target;
1075     }
1076 }
1077
1078
1079 /***********************************************************************
1080  *           QueryDosDeviceA   (KERNEL32.@)
1081  *
1082  * returns array of strings terminated by \0, terminated by \0
1083  */
1084 DWORD WINAPI QueryDosDeviceA( LPCSTR devname, LPSTR target, DWORD bufsize )
1085 {
1086     DWORD ret = 0, retW;
1087     WCHAR *devnameW = NULL;
1088     LPWSTR targetW;
1089
1090     if (devname && !(devnameW = FILE_name_AtoW( devname, FALSE ))) return 0;
1091
1092     targetW = HeapAlloc( GetProcessHeap(),0, bufsize * sizeof(WCHAR) );
1093     if (!targetW)
1094     {
1095         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1096         return 0;
1097     }
1098
1099     retW = QueryDosDeviceW(devnameW, targetW, bufsize);
1100
1101     ret = FILE_name_WtoA( targetW, retW, target, bufsize );
1102
1103     HeapFree(GetProcessHeap(), 0, targetW);
1104     return ret;
1105 }
1106
1107
1108 /***********************************************************************
1109  *           GetLogicalDrives   (KERNEL32.@)
1110  */
1111 DWORD WINAPI GetLogicalDrives(void)
1112 {
1113     const char *config_dir = wine_get_config_dir();
1114     struct stat st;
1115     char *buffer, *dev;
1116     DWORD ret = 0;
1117     int i;
1118
1119     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") )))
1120     {
1121         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1122         return 0;
1123     }
1124     strcpy( buffer, config_dir );
1125     strcat( buffer, "/dosdevices/a:" );
1126     dev = buffer + strlen(buffer) - 2;
1127
1128     for (i = 0; i < 26; i++)
1129     {
1130         *dev = 'a' + i;
1131         if (!stat( buffer, &st )) ret |= (1 << i);
1132     }
1133     HeapFree( GetProcessHeap(), 0, buffer );
1134     return ret;
1135 }
1136
1137
1138 /***********************************************************************
1139  *           GetLogicalDriveStringsA   (KERNEL32.@)
1140  */
1141 UINT WINAPI GetLogicalDriveStringsA( UINT len, LPSTR buffer )
1142 {
1143     DWORD drives = GetLogicalDrives();
1144     UINT drive, count;
1145
1146     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1147     if ((count * 4) + 1 > len) return count * 4 + 1;
1148
1149     for (drive = 0; drive < 26; drive++)
1150     {
1151         if (drives & (1 << drive))
1152         {
1153             *buffer++ = 'a' + drive;
1154             *buffer++ = ':';
1155             *buffer++ = '\\';
1156             *buffer++ = 0;
1157         }
1158     }
1159     *buffer = 0;
1160     return count * 4;
1161 }
1162
1163
1164 /***********************************************************************
1165  *           GetLogicalDriveStringsW   (KERNEL32.@)
1166  */
1167 UINT WINAPI GetLogicalDriveStringsW( UINT len, LPWSTR buffer )
1168 {
1169     DWORD drives = GetLogicalDrives();
1170     UINT drive, count;
1171
1172     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1173     if ((count * 4) + 1 > len) return count * 4 + 1;
1174
1175     for (drive = 0; drive < 26; drive++)
1176     {
1177         if (drives & (1 << drive))
1178         {
1179             *buffer++ = 'a' + drive;
1180             *buffer++ = ':';
1181             *buffer++ = '\\';
1182             *buffer++ = 0;
1183         }
1184     }
1185     *buffer = 0;
1186     return count * 4;
1187 }
1188
1189
1190 /***********************************************************************
1191  *           GetDriveTypeW   (KERNEL32.@)
1192  *
1193  * Returns the type of the disk drive specified. If root is NULL the
1194  * root of the current directory is used.
1195  *
1196  * RETURNS
1197  *
1198  *  Type of drive (from Win32 SDK):
1199  *
1200  *   DRIVE_UNKNOWN     unable to find out anything about the drive
1201  *   DRIVE_NO_ROOT_DIR nonexistent root dir
1202  *   DRIVE_REMOVABLE   the disk can be removed from the machine
1203  *   DRIVE_FIXED       the disk cannot be removed from the machine
1204  *   DRIVE_REMOTE      network disk
1205  *   DRIVE_CDROM       CDROM drive
1206  *   DRIVE_RAMDISK     virtual disk in RAM
1207  */
1208 UINT WINAPI GetDriveTypeW(LPCWSTR root) /* [in] String describing drive */
1209 {
1210     FILE_FS_DEVICE_INFORMATION info;
1211     IO_STATUS_BLOCK io;
1212     NTSTATUS status;
1213     HANDLE handle;
1214     UINT ret;
1215
1216     if (!open_device_root( root, &handle )) return DRIVE_NO_ROOT_DIR;
1217
1218     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsDeviceInformation );
1219     NtClose( handle );
1220     if (status != STATUS_SUCCESS)
1221     {
1222         SetLastError( RtlNtStatusToDosError(status) );
1223         ret = DRIVE_UNKNOWN;
1224     }
1225     else if ((ret = get_registry_drive_type( root )) == DRIVE_UNKNOWN)
1226     {
1227         switch (info.DeviceType)
1228         {
1229         case FILE_DEVICE_CD_ROM_FILE_SYSTEM:  ret = DRIVE_CDROM; break;
1230         case FILE_DEVICE_VIRTUAL_DISK:        ret = DRIVE_RAMDISK; break;
1231         case FILE_DEVICE_NETWORK_FILE_SYSTEM: ret = DRIVE_REMOTE; break;
1232         case FILE_DEVICE_DISK_FILE_SYSTEM:
1233             if (info.Characteristics & FILE_REMOTE_DEVICE) ret = DRIVE_REMOTE;
1234             else if (info.Characteristics & FILE_REMOVABLE_MEDIA) ret = DRIVE_REMOVABLE;
1235             else ret = DRIVE_FIXED;
1236             break;
1237         default:
1238             ret = DRIVE_UNKNOWN;
1239             break;
1240         }
1241     }
1242     TRACE( "%s -> %d\n", debugstr_w(root), ret );
1243     return ret;
1244 }
1245
1246
1247 /***********************************************************************
1248  *           GetDriveTypeA   (KERNEL32.@)
1249  *
1250  * See GetDriveTypeW.
1251  */
1252 UINT WINAPI GetDriveTypeA( LPCSTR root )
1253 {
1254     WCHAR *rootW = NULL;
1255
1256     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return DRIVE_NO_ROOT_DIR;
1257     return GetDriveTypeW( rootW );
1258 }
1259
1260
1261 /***********************************************************************
1262  *           GetDiskFreeSpaceExW   (KERNEL32.@)
1263  *
1264  *  This function is used to acquire the size of the available and
1265  *  total space on a logical volume.
1266  *
1267  * RETURNS
1268  *
1269  *  Zero on failure, nonzero upon success. Use GetLastError to obtain
1270  *  detailed error information.
1271  *
1272  */
1273 BOOL WINAPI GetDiskFreeSpaceExW( LPCWSTR root, PULARGE_INTEGER avail,
1274                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1275 {
1276     FILE_FS_SIZE_INFORMATION info;
1277     IO_STATUS_BLOCK io;
1278     NTSTATUS status;
1279     HANDLE handle;
1280     UINT units;
1281
1282     TRACE( "%s,%p,%p,%p\n", debugstr_w(root), avail, total, totalfree );
1283
1284     if (!open_device_root( root, &handle )) return FALSE;
1285
1286     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1287     NtClose( handle );
1288     if (status != STATUS_SUCCESS)
1289     {
1290         SetLastError( RtlNtStatusToDosError(status) );
1291         return FALSE;
1292     }
1293
1294     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1295     if (total) total->QuadPart = info.TotalAllocationUnits.QuadPart * units;
1296     if (totalfree) totalfree->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1297     /* FIXME: this one should take quotas into account */
1298     if (avail) avail->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1299     return TRUE;
1300 }
1301
1302
1303 /***********************************************************************
1304  *           GetDiskFreeSpaceExA   (KERNEL32.@)
1305  *
1306  * See GetDiskFreeSpaceExW.
1307  */
1308 BOOL WINAPI GetDiskFreeSpaceExA( LPCSTR root, PULARGE_INTEGER avail,
1309                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1310 {
1311     WCHAR *rootW = NULL;
1312
1313     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1314     return GetDiskFreeSpaceExW( rootW, avail, total, totalfree );
1315 }
1316
1317
1318 /***********************************************************************
1319  *           GetDiskFreeSpaceW   (KERNEL32.@)
1320  */
1321 BOOL WINAPI GetDiskFreeSpaceW( LPCWSTR root, LPDWORD cluster_sectors,
1322                                LPDWORD sector_bytes, LPDWORD free_clusters,
1323                                LPDWORD total_clusters )
1324 {
1325     FILE_FS_SIZE_INFORMATION info;
1326     IO_STATUS_BLOCK io;
1327     NTSTATUS status;
1328     HANDLE handle;
1329     UINT units;
1330
1331     TRACE( "%s,%p,%p,%p,%p\n", debugstr_w(root),
1332            cluster_sectors, sector_bytes, free_clusters, total_clusters );
1333
1334     if (!open_device_root( root, &handle )) return FALSE;
1335
1336     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1337     NtClose( handle );
1338     if (status != STATUS_SUCCESS)
1339     {
1340         SetLastError( RtlNtStatusToDosError(status) );
1341         return FALSE;
1342     }
1343
1344     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1345
1346     if( GetVersion() & 0x80000000) {    /* win3.x, 9x, ME */
1347         /* cap the size and available at 2GB as per specs */
1348         if (info.TotalAllocationUnits.QuadPart * units > 0x7fffffff) {
1349             info.TotalAllocationUnits.QuadPart = 0x7fffffff / units;
1350             if (info.AvailableAllocationUnits.QuadPart * units > 0x7fffffff)
1351                 info.AvailableAllocationUnits.QuadPart = 0x7fffffff / units;
1352         }
1353         /* nr. of clusters is always <= 65335 */
1354         while( info.TotalAllocationUnits.QuadPart > 65535 ) {
1355             info.TotalAllocationUnits.QuadPart /= 2;
1356             info.AvailableAllocationUnits.QuadPart /= 2;
1357             info.SectorsPerAllocationUnit *= 2;
1358         }
1359     }
1360
1361     if (cluster_sectors) *cluster_sectors = info.SectorsPerAllocationUnit;
1362     if (sector_bytes) *sector_bytes = info.BytesPerSector;
1363     if (free_clusters) *free_clusters = info.AvailableAllocationUnits.u.LowPart;
1364     if (total_clusters) *total_clusters = info.TotalAllocationUnits.u.LowPart;
1365     return TRUE;
1366 }
1367
1368
1369 /***********************************************************************
1370  *           GetDiskFreeSpaceA   (KERNEL32.@)
1371  */
1372 BOOL WINAPI GetDiskFreeSpaceA( LPCSTR root, LPDWORD cluster_sectors,
1373                                LPDWORD sector_bytes, LPDWORD free_clusters,
1374                                LPDWORD total_clusters )
1375 {
1376     WCHAR *rootW = NULL;
1377
1378     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1379     return GetDiskFreeSpaceW( rootW, cluster_sectors, sector_bytes, free_clusters, total_clusters );
1380 }
1381
1382 /***********************************************************************
1383  *           GetVolumePathNameA   (KERNEL32.@)
1384  */
1385 BOOL WINAPI GetVolumePathNameA(LPCSTR filename, LPSTR volumepathname, DWORD buflen)
1386 {
1387     FIXME("(%s, %p, %d), stub!\n", debugstr_a(filename), volumepathname, buflen);
1388     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1389     return FALSE;
1390 }
1391
1392 /***********************************************************************
1393  *           GetVolumePathNameW   (KERNEL32.@)
1394  */
1395 BOOL WINAPI GetVolumePathNameW(LPCWSTR filename, LPWSTR volumepathname, DWORD buflen)
1396 {
1397     FIXME("(%s, %p, %d), stub!\n", debugstr_w(filename), volumepathname, buflen);
1398     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1399     return FALSE;
1400 }
1401
1402 /***********************************************************************
1403  *           FindFirstVolumeA   (KERNEL32.@)
1404  */
1405 HANDLE WINAPI FindFirstVolumeA(LPSTR volume, DWORD len)
1406 {
1407     WCHAR *buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1408     HANDLE handle = FindFirstVolumeW( buffer, len );
1409
1410     if (handle != INVALID_HANDLE_VALUE)
1411     {
1412         if (!WideCharToMultiByte( CP_ACP, 0, buffer, -1, volume, len, NULL, NULL ))
1413         {
1414             FindVolumeClose( handle );
1415             handle = INVALID_HANDLE_VALUE;
1416         }
1417     }
1418     HeapFree( GetProcessHeap(), 0, buffer );
1419     return handle;
1420 }
1421
1422 /***********************************************************************
1423  *           FindFirstVolumeW   (KERNEL32.@)
1424  */
1425 HANDLE WINAPI FindFirstVolumeW( LPWSTR volume, DWORD len )
1426 {
1427     DWORD size = 1024;
1428     HANDLE mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE,
1429                               NULL, OPEN_EXISTING, 0, 0 );
1430     if (mgr == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;
1431
1432     for (;;)
1433     {
1434         MOUNTMGR_MOUNT_POINT input;
1435         MOUNTMGR_MOUNT_POINTS *output;
1436
1437         if (!(output = HeapAlloc( GetProcessHeap(), 0, size )))
1438         {
1439             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1440             break;
1441         }
1442         memset( &input, 0, sizeof(input) );
1443
1444         if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, &input, sizeof(input),
1445                               output, size, NULL, NULL ))
1446         {
1447             if (GetLastError() != ERROR_MORE_DATA) break;
1448             size = output->Size;
1449             HeapFree( GetProcessHeap(), 0, output );
1450             continue;
1451         }
1452         CloseHandle( mgr );
1453         /* abuse the Size field to store the current index */
1454         output->Size = 0;
1455         if (!FindNextVolumeW( output, volume, len ))
1456         {
1457             HeapFree( GetProcessHeap(), 0, output );
1458             return INVALID_HANDLE_VALUE;
1459         }
1460         return (HANDLE)output;
1461     }
1462     CloseHandle( mgr );
1463     return INVALID_HANDLE_VALUE;
1464 }
1465
1466 /***********************************************************************
1467  *           FindNextVolumeA   (KERNEL32.@)
1468  */
1469 BOOL WINAPI FindNextVolumeA( HANDLE handle, LPSTR volume, DWORD len )
1470 {
1471     WCHAR *buffer = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) );
1472     BOOL ret;
1473
1474     if ((ret = FindNextVolumeW( handle, buffer, len )))
1475     {
1476         if (!WideCharToMultiByte( CP_ACP, 0, buffer, -1, volume, len, NULL, NULL )) ret = FALSE;
1477     }
1478     return ret;
1479 }
1480
1481 /***********************************************************************
1482  *           FindNextVolumeW   (KERNEL32.@)
1483  */
1484 BOOL WINAPI FindNextVolumeW( HANDLE handle, LPWSTR volume, DWORD len )
1485 {
1486     MOUNTMGR_MOUNT_POINTS *data = handle;
1487
1488     while (data->Size < data->NumberOfMountPoints)
1489     {
1490         static const WCHAR volumeW[] = {'\\','?','?','\\','V','o','l','u','m','e','{',};
1491         WCHAR *link = (WCHAR *)((char *)data + data->MountPoints[data->Size].SymbolicLinkNameOffset);
1492         DWORD size = data->MountPoints[data->Size].SymbolicLinkNameLength;
1493         data->Size++;
1494         /* skip non-volumes */
1495         if (size < sizeof(volumeW) || memcmp( link, volumeW, sizeof(volumeW) )) continue;
1496         if (size + sizeof(WCHAR) >= len * sizeof(WCHAR))
1497         {
1498             SetLastError( ERROR_FILENAME_EXCED_RANGE );
1499             return FALSE;
1500         }
1501         memcpy( volume, link, size );
1502         volume[1] = '\\';  /* map \??\ to \\?\ */
1503         volume[size / sizeof(WCHAR)] = '\\';  /* Windows appends a backslash */
1504         volume[size / sizeof(WCHAR) + 1] = 0;
1505         TRACE( "returning entry %u %s\n", data->Size - 1, debugstr_w(volume) );
1506         return TRUE;
1507     }
1508     SetLastError( ERROR_NO_MORE_FILES );
1509     return FALSE;
1510 }
1511
1512 /***********************************************************************
1513  *           FindVolumeClose   (KERNEL32.@)
1514  */
1515 BOOL WINAPI FindVolumeClose(HANDLE handle)
1516 {
1517     return HeapFree( GetProcessHeap(), 0, handle );
1518 }
1519
1520 /***********************************************************************
1521  *           FindFirstVolumeMountPointA   (KERNEL32.@)
1522  */
1523 HANDLE WINAPI FindFirstVolumeMountPointA(LPCSTR root, LPSTR mount_point, DWORD len)
1524 {
1525     FIXME("(%s, %p, %d), stub!\n", debugstr_a(root), mount_point, len);
1526     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1527     return INVALID_HANDLE_VALUE;
1528 }
1529
1530 /***********************************************************************
1531  *           FindFirstVolumeMountPointW   (KERNEL32.@)
1532  */
1533 HANDLE WINAPI FindFirstVolumeMountPointW(LPCWSTR root, LPWSTR mount_point, DWORD len)
1534 {
1535     FIXME("(%s, %p, %d), stub!\n", debugstr_w(root), mount_point, len);
1536     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1537     return INVALID_HANDLE_VALUE;
1538 }
1539
1540 /***********************************************************************
1541  *           FindVolumeMountPointClose   (KERNEL32.@)
1542  */
1543 BOOL WINAPI FindVolumeMountPointClose(HANDLE h)
1544 {
1545     FIXME("(%p), stub!\n", h);
1546     return FALSE;
1547 }