Correctly use the returned value from GetTimeZoneInformation.
[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         unsigned 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                 unsigned 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 TRACE( "cannot open device %s: err %ld\n", debugstr_w(device), GetLastError() );
767
768     /* we couldn't open the device, fallback to default strategy */
769
770     switch(GetDriveTypeW( root ))
771     {
772     case DRIVE_UNKNOWN:
773     case DRIVE_NO_ROOT_DIR:
774         SetLastError( ERROR_NOT_READY );
775         return FALSE;
776     case DRIVE_REMOVABLE:
777     case DRIVE_FIXED:
778     case DRIVE_REMOTE:
779     case DRIVE_RAMDISK:
780         type = FS_UNKNOWN;
781         break;
782     case DRIVE_CDROM:
783         type = FS_ISO9660;
784         break;
785     }
786
787     if (label && label_len)
788     {
789         WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
790
791         labelW[0] = device[4];
792         handle = CreateFileW( labelW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
793                               OPEN_EXISTING, 0, 0 );
794         if (handle != INVALID_HANDLE_VALUE)
795         {
796             char buffer[256], *p;
797             DWORD size;
798
799             if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
800             CloseHandle( handle );
801             p = buffer + size;
802             while (p > buffer && (p[-1] == ' ' || p[-1] == '\r' || p[-1] == '\n')) p--;
803             *p = 0;
804             if (!MultiByteToWideChar( CP_UNIXCP, 0, buffer, -1, label, label_len ))
805                 label[label_len-1] = 0;
806         }
807         else label[0] = 0;
808     }
809     if (serial)
810     {
811         WCHAR serialW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','s','e','r','i','a','l',0};
812
813         serialW[0] = device[4];
814         handle = CreateFileW( serialW, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
815                               OPEN_EXISTING, 0, 0 );
816         if (handle != INVALID_HANDLE_VALUE)
817         {
818             char buffer[32];
819             DWORD size;
820
821             if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
822             CloseHandle( handle );
823             buffer[size] = 0;
824             *serial = strtoul( buffer, NULL, 16 );
825         }
826         else *serial = 0;
827     }
828
829 fill_fs_info:  /* now fill in the information that depends on the file system type */
830
831     switch(type)
832     {
833     case FS_ISO9660:
834         if (fsname) lstrcpynW( fsname, cdfsW, fsname_len );
835         if (filename_len) *filename_len = 221;
836         if (flags) *flags = FILE_READ_ONLY_VOLUME;
837         break;
838     case FS_FAT1216:
839     case FS_FAT32:
840         if (fsname) lstrcpynW( fsname, fatW, fsname_len );
841         if (filename_len) *filename_len = 255;
842         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;  /* FIXME */
843         break;
844     default:
845         if (fsname) lstrcpynW( fsname, ntfsW, fsname_len );
846         if (filename_len) *filename_len = 255;
847         if (flags) *flags = FILE_CASE_PRESERVED_NAMES;
848         break;
849     }
850     return TRUE;
851 }
852
853
854 /***********************************************************************
855  *           GetVolumeInformationA   (KERNEL32.@)
856  */
857 BOOL WINAPI GetVolumeInformationA( LPCSTR root, LPSTR label,
858                                    DWORD label_len, DWORD *serial,
859                                    DWORD *filename_len, DWORD *flags,
860                                    LPSTR fsname, DWORD fsname_len )
861 {
862     WCHAR *rootW = NULL;
863     LPWSTR labelW, fsnameW;
864     BOOL ret;
865
866     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
867
868     labelW = label ? HeapAlloc(GetProcessHeap(), 0, label_len * sizeof(WCHAR)) : NULL;
869     fsnameW = fsname ? HeapAlloc(GetProcessHeap(), 0, fsname_len * sizeof(WCHAR)) : NULL;
870
871     if ((ret = GetVolumeInformationW(rootW, labelW, label_len, serial,
872                                     filename_len, flags, fsnameW, fsname_len)))
873     {
874         if (label) FILE_name_WtoA( labelW, -1, label, label_len );
875         if (fsname) FILE_name_WtoA( fsnameW, -1, fsname, fsname_len );
876     }
877
878     if (labelW) HeapFree( GetProcessHeap(), 0, labelW );
879     if (fsnameW) HeapFree( GetProcessHeap(), 0, fsnameW );
880     return ret;
881 }
882
883
884
885 /***********************************************************************
886  *           SetVolumeLabelW   (KERNEL32.@)
887  */
888 BOOL WINAPI SetVolumeLabelW( LPCWSTR root, LPCWSTR label )
889 {
890     WCHAR device[] = {'\\','\\','.','\\','A',':',0};
891     HANDLE handle;
892     enum fs_type type = FS_UNKNOWN;
893
894     if (!root)
895     {
896         WCHAR path[MAX_PATH];
897         GetCurrentDirectoryW( MAX_PATH, path );
898         device[4] = path[0];
899     }
900     else
901     {
902         if (!root[0] || root[1] != ':')
903         {
904             SetLastError( ERROR_INVALID_NAME );
905             return FALSE;
906         }
907         device[4] = root[0];
908     }
909
910     /* try to open the device */
911
912     handle = CreateFileW( device, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE,
913                           NULL, OPEN_EXISTING, 0, 0 );
914     if (handle == INVALID_HANDLE_VALUE)
915     {
916         /* try read-only */
917         handle = CreateFileW( device, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE,
918                               NULL, OPEN_EXISTING, 0, 0 );
919         if (handle != INVALID_HANDLE_VALUE)
920         {
921             /* device can be read but not written, return error */
922             CloseHandle( handle );
923             SetLastError( ERROR_ACCESS_DENIED );
924             return FALSE;
925         }
926     }
927
928     if (handle != INVALID_HANDLE_VALUE)
929     {
930         BYTE superblock[SUPERBLOCK_SIZE];
931         BOOL ret;
932
933         type = VOLUME_ReadFATSuperblock( handle, superblock );
934         ret = VOLUME_SetSuperblockLabel( type, handle, label );
935         CloseHandle( handle );
936         return ret;
937     }
938     else
939     {
940         TRACE( "cannot open device %s: err %ld\n", debugstr_w(device), GetLastError() );
941         if (GetLastError() != ERROR_ACCESS_DENIED) return FALSE;
942     }
943
944     /* we couldn't open the device, fallback to default strategy */
945
946     switch(GetDriveTypeW( root ))
947     {
948     case DRIVE_UNKNOWN:
949     case DRIVE_NO_ROOT_DIR:
950         SetLastError( ERROR_NOT_READY );
951         break;
952     case DRIVE_REMOVABLE:
953     case DRIVE_FIXED:
954         {
955             WCHAR labelW[] = {'A',':','\\','.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
956
957             labelW[0] = device[4];
958             handle = CreateFileW( labelW, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL,
959                                   CREATE_ALWAYS, 0, 0 );
960             if (handle != INVALID_HANDLE_VALUE)
961             {
962                 char buffer[64];
963                 DWORD size;
964
965                 if (!WideCharToMultiByte( CP_UNIXCP, 0, label, -1, buffer, sizeof(buffer), NULL, NULL ))
966                     buffer[sizeof(buffer)-1] = 0;
967                 WriteFile( handle, buffer, strlen(buffer), &size, NULL );
968                 CloseHandle( handle );
969                 return TRUE;
970             }
971             break;
972         }
973     case DRIVE_REMOTE:
974     case DRIVE_RAMDISK:
975     case DRIVE_CDROM:
976         SetLastError( ERROR_ACCESS_DENIED );
977         break;
978     }
979     return FALSE;
980 }
981
982 /***********************************************************************
983  *           SetVolumeLabelA   (KERNEL32.@)
984  */
985 BOOL WINAPI SetVolumeLabelA(LPCSTR root, LPCSTR volname)
986 {
987     WCHAR *rootW = NULL, *volnameW = NULL;
988     BOOL ret;
989
990     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
991     if (volname && !(volnameW = FILE_name_AtoW( volname, TRUE ))) return FALSE;
992     ret = SetVolumeLabelW( rootW, volnameW );
993     if (volnameW) HeapFree( GetProcessHeap(), 0, volnameW );
994     return ret;
995 }
996
997
998 /***********************************************************************
999  *           GetVolumeNameForVolumeMountPointW   (KERNEL32.@)
1000  */
1001 BOOL WINAPI GetVolumeNameForVolumeMountPointW(LPCWSTR str, LPWSTR dst, DWORD size)
1002 {
1003     FIXME("(%s, %p, %lx): stub\n", debugstr_w(str), dst, size);
1004     return 0;
1005 }
1006
1007
1008 /***********************************************************************
1009  *           DefineDosDeviceW       (KERNEL32.@)
1010  */
1011 BOOL WINAPI DefineDosDeviceW( DWORD flags, LPCWSTR devname, LPCWSTR targetpath )
1012 {
1013     DWORD len, dosdev;
1014     BOOL ret = FALSE;
1015     char *path = NULL, *target, *p;
1016
1017     if (!(flags & DDD_REMOVE_DEFINITION))
1018     {
1019         if (!(flags & DDD_RAW_TARGET_PATH))
1020         {
1021             FIXME( "(0x%08lx,%s,%s) DDD_RAW_TARGET_PATH flag not set, not supported yet\n",
1022                    flags, debugstr_w(devname), debugstr_w(targetpath) );
1023             SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1024             return FALSE;
1025         }
1026
1027         len = WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, NULL, 0, NULL, NULL );
1028         if ((target = HeapAlloc( GetProcessHeap(), 0, len )))
1029         {
1030             WideCharToMultiByte( CP_UNIXCP, 0, targetpath, -1, target, len, NULL, NULL );
1031             for (p = target; *p; p++) if (*p == '\\') *p = '/';
1032         }
1033         else
1034         {
1035             SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1036             return FALSE;
1037         }
1038     }
1039     else target = NULL;
1040
1041     /* first check for a DOS device */
1042
1043     if ((dosdev = RtlIsDosDeviceName_U( devname )))
1044     {
1045         WCHAR name[5];
1046
1047         memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
1048         name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
1049         path = get_dos_device_path( name );
1050     }
1051     else if (isalphaW(devname[0]) && devname[1] == ':' && !devname[2])  /* drive mapping */
1052     {
1053         path = get_dos_device_path( devname );
1054     }
1055     else SetLastError( ERROR_FILE_NOT_FOUND );
1056
1057     if (path)
1058     {
1059         if (target)
1060         {
1061             TRACE( "creating symlink %s -> %s\n", path, target );
1062             unlink( path );
1063             if (!symlink( target, path )) ret = TRUE;
1064             else FILE_SetDosError();
1065         }
1066         else
1067         {
1068             TRACE( "removing symlink %s\n", path );
1069             if (!unlink( path )) ret = TRUE;
1070             else FILE_SetDosError();
1071         }
1072         HeapFree( GetProcessHeap(), 0, path );
1073     }
1074     if (target) HeapFree( GetProcessHeap(), 0, target );
1075     return ret;
1076 }
1077
1078
1079 /***********************************************************************
1080  *           DefineDosDeviceA       (KERNEL32.@)
1081  */
1082 BOOL WINAPI DefineDosDeviceA(DWORD flags, LPCSTR devname, LPCSTR targetpath)
1083 {
1084     WCHAR *devW, *targetW = NULL;
1085     BOOL ret;
1086
1087     if (!(devW = FILE_name_AtoW( devname, FALSE ))) return FALSE;
1088     if (targetpath && !(targetW = FILE_name_AtoW( targetpath, TRUE ))) return FALSE;
1089     ret = DefineDosDeviceW(flags, devW, targetW);
1090     if (targetW) HeapFree( GetProcessHeap(), 0, targetW );
1091     return ret;
1092 }
1093
1094
1095 /***********************************************************************
1096  *           QueryDosDeviceW   (KERNEL32.@)
1097  *
1098  * returns array of strings terminated by \0, terminated by \0
1099  */
1100 DWORD WINAPI QueryDosDeviceW( LPCWSTR devname, LPWSTR target, DWORD bufsize )
1101 {
1102     static const WCHAR auxW[] = {'A','U','X',0};
1103     static const WCHAR nulW[] = {'N','U','L',0};
1104     static const WCHAR prnW[] = {'P','R','N',0};
1105     static const WCHAR comW[] = {'C','O','M',0};
1106     static const WCHAR lptW[] = {'L','P','T',0};
1107     static const WCHAR rootW[] = {'A',':','\\',0};
1108     static const WCHAR com0W[] = {'\\','?','?','\\','C','O','M','0',0};
1109     static const WCHAR com1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','C','O','M','1',0,0};
1110     static const WCHAR lpt1W[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\','L','P','T','1',0,0};
1111
1112     UNICODE_STRING nt_name;
1113     ANSI_STRING unix_name;
1114     WCHAR nt_buffer[10];
1115     NTSTATUS status;
1116
1117     if (!bufsize)
1118     {
1119         SetLastError( ERROR_INSUFFICIENT_BUFFER );
1120         return 0;
1121     }
1122
1123     if (devname)
1124     {
1125         WCHAR *p, name[5];
1126         char *path, *link;
1127         DWORD dosdev, ret = 0;
1128
1129         if ((dosdev = RtlIsDosDeviceName_U( devname )))
1130         {
1131             memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
1132             name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
1133         }
1134         else if (devname[0] && devname[1] == ':' && !devname[2])
1135         {
1136             memcpy( name, devname, 3 * sizeof(WCHAR) );
1137         }
1138         else
1139         {
1140             SetLastError( ERROR_BAD_PATHNAME );
1141             return 0;
1142         }
1143
1144         if (!(path = get_dos_device_path( name ))) return 0;
1145         link = read_symlink( path );
1146         HeapFree( GetProcessHeap(), 0, path );
1147
1148         if (link)
1149         {
1150             ret = MultiByteToWideChar( CP_UNIXCP, 0, link, -1, target, bufsize );
1151             HeapFree( GetProcessHeap(), 0, link );
1152         }
1153         else if (dosdev)  /* look for device defaults */
1154         {
1155             if (!strcmpiW( name, auxW ))
1156             {
1157                 if (bufsize >= sizeof(com1W)/sizeof(WCHAR))
1158                 {
1159                     memcpy( target, com1W, sizeof(com1W) );
1160                     ret = sizeof(com1W)/sizeof(WCHAR);
1161                 }
1162                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
1163                 return ret;
1164             }
1165             if (!strcmpiW( name, prnW ))
1166             {
1167                 if (bufsize >= sizeof(lpt1W)/sizeof(WCHAR))
1168                 {
1169                     memcpy( target, lpt1W, sizeof(lpt1W) );
1170                     ret = sizeof(lpt1W)/sizeof(WCHAR);
1171                 }
1172                 else SetLastError( ERROR_INSUFFICIENT_BUFFER );
1173                 return ret;
1174             }
1175
1176             nt_buffer[0] = '\\';
1177             nt_buffer[1] = '?';
1178             nt_buffer[2] = '?';
1179             nt_buffer[3] = '\\';
1180             strcpyW( nt_buffer + 4, name );
1181             RtlInitUnicodeString( &nt_name, nt_buffer );
1182             status = wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE );
1183             if (status) SetLastError( RtlNtStatusToDosError(status) );
1184             else
1185             {
1186                 ret = MultiByteToWideChar( CP_UNIXCP, 0, unix_name.Buffer, -1, target, bufsize );
1187                 RtlFreeAnsiString( &unix_name );
1188             }
1189         }
1190
1191         if (ret)
1192         {
1193             if (ret < bufsize) target[ret++] = 0;  /* add an extra null */
1194             for (p = target; *p; p++) if (*p == '/') *p = '\\';
1195         }
1196
1197         return ret;
1198     }
1199     else  /* return a list of all devices */
1200     {
1201         WCHAR *p = target;
1202         int i;
1203
1204         if (bufsize <= (sizeof(auxW)+sizeof(nulW)+sizeof(prnW))/sizeof(WCHAR))
1205         {
1206             SetLastError( ERROR_INSUFFICIENT_BUFFER );
1207             return 0;
1208         }
1209
1210         memcpy( p, auxW, sizeof(auxW) );
1211         p += sizeof(auxW) / sizeof(WCHAR);
1212         memcpy( p, nulW, sizeof(nulW) );
1213         p += sizeof(nulW) / sizeof(WCHAR);
1214         memcpy( p, prnW, sizeof(prnW) );
1215         p += sizeof(prnW) / sizeof(WCHAR);
1216
1217         strcpyW( nt_buffer, com0W );
1218         RtlInitUnicodeString( &nt_name, nt_buffer );
1219
1220         for (i = 1; i <= 9; i++)
1221         {
1222             nt_buffer[7] = '0' + i;
1223             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1224             {
1225                 RtlFreeAnsiString( &unix_name );
1226                 if (p + 5 >= target + bufsize)
1227                 {
1228                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1229                     return 0;
1230                 }
1231                 strcpyW( p, comW );
1232                 p[3] = '0' + i;
1233                 p[4] = 0;
1234                 p += 5;
1235             }
1236         }
1237         strcpyW( nt_buffer + 4, lptW );
1238         for (i = 1; i <= 9; i++)
1239         {
1240             nt_buffer[7] = '0' + i;
1241             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1242             {
1243                 RtlFreeAnsiString( &unix_name );
1244                 if (p + 5 >= target + bufsize)
1245                 {
1246                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1247                     return 0;
1248                 }
1249                 strcpyW( p, lptW );
1250                 p[3] = '0' + i;
1251                 p[4] = 0;
1252                 p += 5;
1253             }
1254         }
1255
1256         strcpyW( nt_buffer + 4, rootW );
1257         RtlInitUnicodeString( &nt_name, nt_buffer );
1258
1259         for (i = 0; i < 26; i++)
1260         {
1261             nt_buffer[4] = 'a' + i;
1262             if (!wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, TRUE ))
1263             {
1264                 RtlFreeAnsiString( &unix_name );
1265                 if (p + 3 >= target + bufsize)
1266                 {
1267                     SetLastError( ERROR_INSUFFICIENT_BUFFER );
1268                     return 0;
1269                 }
1270                 *p++ = 'A' + i;
1271                 *p++ = ':';
1272                 *p++ = 0;
1273             }
1274         }
1275         *p++ = 0;  /* terminating null */
1276         return p - target;
1277     }
1278 }
1279
1280
1281 /***********************************************************************
1282  *           QueryDosDeviceA   (KERNEL32.@)
1283  *
1284  * returns array of strings terminated by \0, terminated by \0
1285  */
1286 DWORD WINAPI QueryDosDeviceA( LPCSTR devname, LPSTR target, DWORD bufsize )
1287 {
1288     DWORD ret = 0, retW;
1289     WCHAR *devnameW;
1290     LPWSTR targetW;
1291
1292     if (!(devnameW = FILE_name_AtoW( devname, FALSE ))) return 0;
1293
1294     targetW = HeapAlloc( GetProcessHeap(),0, bufsize * sizeof(WCHAR) );
1295     if (!targetW)
1296     {
1297         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1298         return 0;
1299     }
1300
1301     retW = QueryDosDeviceW(devnameW, targetW, bufsize);
1302
1303     ret = FILE_name_WtoA( targetW, retW, target, bufsize );
1304
1305     HeapFree(GetProcessHeap(), 0, targetW);
1306     return ret;
1307 }
1308
1309
1310 /***********************************************************************
1311  *           GetLogicalDrives   (KERNEL32.@)
1312  */
1313 DWORD WINAPI GetLogicalDrives(void)
1314 {
1315     const char *config_dir = wine_get_config_dir();
1316     struct stat st;
1317     char *buffer, *dev;
1318     DWORD ret = 0;
1319     int i;
1320
1321     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, strlen(config_dir) + sizeof("/dosdevices/a:") )))
1322     {
1323         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1324         return 0;
1325     }
1326     strcpy( buffer, config_dir );
1327     strcat( buffer, "/dosdevices/a:" );
1328     dev = buffer + strlen(buffer) - 2;
1329
1330     for (i = 0; i < 26; i++)
1331     {
1332         *dev = 'a' + i;
1333         if (!stat( buffer, &st )) ret |= (1 << i);
1334     }
1335     HeapFree( GetProcessHeap(), 0, buffer );
1336     return ret;
1337 }
1338
1339
1340 /***********************************************************************
1341  *           GetLogicalDriveStringsA   (KERNEL32.@)
1342  */
1343 UINT WINAPI GetLogicalDriveStringsA( UINT len, LPSTR buffer )
1344 {
1345     DWORD drives = GetLogicalDrives();
1346     UINT drive, count;
1347
1348     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1349     if ((count * 4) + 1 > len) return count * 4 + 1;
1350
1351     for (drive = 0; drive < 26; drive++)
1352     {
1353         if (drives & (1 << drive))
1354         {
1355             *buffer++ = 'a' + drive;
1356             *buffer++ = ':';
1357             *buffer++ = '\\';
1358             *buffer++ = 0;
1359         }
1360     }
1361     *buffer = 0;
1362     return count * 4;
1363 }
1364
1365
1366 /***********************************************************************
1367  *           GetLogicalDriveStringsW   (KERNEL32.@)
1368  */
1369 UINT WINAPI GetLogicalDriveStringsW( UINT len, LPWSTR buffer )
1370 {
1371     DWORD drives = GetLogicalDrives();
1372     UINT drive, count;
1373
1374     for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1375     if ((count * 4) + 1 > len) return count * 4 + 1;
1376
1377     for (drive = 0; drive < 26; drive++)
1378     {
1379         if (drives & (1 << drive))
1380         {
1381             *buffer++ = 'a' + drive;
1382             *buffer++ = ':';
1383             *buffer++ = '\\';
1384             *buffer++ = 0;
1385         }
1386     }
1387     *buffer = 0;
1388     return count * 4;
1389 }
1390
1391
1392 /***********************************************************************
1393  *           GetDriveTypeW   (KERNEL32.@)
1394  *
1395  * Returns the type of the disk drive specified. If root is NULL the
1396  * root of the current directory is used.
1397  *
1398  * RETURNS
1399  *
1400  *  Type of drive (from Win32 SDK):
1401  *
1402  *   DRIVE_UNKNOWN     unable to find out anything about the drive
1403  *   DRIVE_NO_ROOT_DIR nonexistent root dir
1404  *   DRIVE_REMOVABLE   the disk can be removed from the machine
1405  *   DRIVE_FIXED       the disk can not be removed from the machine
1406  *   DRIVE_REMOTE      network disk
1407  *   DRIVE_CDROM       CDROM drive
1408  *   DRIVE_RAMDISK     virtual disk in RAM
1409  */
1410 UINT WINAPI GetDriveTypeW(LPCWSTR root) /* [in] String describing drive */
1411 {
1412     FILE_FS_DEVICE_INFORMATION info;
1413     IO_STATUS_BLOCK io;
1414     NTSTATUS status;
1415     HANDLE handle;
1416     UINT ret;
1417
1418     if (!open_device_root( root, &handle )) return DRIVE_NO_ROOT_DIR;
1419
1420     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsDeviceInformation );
1421     NtClose( handle );
1422     if (status != STATUS_SUCCESS)
1423     {
1424         SetLastError( RtlNtStatusToDosError(status) );
1425         ret = DRIVE_UNKNOWN;
1426     }
1427     else if ((ret = get_registry_drive_type( root )) == DRIVE_UNKNOWN)
1428     {
1429         switch (info.DeviceType)
1430         {
1431         case FILE_DEVICE_CD_ROM_FILE_SYSTEM:  ret = DRIVE_CDROM; break;
1432         case FILE_DEVICE_VIRTUAL_DISK:        ret = DRIVE_RAMDISK; break;
1433         case FILE_DEVICE_NETWORK_FILE_SYSTEM: ret = DRIVE_REMOTE; break;
1434         case FILE_DEVICE_DISK_FILE_SYSTEM:
1435             if (info.Characteristics & FILE_REMOTE_DEVICE) ret = DRIVE_REMOTE;
1436             else if (info.Characteristics & FILE_REMOVABLE_MEDIA) ret = DRIVE_REMOVABLE;
1437             else ret = DRIVE_FIXED;
1438             break;
1439         default:
1440             ret = DRIVE_UNKNOWN;
1441             break;
1442         }
1443     }
1444     TRACE( "%s -> %d\n", debugstr_w(root), ret );
1445     return ret;
1446 }
1447
1448
1449 /***********************************************************************
1450  *           GetDriveTypeA   (KERNEL32.@)
1451  */
1452 UINT WINAPI GetDriveTypeA( LPCSTR root )
1453 {
1454     WCHAR *rootW = NULL;
1455
1456     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return DRIVE_NO_ROOT_DIR;
1457     return GetDriveTypeW( rootW );
1458 }
1459
1460
1461 /***********************************************************************
1462  *           GetDiskFreeSpaceExW   (KERNEL32.@)
1463  *
1464  *  This function is used to acquire the size of the available and
1465  *  total space on a logical volume.
1466  *
1467  * RETURNS
1468  *
1469  *  Zero on failure, nonzero upon success. Use GetLastError to obtain
1470  *  detailed error information.
1471  *
1472  */
1473 BOOL WINAPI GetDiskFreeSpaceExW( LPCWSTR root, PULARGE_INTEGER avail,
1474                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1475 {
1476     FILE_FS_SIZE_INFORMATION info;
1477     IO_STATUS_BLOCK io;
1478     NTSTATUS status;
1479     HANDLE handle;
1480     UINT units;
1481
1482     TRACE( "%s,%p,%p,%p\n", debugstr_w(root), avail, total, totalfree );
1483
1484     if (!open_device_root( root, &handle )) return FALSE;
1485
1486     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1487     NtClose( handle );
1488     if (status != STATUS_SUCCESS)
1489     {
1490         SetLastError( RtlNtStatusToDosError(status) );
1491         return FALSE;
1492     }
1493
1494     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1495     if (total) total->QuadPart = info.TotalAllocationUnits.QuadPart * units;
1496     if (totalfree) totalfree->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1497     /* FIXME: this one should take quotas into account */
1498     if (avail) avail->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1499     return TRUE;
1500 }
1501
1502
1503 /***********************************************************************
1504  *           GetDiskFreeSpaceExA   (KERNEL32.@)
1505  */
1506 BOOL WINAPI GetDiskFreeSpaceExA( LPCSTR root, PULARGE_INTEGER avail,
1507                                  PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1508 {
1509     WCHAR *rootW = NULL;
1510
1511     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1512     return GetDiskFreeSpaceExW( rootW, avail, total, totalfree );
1513 }
1514
1515
1516 /***********************************************************************
1517  *           GetDiskFreeSpaceW   (KERNEL32.@)
1518  */
1519 BOOL WINAPI GetDiskFreeSpaceW( LPCWSTR root, LPDWORD cluster_sectors,
1520                                LPDWORD sector_bytes, LPDWORD free_clusters,
1521                                LPDWORD total_clusters )
1522 {
1523     FILE_FS_SIZE_INFORMATION info;
1524     IO_STATUS_BLOCK io;
1525     NTSTATUS status;
1526     HANDLE handle;
1527     UINT units;
1528
1529     TRACE( "%s,%p,%p,%p,%p\n", debugstr_w(root),
1530            cluster_sectors, sector_bytes, free_clusters, total_clusters );
1531
1532     if (!open_device_root( root, &handle )) return FALSE;
1533
1534     status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1535     NtClose( handle );
1536     if (status != STATUS_SUCCESS)
1537     {
1538         SetLastError( RtlNtStatusToDosError(status) );
1539         return FALSE;
1540     }
1541
1542     units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1543
1544     /* cap the size and available at 2GB as per specs */
1545     if (info.AvailableAllocationUnits.QuadPart * units > 0x7fffffff)
1546         info.AvailableAllocationUnits.QuadPart = 0x7fffffff / units;
1547     if (info.TotalAllocationUnits.QuadPart * units > 0x7fffffff)
1548         info.TotalAllocationUnits.QuadPart = 0x7fffffff / units;
1549
1550     if (cluster_sectors) *cluster_sectors = info.SectorsPerAllocationUnit;
1551     if (sector_bytes) *sector_bytes = info.BytesPerSector;
1552     if (free_clusters) *free_clusters = info.AvailableAllocationUnits.u.LowPart;
1553     if (total_clusters) *total_clusters = info.TotalAllocationUnits.u.LowPart;
1554     return TRUE;
1555 }
1556
1557
1558 /***********************************************************************
1559  *           GetDiskFreeSpaceA   (KERNEL32.@)
1560  */
1561 BOOL WINAPI GetDiskFreeSpaceA( LPCSTR root, LPDWORD cluster_sectors,
1562                                LPDWORD sector_bytes, LPDWORD free_clusters,
1563                                LPDWORD total_clusters )
1564 {
1565     WCHAR *rootW = NULL;
1566
1567     if (root && !(rootW = FILE_name_AtoW( root, FALSE ))) return FALSE;
1568     return GetDiskFreeSpaceW( rootW, cluster_sectors, sector_bytes, free_clusters, total_clusters );
1569 }