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