ntdll: Move retrieving the startup info to the Unix library.
[wine.git] / dlls / kernelbase / volume.c
blob9939ea3bef4ab8997ca1f636d6494b18756f0859
1 /*
2 * Volume management functions
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
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.
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.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <stdio.h>
29 #include "ntstatus.h"
30 #define WIN32_NO_STATUS
31 #include "windef.h"
32 #include "winbase.h"
33 #include "winnls.h"
34 #include "winternl.h"
35 #include "winioctl.h"
36 #include "ntddcdrm.h"
37 #define WINE_MOUNTMGR_EXTENSIONS
38 #include "ddk/mountmgr.h"
39 #include "ddk/wdm.h"
40 #include "kernelbase.h"
41 #include "wine/server.h"
42 #include "wine/debug.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(volume);
46 #define BLOCK_SIZE 2048
47 #define SUPERBLOCK_SIZE BLOCK_SIZE
48 #define SYMBOLIC_LINK_QUERY 0x0001
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)
55 #define GETWORD(buf,off) MAKEWORD(buf[(off)],buf[(off+1)])
56 #define GETLONG(buf,off) MAKELONG(GETWORD(buf,off),GETWORD(buf,off+2))
58 enum fs_type
60 FS_ERROR, /* error accessing the device */
61 FS_UNKNOWN, /* unknown file system */
62 FS_FAT1216,
63 FS_FAT32,
64 FS_ISO9660,
65 FS_UDF /* For reference [E] = Ecma-167.pdf, [U] = udf260.pdf */
68 /* read the contents of an NT symlink object */
69 static NTSTATUS read_nt_symlink( const WCHAR *name, WCHAR *target, DWORD size )
71 NTSTATUS status;
72 OBJECT_ATTRIBUTES attr;
73 UNICODE_STRING nameW;
74 HANDLE handle;
76 attr.Length = sizeof(attr);
77 attr.RootDirectory = 0;
78 attr.Attributes = OBJ_CASE_INSENSITIVE;
79 attr.ObjectName = &nameW;
80 attr.SecurityDescriptor = NULL;
81 attr.SecurityQualityOfService = NULL;
82 RtlInitUnicodeString( &nameW, name );
84 if (!(status = NtOpenSymbolicLinkObject( &handle, SYMBOLIC_LINK_QUERY, &attr )))
86 UNICODE_STRING targetW;
87 targetW.Buffer = target;
88 targetW.MaximumLength = (size - 1) * sizeof(WCHAR);
89 status = NtQuerySymbolicLinkObject( handle, &targetW, NULL );
90 if (!status) target[targetW.Length / sizeof(WCHAR)] = 0;
91 NtClose( handle );
93 return status;
96 /* open a handle to a device root */
97 static BOOL open_device_root( LPCWSTR root, HANDLE *handle )
99 UNICODE_STRING nt_name;
100 OBJECT_ATTRIBUTES attr;
101 IO_STATUS_BLOCK io;
102 NTSTATUS status;
104 if (!root) root = L"\\";
105 if (!RtlDosPathNameToNtPathName_U( root, &nt_name, NULL, NULL ))
107 SetLastError( ERROR_PATH_NOT_FOUND );
108 return FALSE;
110 attr.Length = sizeof(attr);
111 attr.RootDirectory = 0;
112 attr.Attributes = OBJ_CASE_INSENSITIVE;
113 attr.ObjectName = &nt_name;
114 attr.SecurityDescriptor = NULL;
115 attr.SecurityQualityOfService = NULL;
117 status = NtOpenFile( handle, SYNCHRONIZE, &attr, &io, 0,
118 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
119 RtlFreeUnicodeString( &nt_name );
120 return set_ntstatus( status );
123 /* query the type of a drive from the mount manager */
124 static DWORD get_mountmgr_drive_type( LPCWSTR root )
126 HANDLE mgr;
127 struct mountmgr_unix_drive data;
128 DWORD br;
130 memset( &data, 0, sizeof(data) );
131 if (root) data.letter = root[0];
132 else
134 WCHAR curdir[MAX_PATH];
135 GetCurrentDirectoryW( MAX_PATH, curdir );
136 if (curdir[1] != ':' || curdir[2] != '\\') return DRIVE_UNKNOWN;
137 data.letter = curdir[0];
140 mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, GENERIC_READ,
141 FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
142 if (mgr == INVALID_HANDLE_VALUE) return DRIVE_UNKNOWN;
144 if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_UNIX_DRIVE, &data, sizeof(data), &data,
145 sizeof(data), &br, NULL ) && GetLastError() != ERROR_MORE_DATA)
146 data.type = DRIVE_UNKNOWN;
148 CloseHandle( mgr );
149 return data.type;
152 /* get the label by reading it from a file at the root of the filesystem */
153 static void get_filesystem_label( const UNICODE_STRING *device, WCHAR *label, DWORD len )
155 static const WCHAR labelW[] = {'.','w','i','n','d','o','w','s','-','l','a','b','e','l',0};
156 HANDLE handle;
157 UNICODE_STRING name;
158 IO_STATUS_BLOCK io;
159 OBJECT_ATTRIBUTES attr;
161 label[0] = 0;
163 attr.Length = sizeof(attr);
164 attr.RootDirectory = 0;
165 attr.Attributes = OBJ_CASE_INSENSITIVE;
166 attr.ObjectName = &name;
167 attr.SecurityDescriptor = NULL;
168 attr.SecurityQualityOfService = NULL;
170 name.MaximumLength = device->Length + sizeof(labelW);
171 name.Length = name.MaximumLength - sizeof(WCHAR);
172 if (!(name.Buffer = HeapAlloc( GetProcessHeap(), 0, name.MaximumLength ))) return;
174 memcpy( name.Buffer, device->Buffer, device->Length );
175 memcpy( name.Buffer + device->Length / sizeof(WCHAR), labelW, sizeof(labelW) );
176 if (!NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_WRITE,
177 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))
179 char buffer[256], *p;
180 DWORD size;
182 if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
183 CloseHandle( handle );
184 p = buffer + size;
185 while (p > buffer && (p[-1] == ' ' || p[-1] == '\r' || p[-1] == '\n')) p--;
186 *p = 0;
187 if (!MultiByteToWideChar( CP_UNIXCP, 0, buffer, -1, label, len ))
188 label[len-1] = 0;
190 RtlFreeUnicodeString( &name );
193 /* get the serial number by reading it from a file at the root of the filesystem */
194 static DWORD get_filesystem_serial( const UNICODE_STRING *device )
196 static const WCHAR serialW[] = {'.','w','i','n','d','o','w','s','-','s','e','r','i','a','l',0};
197 HANDLE handle;
198 UNICODE_STRING name;
199 IO_STATUS_BLOCK io;
200 OBJECT_ATTRIBUTES attr;
201 DWORD ret = 0;
203 attr.Length = sizeof(attr);
204 attr.RootDirectory = 0;
205 attr.Attributes = OBJ_CASE_INSENSITIVE;
206 attr.ObjectName = &name;
207 attr.SecurityDescriptor = NULL;
208 attr.SecurityQualityOfService = NULL;
210 name.MaximumLength = device->Length + sizeof(serialW);
211 name.Length = name.MaximumLength - sizeof(WCHAR);
212 if (!(name.Buffer = HeapAlloc( GetProcessHeap(), 0, name.MaximumLength ))) return 0;
214 memcpy( name.Buffer, device->Buffer, device->Length );
215 memcpy( name.Buffer + device->Length / sizeof(WCHAR), serialW, sizeof(serialW) );
216 if (!NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ|FILE_SHARE_WRITE,
217 FILE_SYNCHRONOUS_IO_NONALERT ))
219 char buffer[32];
220 DWORD size;
222 if (!ReadFile( handle, buffer, sizeof(buffer)-1, &size, NULL )) size = 0;
223 CloseHandle( handle );
224 buffer[size] = 0;
225 ret = strtoul( buffer, NULL, 16 );
227 RtlFreeUnicodeString( &name );
228 return ret;
232 /******************************************************************
233 * find_cdrom_best_voldesc
235 static DWORD find_cdrom_best_voldesc( HANDLE handle )
237 BYTE cur_vd_type, max_vd_type = 0;
238 BYTE buffer[0x800];
239 DWORD size, offs, best_offs = 0, extra_offs = 0;
241 for (offs = 0x8000; offs <= 0x9800; offs += 0x800)
243 /* if 'CDROM' occurs at position 8, this is a pre-iso9660 cd, and
244 * the volume label is displaced forward by 8
246 if (SetFilePointer( handle, offs, NULL, FILE_BEGIN ) != offs) break;
247 if (!ReadFile( handle, buffer, sizeof(buffer), &size, NULL )) break;
248 if (size != sizeof(buffer)) break;
249 /* check for non-ISO9660 signature */
250 if (!memcmp( buffer + 11, "ROM", 3 )) extra_offs = 8;
251 cur_vd_type = buffer[extra_offs];
252 if (cur_vd_type == 0xff) /* voldesc set terminator */
253 break;
254 if (cur_vd_type > max_vd_type)
256 max_vd_type = cur_vd_type;
257 best_offs = offs + extra_offs;
260 return best_offs;
264 /***********************************************************************
265 * read_fat_superblock
267 static enum fs_type read_fat_superblock( HANDLE handle, BYTE *buff )
269 DWORD size;
271 /* try a fixed disk, with a FAT partition */
272 if (SetFilePointer( handle, 0, NULL, FILE_BEGIN ) != 0 ||
273 !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ))
275 if (GetLastError() == ERROR_BAD_DEV_TYPE) return FS_UNKNOWN; /* not a real device */
276 return FS_ERROR;
279 if (size < SUPERBLOCK_SIZE) return FS_UNKNOWN;
281 /* FIXME: do really all FAT have their name beginning with
282 * "FAT" ? (At least FAT12, FAT16 and FAT32 have :)
284 if (!memcmp(buff+0x36, "FAT", 3) || !memcmp(buff+0x52, "FAT", 3))
286 /* guess which type of FAT we have */
287 int reasonable;
288 unsigned int sectors,
289 sect_per_fat,
290 total_sectors,
291 num_boot_sectors,
292 num_fats,
293 num_root_dir_ents,
294 bytes_per_sector,
295 sectors_per_cluster,
296 nclust;
297 sect_per_fat = GETWORD(buff, 0x16);
298 if (!sect_per_fat) sect_per_fat = GETLONG(buff, 0x24);
299 total_sectors = GETWORD(buff, 0x13);
300 if (!total_sectors)
301 total_sectors = GETLONG(buff, 0x20);
302 num_boot_sectors = GETWORD(buff, 0x0e);
303 num_fats = buff[0x10];
304 num_root_dir_ents = GETWORD(buff, 0x11);
305 bytes_per_sector = GETWORD(buff, 0x0b);
306 sectors_per_cluster = buff[0x0d];
307 /* check if the parameters are reasonable and will not cause
308 * arithmetic errors in the calculation */
309 reasonable = num_boot_sectors < total_sectors &&
310 num_fats < 16 &&
311 bytes_per_sector >= 512 && bytes_per_sector % 512 == 0 &&
312 sectors_per_cluster >= 1;
313 if (!reasonable) return FS_UNKNOWN;
314 sectors = total_sectors - num_boot_sectors - num_fats * sect_per_fat -
315 (num_root_dir_ents * 32 + bytes_per_sector - 1) / bytes_per_sector;
316 nclust = sectors / sectors_per_cluster;
317 if ((buff[0x42] == 0x28 || buff[0x42] == 0x29) &&
318 !memcmp(buff+0x52, "FAT", 3)) return FS_FAT32;
319 if (nclust < 65525)
321 if ((buff[0x26] == 0x28 || buff[0x26] == 0x29) &&
322 !memcmp(buff+0x36, "FAT", 3))
323 return FS_FAT1216;
326 return FS_UNKNOWN;
330 /***********************************************************************
331 * read_cd_block
333 static BOOL read_cd_block( HANDLE handle, BYTE *buff, INT offs )
335 DWORD size, whence = offs >= 0 ? FILE_BEGIN : FILE_END;
337 if (SetFilePointer( handle, offs, NULL, whence ) != offs ||
338 !ReadFile( handle, buff, SUPERBLOCK_SIZE, &size, NULL ) ||
339 size != SUPERBLOCK_SIZE)
340 return FALSE;
342 return TRUE;
346 /***********************************************************************
347 * read_cd_superblock
349 static enum fs_type read_cd_superblock( HANDLE handle, BYTE *buff )
351 int i;
352 DWORD offs;
354 /* Check UDF first as UDF and ISO9660 structures can coexist on the same medium
355 * Starting from sector 16, we may find :
356 * - a CD-ROM Volume Descriptor Set (ISO9660) containing one or more Volume Descriptors
357 * - an Extended Area (UDF) -- [E] 2/8.3.1 and [U] 2.1.7
358 * There is no explicit end so read 16 sectors and then give up */
359 for( i=16; i<16+16; i++)
361 if (!read_cd_block(handle, buff, i*BLOCK_SIZE))
362 continue;
364 /* We are supposed to check "BEA01", "NSR0x" and "TEA01" IDs + verify tag checksum
365 * but we assume the volume is well-formatted */
366 if (!memcmp(&buff[1], "BEA01", 5)) return FS_UDF;
369 offs = find_cdrom_best_voldesc( handle );
370 if (!offs) return FS_UNKNOWN;
372 if (!read_cd_block(handle, buff, offs))
373 return FS_ERROR;
375 /* check for the iso9660 identifier */
376 if (!memcmp(&buff[1], "CD001", 5)) return FS_ISO9660;
377 return FS_UNKNOWN;
381 /**************************************************************************
382 * udf_find_pvd
384 static BOOL udf_find_pvd( HANDLE handle, BYTE pvd[] )
386 unsigned int i;
387 DWORD offset;
388 INT locations[] = { 256, -1, -257, 512 };
390 for(i=0; i<ARRAY_SIZE(locations); i++)
392 if (!read_cd_block(handle, pvd, locations[i]*BLOCK_SIZE))
393 return FALSE;
395 /* Tag Identifier of Anchor Volume Descriptor Pointer is 2 -- [E] 3/10.2.1 */
396 if (pvd[0]==2 && pvd[1]==0)
398 /* Tag location (Uint32) at offset 12, little-endian */
399 offset = pvd[20 + 0];
400 offset |= pvd[20 + 1] << 8;
401 offset |= pvd[20 + 2] << 16;
402 offset |= pvd[20 + 3] << 24;
403 offset *= BLOCK_SIZE;
405 if (!read_cd_block(handle, pvd, offset))
406 return FALSE;
408 /* Check for the Primary Volume Descriptor Tag Id -- [E] 3/10.1.1 */
409 if (pvd[0]!=1 || pvd[1]!=0)
410 return FALSE;
412 /* 8 or 16 bits per character -- [U] 2.1.1 */
413 if (!(pvd[24]==8 || pvd[24]==16))
414 return FALSE;
416 return TRUE;
420 return FALSE;
424 /**************************************************************************
425 * get_superblock_label
427 static void get_superblock_label( const UNICODE_STRING *device, HANDLE handle,
428 enum fs_type type, const BYTE *superblock,
429 WCHAR *label, DWORD len )
431 const BYTE *label_ptr = NULL;
432 DWORD label_len;
434 switch(type)
436 case FS_ERROR:
437 label_len = 0;
438 break;
439 case FS_UNKNOWN:
440 get_filesystem_label( device, label, len );
441 return;
442 case FS_FAT1216:
443 label_ptr = superblock + 0x2b;
444 label_len = 11;
445 break;
446 case FS_FAT32:
447 label_ptr = superblock + 0x47;
448 label_len = 11;
449 break;
450 case FS_ISO9660:
452 BYTE ver = superblock[0x5a];
454 if (superblock[0x58] == 0x25 && superblock[0x59] == 0x2f && /* Unicode ID */
455 ((ver == 0x40) || (ver == 0x43) || (ver == 0x45)))
456 { /* yippee, unicode */
457 unsigned int i;
459 if (len > 17) len = 17;
460 for (i = 0; i < len-1; i++)
461 label[i] = (superblock[40+2*i] << 8) | superblock[41+2*i];
462 label[i] = 0;
463 while (i && label[i-1] == ' ') label[--i] = 0;
464 return;
466 label_ptr = superblock + 40;
467 label_len = 32;
468 break;
470 case FS_UDF:
472 BYTE pvd[BLOCK_SIZE];
474 if(!udf_find_pvd(handle, pvd))
476 label_len = 0;
477 break;
480 /* [E] 3/10.1.4 and [U] 2.1.1 */
481 if(pvd[24]==8)
483 label_ptr = pvd + 24 + 1;
484 label_len = pvd[24+32-1];
485 break;
487 else
489 unsigned int i;
491 label_len = 1 + pvd[24+32-1];
492 for(i=0; i<label_len && i<len; i+=2)
493 label[i/2] = (pvd[24+1 +i] << 8) | pvd[24+1 +i+1];
494 label[label_len] = 0;
495 return;
499 if (label_len) RtlMultiByteToUnicodeN( label, (len-1) * sizeof(WCHAR),
500 &label_len, (LPCSTR)label_ptr, label_len );
501 label_len /= sizeof(WCHAR);
502 label[label_len] = 0;
503 while (label_len && label[label_len-1] == ' ') label[--label_len] = 0;
507 /**************************************************************************
508 * udf_find_fsd_sector
510 static int udf_find_fsd_sector( HANDLE handle, BYTE block[] )
512 int i, PVD_sector, PD_sector, PD_length;
514 if(!udf_find_pvd(handle,block))
515 goto default_sector;
517 /* Retrieve the tag location of the PVD -- [E] 3/7.2 */
518 PVD_sector = block[12 + 0];
519 PVD_sector |= block[12 + 1] << 8;
520 PVD_sector |= block[12 + 2] << 16;
521 PVD_sector |= block[12 + 3] << 24;
523 /* Find the Partition Descriptor */
524 for(i=PVD_sector+1; ; i++)
526 if(!read_cd_block(handle, block, i*BLOCK_SIZE))
527 goto default_sector;
529 /* Partition Descriptor Tag Id -- [E] 3/10.5.1 */
530 if(block[0]==5 && block[1]==0)
531 break;
533 /* Terminating Descriptor Tag Id -- [E] 3/10.9.1 */
534 if(block[0]==8 && block[1]==0)
535 goto default_sector;
538 /* Find the partition starting location -- [E] 3/10.5.8 */
539 PD_sector = block[188 + 0];
540 PD_sector |= block[188 + 1] << 8;
541 PD_sector |= block[188 + 2] << 16;
542 PD_sector |= block[188 + 3] << 24;
544 /* Find the partition length -- [E] 3/10.5.9 */
545 PD_length = block[192 + 0];
546 PD_length |= block[192 + 1] << 8;
547 PD_length |= block[192 + 2] << 16;
548 PD_length |= block[192 + 3] << 24;
550 for(i=PD_sector; i<PD_sector+PD_length; i++)
552 if(!read_cd_block(handle, block, i*BLOCK_SIZE))
553 goto default_sector;
555 /* File Set Descriptor Tag Id -- [E] 3/14.1.1 */
556 if(block[0]==0 && block[1]==1)
557 return i;
560 default_sector:
561 WARN("FSD sector not found, serial may be incorrect\n");
562 return 257;
566 /**************************************************************************
567 * get_superblock_serial
569 static DWORD get_superblock_serial( const UNICODE_STRING *device, HANDLE handle,
570 enum fs_type type, const BYTE *superblock )
572 int FSD_sector;
573 BYTE block[BLOCK_SIZE];
575 switch(type)
577 case FS_ERROR:
578 break;
579 case FS_UNKNOWN:
580 return get_filesystem_serial( device );
581 case FS_FAT1216:
582 return GETLONG( superblock, 0x27 );
583 case FS_FAT32:
584 return GETLONG( superblock, 0x33 );
585 case FS_UDF:
586 FSD_sector = udf_find_fsd_sector(handle, block);
587 if (!read_cd_block(handle, block, FSD_sector*BLOCK_SIZE))
588 break;
589 superblock = block;
590 /* fallthrough */
591 case FS_ISO9660:
593 BYTE sum[4];
594 int i;
596 sum[0] = sum[1] = sum[2] = sum[3] = 0;
597 for (i = 0; i < 2048; i += 4)
599 /* DON'T optimize this into DWORD !! (breaks overflow) */
600 sum[0] += superblock[i+0];
601 sum[1] += superblock[i+1];
602 sum[2] += superblock[i+2];
603 sum[3] += superblock[i+3];
606 * OK, another braindead one... argh. Just believe it.
607 * Me$$ysoft chose to reverse the serial number in NT4/W2K.
608 * It's true and nobody will ever be able to change it.
610 if ((GetVersion() & 0x80000000) || type == FS_UDF)
611 return (sum[3] << 24) | (sum[2] << 16) | (sum[1] << 8) | sum[0];
612 else
613 return (sum[0] << 24) | (sum[1] << 16) | (sum[2] << 8) | sum[3];
616 return 0;
620 /**************************************************************************
621 * get_audiocd_serial
623 static DWORD get_audiocd_serial( const CDROM_TOC *toc )
625 DWORD serial = 0;
626 int i;
628 for (i = 0; i <= toc->LastTrack - toc->FirstTrack; i++)
629 serial += ((toc->TrackData[i].Address[1] << 16) |
630 (toc->TrackData[i].Address[2] << 8) |
631 toc->TrackData[i].Address[3]);
634 * dwStart, dwEnd collect the beginning and end of the disc respectively, in
635 * frames.
636 * There it is collected for correcting the serial when there are less than
637 * 3 tracks.
639 if (toc->LastTrack - toc->FirstTrack + 1 < 3)
641 DWORD dwStart = FRAME_OF_TOC(toc, toc->FirstTrack);
642 DWORD dwEnd = FRAME_OF_TOC(toc, toc->LastTrack + 1);
643 serial += dwEnd - dwStart;
645 return serial;
649 /***********************************************************************
650 * GetVolumeInformationW (kernelbase.@)
652 BOOL WINAPI DECLSPEC_HOTPATCH GetVolumeInformationW( LPCWSTR root, LPWSTR label, DWORD label_len,
653 DWORD *serial, DWORD *filename_len, DWORD *flags,
654 LPWSTR fsname, DWORD fsname_len )
656 HANDLE handle;
657 NTSTATUS status;
658 UNICODE_STRING nt_name;
659 IO_STATUS_BLOCK io;
660 OBJECT_ATTRIBUTES attr;
661 FILE_FS_DEVICE_INFORMATION info;
662 unsigned int i;
663 enum fs_type type = FS_UNKNOWN;
664 BOOL ret = FALSE;
666 if (!root) root = L"\\";
667 if (!RtlDosPathNameToNtPathName_U( root, &nt_name, NULL, NULL ))
669 SetLastError( ERROR_PATH_NOT_FOUND );
670 return FALSE;
672 /* there must be exactly one backslash in the name, at the end */
673 for (i = 4; i < nt_name.Length / sizeof(WCHAR); i++) if (nt_name.Buffer[i] == '\\') break;
674 if (i != nt_name.Length / sizeof(WCHAR) - 1)
676 /* check if root contains an explicit subdir */
677 if (root[0] && root[1] == ':') root += 2;
678 while (*root == '\\') root++;
679 if (wcschr( root, '\\' ))
680 SetLastError( ERROR_DIR_NOT_ROOT );
681 else
682 SetLastError( ERROR_INVALID_NAME );
683 goto done;
686 /* try to open the device */
688 attr.Length = sizeof(attr);
689 attr.RootDirectory = 0;
690 attr.Attributes = OBJ_CASE_INSENSITIVE;
691 attr.ObjectName = &nt_name;
692 attr.SecurityDescriptor = NULL;
693 attr.SecurityQualityOfService = NULL;
695 nt_name.Length -= sizeof(WCHAR); /* without trailing slash */
696 status = NtOpenFile( &handle, GENERIC_READ | SYNCHRONIZE, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE,
697 FILE_NON_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT );
698 nt_name.Length += sizeof(WCHAR);
700 if (status == STATUS_SUCCESS)
702 BYTE superblock[SUPERBLOCK_SIZE];
703 CDROM_TOC toc;
704 DWORD br;
706 /* check for audio CD */
707 /* FIXME: we only check the first track for now */
708 if (DeviceIoControl( handle, IOCTL_CDROM_READ_TOC, NULL, 0, &toc, sizeof(toc), &br, 0 ))
710 if (!(toc.TrackData[0].Control & 0x04)) /* audio track */
712 TRACE( "%s: found audio CD\n", debugstr_w(nt_name.Buffer) );
713 if (label) lstrcpynW( label, L"Audio CD", label_len );
714 if (serial) *serial = get_audiocd_serial( &toc );
715 CloseHandle( handle );
716 type = FS_ISO9660;
717 goto fill_fs_info;
719 type = read_cd_superblock( handle, superblock );
721 else
723 type = read_fat_superblock( handle, superblock );
724 if (type == FS_UNKNOWN) type = read_cd_superblock( handle, superblock );
726 TRACE( "%s: found fs type %d\n", debugstr_w(nt_name.Buffer), type );
727 if (type == FS_ERROR)
729 CloseHandle( handle );
730 goto done;
733 if (label && label_len) get_superblock_label( &nt_name, handle, type, superblock, label, label_len );
734 if (serial) *serial = get_superblock_serial( &nt_name, handle, type, superblock );
735 CloseHandle( handle );
736 goto fill_fs_info;
738 else
740 TRACE( "cannot open device %s: %x\n", debugstr_w(nt_name.Buffer), status );
741 if (status == STATUS_ACCESS_DENIED)
742 MESSAGE( "wine: Read access denied for device %s, FS volume label and serial are not available.\n", debugstr_w(nt_name.Buffer) );
744 /* we couldn't open the device, fallback to default strategy */
746 if (!set_ntstatus( NtOpenFile( &handle, SYNCHRONIZE, &attr, &io, 0,
747 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT )))
748 goto done;
750 status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsDeviceInformation );
751 NtClose( handle );
752 if (!set_ntstatus( status )) goto done;
754 if (info.DeviceType == FILE_DEVICE_CD_ROM_FILE_SYSTEM) type = FS_ISO9660;
756 if (label && label_len) get_filesystem_label( &nt_name, label, label_len );
757 if (serial) *serial = get_filesystem_serial( &nt_name );
759 fill_fs_info: /* now fill in the information that depends on the file system type */
761 switch(type)
763 case FS_ISO9660:
764 if (fsname) lstrcpynW( fsname, L"CDFS", fsname_len );
765 if (filename_len) *filename_len = 221;
766 if (flags) *flags = FILE_READ_ONLY_VOLUME;
767 break;
768 case FS_UDF:
769 if (fsname) lstrcpynW( fsname, L"UDF", fsname_len );
770 if (filename_len) *filename_len = 255;
771 if (flags)
772 *flags = FILE_READ_ONLY_VOLUME | FILE_UNICODE_ON_DISK | FILE_CASE_SENSITIVE_SEARCH;
773 break;
774 case FS_FAT1216:
775 if (fsname) lstrcpynW( fsname, L"FAT", fsname_len );
776 case FS_FAT32:
777 if (type == FS_FAT32 && fsname) lstrcpynW( fsname, L"FAT32", fsname_len );
778 if (filename_len) *filename_len = 255;
779 if (flags) *flags = FILE_CASE_PRESERVED_NAMES; /* FIXME */
780 break;
781 default:
782 if (fsname) lstrcpynW( fsname, L"NTFS", fsname_len );
783 if (filename_len) *filename_len = 255;
784 if (flags) *flags = FILE_CASE_PRESERVED_NAMES | FILE_PERSISTENT_ACLS;
785 break;
787 ret = TRUE;
789 done:
790 RtlFreeUnicodeString( &nt_name );
791 return ret;
795 /***********************************************************************
796 * GetVolumeInformationA (kernelbase.@)
798 BOOL WINAPI GetVolumeInformationA( LPCSTR root, LPSTR label,
799 DWORD label_len, DWORD *serial,
800 DWORD *filename_len, DWORD *flags,
801 LPSTR fsname, DWORD fsname_len )
803 WCHAR *rootW = NULL;
804 LPWSTR labelW, fsnameW;
805 BOOL ret;
807 if (root && !(rootW = file_name_AtoW( root, FALSE ))) return FALSE;
809 labelW = label ? HeapAlloc(GetProcessHeap(), 0, label_len * sizeof(WCHAR)) : NULL;
810 fsnameW = fsname ? HeapAlloc(GetProcessHeap(), 0, fsname_len * sizeof(WCHAR)) : NULL;
812 if ((ret = GetVolumeInformationW(rootW, labelW, label_len, serial,
813 filename_len, flags, fsnameW, fsname_len)))
815 if (label) file_name_WtoA( labelW, -1, label, label_len );
816 if (fsname) file_name_WtoA( fsnameW, -1, fsname, fsname_len );
819 HeapFree( GetProcessHeap(), 0, labelW );
820 HeapFree( GetProcessHeap(), 0, fsnameW );
821 return ret;
825 /***********************************************************************
826 * GetVolumeNameForVolumeMountPointW (kernelbase.@)
828 BOOL WINAPI GetVolumeNameForVolumeMountPointW( LPCWSTR path, LPWSTR volume, DWORD size )
830 MOUNTMGR_MOUNT_POINT *input = NULL, *o1;
831 MOUNTMGR_MOUNT_POINTS *output = NULL;
832 WCHAR *p;
833 char *r;
834 DWORD i, i_size = 1024, o_size = 1024;
835 WCHAR *nonpersist_name;
836 WCHAR symlink_name[MAX_PATH];
837 NTSTATUS status;
838 HANDLE mgr = INVALID_HANDLE_VALUE;
839 BOOL ret = FALSE;
840 DWORD br;
842 TRACE("(%s, %p, %x)\n", debugstr_w(path), volume, size);
843 if (path[lstrlenW(path)-1] != '\\')
845 SetLastError( ERROR_INVALID_NAME );
846 return FALSE;
849 if (size < 50)
851 SetLastError( ERROR_FILENAME_EXCED_RANGE );
852 return FALSE;
854 /* if length of input is > 3 then it must be a mounted folder */
855 if (lstrlenW(path) > 3)
857 FIXME("Mounted Folders are not yet supported\n");
858 SetLastError( ERROR_NOT_A_REPARSE_POINT );
859 return FALSE;
862 mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ,
863 NULL, OPEN_EXISTING, 0, 0 );
864 if (mgr == INVALID_HANDLE_VALUE) return FALSE;
866 if (!(input = HeapAlloc( GetProcessHeap(), 0, i_size )))
868 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
869 goto err_ret;
872 if (!(output = HeapAlloc( GetProcessHeap(), 0, o_size )))
874 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
875 goto err_ret;
878 /* construct the symlink name as "\DosDevices\C:" */
879 lstrcpyW( symlink_name, L"\\DosDevices\\" );
880 lstrcatW( symlink_name, path );
881 symlink_name[lstrlenW(symlink_name)-1] = 0;
883 /* Take the mount point and get the "nonpersistent name" */
884 /* We will then take that and get the volume name */
885 nonpersist_name = (WCHAR *)(input + 1);
886 status = read_nt_symlink( symlink_name, nonpersist_name, i_size - sizeof(*input) );
887 TRACE("read_nt_symlink got stat=%x, for %s, got <%s>\n", status,
888 debugstr_w(symlink_name), debugstr_w(nonpersist_name));
889 if (status != STATUS_SUCCESS)
891 SetLastError( ERROR_FILE_NOT_FOUND );
892 goto err_ret;
895 /* Now take the "nonpersistent name" and ask the mountmgr */
896 /* to give us all the mount points. One of them will be */
897 /* the volume name (format of \??\Volume{). */
898 memset( input, 0, sizeof(*input) ); /* clear all input parameters */
899 input->DeviceNameOffset = sizeof(*input);
900 input->DeviceNameLength = lstrlenW( nonpersist_name) * sizeof(WCHAR);
901 i_size = input->DeviceNameOffset + input->DeviceNameLength;
903 output->Size = o_size;
905 /* now get the true volume name from the mountmgr */
906 if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, input, i_size,
907 output, o_size, &br, NULL ))
908 goto err_ret;
910 /* Verify and return the data, note string is not null terminated */
911 TRACE("found %d matching mount points\n", output->NumberOfMountPoints);
912 if (output->NumberOfMountPoints < 1)
914 SetLastError( ERROR_NO_VOLUME_ID );
915 goto err_ret;
917 o1 = &output->MountPoints[0];
919 /* look for the volume name in returned values */
920 for(i=0;i<output->NumberOfMountPoints;i++)
922 p = (WCHAR*)((char *)output + o1->SymbolicLinkNameOffset);
923 r = (char *)output + o1->UniqueIdOffset;
924 TRACE("found symlink=%s, unique=%s, devname=%s\n",
925 debugstr_wn(p, o1->SymbolicLinkNameLength/sizeof(WCHAR)),
926 debugstr_an(r, o1->UniqueIdLength),
927 debugstr_wn((WCHAR*)((char *)output + o1->DeviceNameOffset),
928 o1->DeviceNameLength/sizeof(WCHAR)));
930 if (!wcsncmp( p, L"\\??\\Volume{", wcslen(L"\\??\\Volume{") ))
932 /* is there space in the return variable ?? */
933 if ((o1->SymbolicLinkNameLength/sizeof(WCHAR))+2 > size)
935 SetLastError( ERROR_FILENAME_EXCED_RANGE );
936 goto err_ret;
938 memcpy( volume, p, o1->SymbolicLinkNameLength );
939 volume[o1->SymbolicLinkNameLength / sizeof(WCHAR)] = 0;
940 lstrcatW( volume, L"\\" );
941 /* change second char from '?' to '\' */
942 volume[1] = '\\';
943 ret = TRUE;
944 break;
946 o1++;
949 err_ret:
950 HeapFree( GetProcessHeap(), 0, input );
951 HeapFree( GetProcessHeap(), 0, output );
952 CloseHandle( mgr );
953 return ret;
957 /***********************************************************************
958 * DefineDosDeviceW (kernelbase.@)
960 BOOL WINAPI DECLSPEC_HOTPATCH DefineDosDeviceW( DWORD flags, const WCHAR *device, const WCHAR *target )
962 WCHAR link_name[15] = L"\\DosDevices\\";
963 UNICODE_STRING nt_name, nt_target;
964 OBJECT_ATTRIBUTES attr;
965 NTSTATUS status;
966 HANDLE handle;
968 TRACE("%#x, %s, %s\n", flags, debugstr_w(device), debugstr_w(target));
970 if (flags & ~(DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION))
971 FIXME("Ignoring flags %#x.\n", flags & ~(DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION));
973 lstrcatW( link_name, device );
974 RtlInitUnicodeString( &nt_name, link_name );
975 InitializeObjectAttributes( &attr, &nt_name, OBJ_CASE_INSENSITIVE, 0, NULL );
976 if (flags & DDD_REMOVE_DEFINITION)
978 if (!set_ntstatus( NtOpenSymbolicLinkObject( &handle, 0, &attr ) ))
979 return FALSE;
981 SERVER_START_REQ( unlink_object )
983 req->handle = wine_server_obj_handle( handle );
984 status = wine_server_call( req );
986 SERVER_END_REQ;
987 NtClose( handle );
989 return set_ntstatus( status );
992 if (!(flags & DDD_RAW_TARGET_PATH))
994 if (!RtlDosPathNameToNtPathName_U( target, &nt_target, NULL, NULL))
996 SetLastError( ERROR_PATH_NOT_FOUND );
997 return FALSE;
1000 else
1001 RtlInitUnicodeString( &nt_target, target );
1003 return set_ntstatus( NtCreateSymbolicLinkObject( &handle, SYMBOLIC_LINK_ALL_ACCESS, &attr, &nt_target ) );
1007 /***********************************************************************
1008 * QueryDosDeviceW (kernelbase.@)
1010 * returns array of strings terminated by \0, terminated by \0
1012 DWORD WINAPI QueryDosDeviceW( LPCWSTR devname, LPWSTR target, DWORD bufsize )
1014 UNICODE_STRING nt_name;
1015 NTSTATUS status;
1017 if (!bufsize)
1019 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1020 return 0;
1023 if (devname)
1025 WCHAR name[8];
1026 WCHAR *buffer;
1027 DWORD dosdev, ret = 0;
1029 if ((dosdev = RtlIsDosDeviceName_U( devname )))
1031 memcpy( name, devname + HIWORD(dosdev)/sizeof(WCHAR), LOWORD(dosdev) );
1032 name[LOWORD(dosdev)/sizeof(WCHAR)] = 0;
1033 devname = name;
1036 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, sizeof(L"\\DosDevices\\") + lstrlenW(devname)*sizeof(WCHAR) )))
1038 SetLastError( ERROR_OUTOFMEMORY );
1039 return 0;
1041 lstrcpyW( buffer, L"\\DosDevices\\" );
1042 lstrcatW( buffer, devname );
1043 status = read_nt_symlink( buffer, target, bufsize );
1044 HeapFree( GetProcessHeap(), 0, buffer );
1045 if (!set_ntstatus( status )) return 0;
1046 ret = lstrlenW( target ) + 1;
1047 if (ret < bufsize) target[ret++] = 0; /* add an extra null */
1048 return ret;
1050 else /* return a list of all devices */
1052 OBJECT_ATTRIBUTES attr;
1053 HANDLE handle;
1054 WCHAR *p = target;
1056 RtlInitUnicodeString( &nt_name, L"\\DosDevices\\" );
1057 nt_name.Length -= sizeof(WCHAR); /* without trailing slash */
1058 attr.Length = sizeof(attr);
1059 attr.RootDirectory = 0;
1060 attr.ObjectName = &nt_name;
1061 attr.Attributes = OBJ_CASE_INSENSITIVE;
1062 attr.SecurityDescriptor = NULL;
1063 attr.SecurityQualityOfService = NULL;
1064 status = NtOpenDirectoryObject( &handle, FILE_LIST_DIRECTORY, &attr );
1065 if (!status)
1067 char data[1024];
1068 DIRECTORY_BASIC_INFORMATION *info = (DIRECTORY_BASIC_INFORMATION *)data;
1069 ULONG ctx = 0, len;
1071 while (!NtQueryDirectoryObject( handle, info, sizeof(data), 1, 0, &ctx, &len ))
1073 if (p + info->ObjectName.Length/sizeof(WCHAR) + 1 >= target + bufsize)
1075 SetLastError( ERROR_INSUFFICIENT_BUFFER );
1076 NtClose( handle );
1077 return 0;
1079 memcpy( p, info->ObjectName.Buffer, info->ObjectName.Length );
1080 p += info->ObjectName.Length/sizeof(WCHAR);
1081 *p++ = 0;
1083 NtClose( handle );
1086 *p++ = 0; /* terminating null */
1087 return p - target;
1092 /***********************************************************************
1093 * GetLogicalDrives (kernelbase.@)
1095 DWORD WINAPI DECLSPEC_HOTPATCH GetLogicalDrives(void)
1097 OBJECT_ATTRIBUTES attr;
1098 UNICODE_STRING nt_name;
1099 DWORD bitmask = 0;
1100 NTSTATUS status;
1101 HANDLE handle;
1103 RtlInitUnicodeString( &nt_name, L"\\DosDevices\\" );
1104 nt_name.Length -= sizeof(WCHAR); /* without trailing slash */
1105 attr.Length = sizeof(attr);
1106 attr.RootDirectory = 0;
1107 attr.ObjectName = &nt_name;
1108 attr.Attributes = OBJ_CASE_INSENSITIVE;
1109 attr.SecurityDescriptor = NULL;
1110 attr.SecurityQualityOfService = NULL;
1111 status = NtOpenDirectoryObject( &handle, FILE_LIST_DIRECTORY, &attr );
1112 if (!status)
1114 char data[1024];
1115 DIRECTORY_BASIC_INFORMATION *info = (DIRECTORY_BASIC_INFORMATION *)data;
1116 ULONG ctx = 0, len;
1118 while (!NtQueryDirectoryObject( handle, info, sizeof(data), 1, 0, &ctx, &len ))
1119 if(info->ObjectName.Length == 2*sizeof(WCHAR) && info->ObjectName.Buffer[1] == ':')
1120 bitmask |= 1 << (info->ObjectName.Buffer[0] - 'A');
1122 NtClose( handle );
1125 return bitmask;
1129 /***********************************************************************
1130 * GetLogicalDriveStringsW (kernelbase.@)
1132 UINT WINAPI DECLSPEC_HOTPATCH GetLogicalDriveStringsW( UINT len, LPWSTR buffer )
1134 DWORD drives = GetLogicalDrives();
1135 UINT drive, count;
1137 for (drive = count = 0; drive < 26; drive++) if (drives & (1 << drive)) count++;
1138 if ((count * 4) + 1 > len) return count * 4 + 1;
1140 for (drive = 0; drive < 26; drive++)
1142 if (drives & (1 << drive))
1144 *buffer++ = 'A' + drive;
1145 *buffer++ = ':';
1146 *buffer++ = '\\';
1147 *buffer++ = 0;
1150 *buffer = 0;
1151 return count * 4;
1155 /***********************************************************************
1156 * GetDriveTypeW (kernelbase.@)
1158 UINT WINAPI DECLSPEC_HOTPATCH GetDriveTypeW( LPCWSTR root )
1160 FILE_FS_DEVICE_INFORMATION info;
1161 IO_STATUS_BLOCK io;
1162 NTSTATUS status;
1163 HANDLE handle;
1164 UINT ret;
1166 if (!open_device_root( root, &handle ))
1168 /* CD ROM devices do not necessarily have a volume, but a drive type */
1169 ret = get_mountmgr_drive_type( root );
1170 if (ret == DRIVE_CDROM || ret == DRIVE_REMOVABLE)
1171 return ret;
1173 return DRIVE_NO_ROOT_DIR;
1176 status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsDeviceInformation );
1177 NtClose( handle );
1178 if (status != STATUS_SUCCESS)
1180 SetLastError( RtlNtStatusToDosError(status) );
1181 ret = DRIVE_UNKNOWN;
1183 else
1185 switch (info.DeviceType)
1187 case FILE_DEVICE_CD_ROM_FILE_SYSTEM: ret = DRIVE_CDROM; break;
1188 case FILE_DEVICE_VIRTUAL_DISK: ret = DRIVE_RAMDISK; break;
1189 case FILE_DEVICE_NETWORK_FILE_SYSTEM: ret = DRIVE_REMOTE; break;
1190 case FILE_DEVICE_DISK_FILE_SYSTEM:
1191 if (info.Characteristics & FILE_REMOTE_DEVICE) ret = DRIVE_REMOTE;
1192 else if (info.Characteristics & FILE_REMOVABLE_MEDIA) ret = DRIVE_REMOVABLE;
1193 else if ((ret = get_mountmgr_drive_type( root )) == DRIVE_UNKNOWN) ret = DRIVE_FIXED;
1194 break;
1195 default:
1196 ret = DRIVE_UNKNOWN;
1197 break;
1200 TRACE( "%s -> %d\n", debugstr_w(root), ret );
1201 return ret;
1205 /***********************************************************************
1206 * GetDriveTypeA (kernelbase.@)
1208 UINT WINAPI DECLSPEC_HOTPATCH GetDriveTypeA( LPCSTR root )
1210 WCHAR *rootW = NULL;
1212 if (root && !(rootW = file_name_AtoW( root, FALSE ))) return DRIVE_NO_ROOT_DIR;
1213 return GetDriveTypeW( rootW );
1217 /***********************************************************************
1218 * GetDiskFreeSpaceExW (kernelbase.@)
1220 BOOL WINAPI DECLSPEC_HOTPATCH GetDiskFreeSpaceExW( LPCWSTR root, PULARGE_INTEGER avail,
1221 PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1223 FILE_FS_SIZE_INFORMATION info;
1224 IO_STATUS_BLOCK io;
1225 NTSTATUS status;
1226 HANDLE handle;
1227 UINT units;
1229 TRACE( "%s,%p,%p,%p\n", debugstr_w(root), avail, total, totalfree );
1231 if (!open_device_root( root, &handle )) return FALSE;
1233 status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1234 NtClose( handle );
1235 if (!set_ntstatus( status )) return FALSE;
1237 units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1238 if (total) total->QuadPart = info.TotalAllocationUnits.QuadPart * units;
1239 if (totalfree) totalfree->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1240 /* FIXME: this one should take quotas into account */
1241 if (avail) avail->QuadPart = info.AvailableAllocationUnits.QuadPart * units;
1242 return TRUE;
1246 /***********************************************************************
1247 * GetDiskFreeSpaceExA (kernelbase.@)
1249 BOOL WINAPI DECLSPEC_HOTPATCH GetDiskFreeSpaceExA( LPCSTR root, PULARGE_INTEGER avail,
1250 PULARGE_INTEGER total, PULARGE_INTEGER totalfree )
1252 WCHAR *rootW = NULL;
1254 if (root && !(rootW = file_name_AtoW( root, FALSE ))) return FALSE;
1255 return GetDiskFreeSpaceExW( rootW, avail, total, totalfree );
1259 /***********************************************************************
1260 * GetDiskFreeSpaceW (kernelbase.@)
1262 BOOL WINAPI DECLSPEC_HOTPATCH GetDiskFreeSpaceW( LPCWSTR root, LPDWORD cluster_sectors,
1263 LPDWORD sector_bytes, LPDWORD free_clusters,
1264 LPDWORD total_clusters )
1266 FILE_FS_SIZE_INFORMATION info;
1267 IO_STATUS_BLOCK io;
1268 NTSTATUS status;
1269 HANDLE handle;
1270 UINT units;
1272 TRACE( "%s,%p,%p,%p,%p\n", debugstr_w(root),
1273 cluster_sectors, sector_bytes, free_clusters, total_clusters );
1275 if (!open_device_root( root, &handle )) return FALSE;
1277 status = NtQueryVolumeInformationFile( handle, &io, &info, sizeof(info), FileFsSizeInformation );
1278 NtClose( handle );
1279 if (!set_ntstatus( status )) return FALSE;
1281 units = info.SectorsPerAllocationUnit * info.BytesPerSector;
1283 if( GetVersion() & 0x80000000) { /* win3.x, 9x, ME */
1284 /* cap the size and available at 2GB as per specs */
1285 if (info.TotalAllocationUnits.QuadPart * units > 0x7fffffff) {
1286 info.TotalAllocationUnits.QuadPart = 0x7fffffff / units;
1287 if (info.AvailableAllocationUnits.QuadPart * units > 0x7fffffff)
1288 info.AvailableAllocationUnits.QuadPart = 0x7fffffff / units;
1290 /* nr. of clusters is always <= 65335 */
1291 while( info.TotalAllocationUnits.QuadPart > 65535 ) {
1292 info.TotalAllocationUnits.QuadPart /= 2;
1293 info.AvailableAllocationUnits.QuadPart /= 2;
1294 info.SectorsPerAllocationUnit *= 2;
1298 if (cluster_sectors) *cluster_sectors = info.SectorsPerAllocationUnit;
1299 if (sector_bytes) *sector_bytes = info.BytesPerSector;
1300 if (free_clusters) *free_clusters = info.AvailableAllocationUnits.u.LowPart;
1301 if (total_clusters) *total_clusters = info.TotalAllocationUnits.u.LowPart;
1302 TRACE("%#08x, %#08x, %#08x, %#08x\n", info.SectorsPerAllocationUnit, info.BytesPerSector,
1303 info.AvailableAllocationUnits.u.LowPart, info.TotalAllocationUnits.u.LowPart);
1304 return TRUE;
1308 /***********************************************************************
1309 * GetDiskFreeSpaceA (kernelbase.@)
1311 BOOL WINAPI DECLSPEC_HOTPATCH GetDiskFreeSpaceA( LPCSTR root, LPDWORD cluster_sectors,
1312 LPDWORD sector_bytes, LPDWORD free_clusters,
1313 LPDWORD total_clusters )
1315 WCHAR *rootW = NULL;
1317 if (root && !(rootW = file_name_AtoW( root, FALSE ))) return FALSE;
1318 return GetDiskFreeSpaceW( rootW, cluster_sectors, sector_bytes, free_clusters, total_clusters );
1322 static BOOL is_dos_path( const UNICODE_STRING *path )
1324 static const WCHAR global_prefix[4] = {'\\','?','?','\\'};
1325 return path->Length >= 7 * sizeof(WCHAR)
1326 && !memcmp(path->Buffer, global_prefix, sizeof(global_prefix))
1327 && path->Buffer[5] == ':' && path->Buffer[6] == '\\';
1330 /* resolve all symlinks in a path in-place; return FALSE if allocation failed */
1331 static BOOL resolve_symlink( UNICODE_STRING *path )
1333 OBJECT_NAME_INFORMATION *info;
1334 OBJECT_ATTRIBUTES attr;
1335 IO_STATUS_BLOCK io;
1336 NTSTATUS status;
1337 HANDLE file;
1338 ULONG size;
1340 InitializeObjectAttributes( &attr, path, OBJ_CASE_INSENSITIVE, 0, NULL );
1341 if (NtOpenFile( &file, SYNCHRONIZE, &attr, &io, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1342 FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))
1343 return TRUE;
1345 if (NtQueryObject( file, ObjectNameInformation, NULL, 0, &size ) != STATUS_INFO_LENGTH_MISMATCH)
1347 NtClose( file );
1348 return TRUE;
1351 if (!(info = HeapAlloc( GetProcessHeap(), 0, size )))
1353 NtClose( file );
1354 return FALSE;
1357 status = NtQueryObject( file, ObjectNameInformation, info, size, NULL );
1358 NtClose( file );
1359 if (status)
1360 return TRUE;
1362 RtlFreeUnicodeString( path );
1363 status = RtlDuplicateUnicodeString( 0, &info->Name, path );
1364 HeapFree( GetProcessHeap(), 0, info );
1365 return !status;
1368 /***********************************************************************
1369 * GetVolumePathNameW (kernelbase.@)
1371 BOOL WINAPI DECLSPEC_HOTPATCH GetVolumePathNameW( const WCHAR *path, WCHAR *volume_path, DWORD length )
1373 FILE_ATTRIBUTE_TAG_INFORMATION attr_info;
1374 FILE_BASIC_INFORMATION basic_info;
1375 OBJECT_ATTRIBUTES attr;
1376 UNICODE_STRING nt_name;
1377 NTSTATUS status;
1379 if (path && !wcsncmp(path, L"\\??\\", 4))
1381 WCHAR current_drive[MAX_PATH];
1383 GetCurrentDirectoryW( ARRAY_SIZE(current_drive), current_drive );
1384 if (length >= 3)
1386 WCHAR ret_path[4] = {current_drive[0], ':', '\\', 0};
1387 lstrcpynW( volume_path, ret_path, length );
1388 return TRUE;
1391 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1392 return FALSE;
1395 if (!volume_path || !length || !RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1397 SetLastError( ERROR_INVALID_PARAMETER );
1398 return FALSE;
1401 if (!is_dos_path( &nt_name ))
1403 RtlFreeUnicodeString( &nt_name );
1404 WARN("invalid path %s\n", debugstr_w(path));
1405 SetLastError( ERROR_INVALID_NAME );
1406 return FALSE;
1409 InitializeObjectAttributes( &attr, &nt_name, OBJ_CASE_INSENSITIVE, 0, NULL );
1411 while (nt_name.Length > 7 * sizeof(WCHAR))
1413 IO_STATUS_BLOCK io;
1414 HANDLE file;
1416 if (!NtQueryAttributesFile( &attr, &basic_info )
1417 && (basic_info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
1418 && (basic_info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY)
1419 && !NtOpenFile( &file, SYNCHRONIZE | FILE_READ_ATTRIBUTES, &attr, &io,
1420 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1421 FILE_OPEN_REPARSE_POINT | FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT ))
1423 status = NtQueryInformationFile( file, &io, &attr_info,
1424 sizeof(attr_info), FileAttributeTagInformation );
1425 NtClose( file );
1426 if (!status)
1429 if (attr_info.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT)
1430 break;
1432 if (!resolve_symlink( &nt_name ))
1434 SetLastError( ERROR_OUTOFMEMORY );
1435 return FALSE;
1440 if (nt_name.Buffer[(nt_name.Length / sizeof(WCHAR)) - 1] == '\\')
1441 nt_name.Length -= sizeof(WCHAR);
1442 while (nt_name.Length && nt_name.Buffer[(nt_name.Length / sizeof(WCHAR)) - 1] != '\\')
1443 nt_name.Length -= sizeof(WCHAR);
1446 nt_name.Buffer[nt_name.Length / sizeof(WCHAR)] = 0;
1448 if (NtQueryAttributesFile( &attr, &basic_info ))
1450 RtlFreeUnicodeString( &nt_name );
1451 WARN("nonexistent path %s -> %s\n", debugstr_w(path), debugstr_w( nt_name.Buffer ));
1452 SetLastError( ERROR_FILE_NOT_FOUND );
1453 return FALSE;
1456 if (!wcsncmp(path, L"\\\\.\\", 4) || !wcsncmp(path, L"\\\\?\\", 4))
1458 if (length >= nt_name.Length / sizeof(WCHAR))
1460 memcpy(volume_path, path, 4 * sizeof(WCHAR));
1461 lstrcpynW( volume_path + 4, nt_name.Buffer + 4, length - 4 );
1463 TRACE("%s -> %s\n", debugstr_w(path), debugstr_w(volume_path));
1465 RtlFreeUnicodeString( &nt_name );
1466 return TRUE;
1469 else if (length >= (nt_name.Length / sizeof(WCHAR)) - 4)
1471 lstrcpynW( volume_path, nt_name.Buffer + 4, length );
1472 volume_path[0] = towupper(volume_path[0]);
1474 TRACE("%s -> %s\n", debugstr_w(path), debugstr_w(volume_path));
1476 RtlFreeUnicodeString( &nt_name );
1477 return TRUE;
1480 RtlFreeUnicodeString( &nt_name );
1481 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1482 return FALSE;
1486 static MOUNTMGR_MOUNT_POINTS *query_mount_points( HANDLE mgr, MOUNTMGR_MOUNT_POINT *input, DWORD insize )
1488 MOUNTMGR_MOUNT_POINTS *output;
1489 DWORD outsize = 1024;
1490 DWORD br;
1492 for (;;)
1494 if (!(output = HeapAlloc( GetProcessHeap(), 0, outsize )))
1496 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1497 return NULL;
1499 if (DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, input, insize, output, outsize, &br, NULL )) break;
1500 outsize = output->Size;
1501 HeapFree( GetProcessHeap(), 0, output );
1502 if (GetLastError() != ERROR_MORE_DATA) return NULL;
1504 return output;
1507 /***********************************************************************
1508 * GetVolumePathNamesForVolumeNameW (kernelbase.@)
1510 BOOL WINAPI DECLSPEC_HOTPATCH GetVolumePathNamesForVolumeNameW( LPCWSTR volumename, LPWSTR volumepathname,
1511 DWORD buflen, PDWORD returnlen )
1513 static const WCHAR dosdevicesW[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\'};
1514 HANDLE mgr;
1515 DWORD len, size;
1516 MOUNTMGR_MOUNT_POINT *spec;
1517 MOUNTMGR_MOUNT_POINTS *link, *target = NULL;
1518 WCHAR *name, *path;
1519 BOOL ret = FALSE;
1520 UINT i, j;
1522 TRACE("%s, %p, %u, %p\n", debugstr_w(volumename), volumepathname, buflen, returnlen);
1524 if (!volumename || (len = lstrlenW( volumename )) != 49)
1526 SetLastError( ERROR_INVALID_NAME );
1527 return FALSE;
1529 mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0 );
1530 if (mgr == INVALID_HANDLE_VALUE) return FALSE;
1532 size = sizeof(*spec) + sizeof(WCHAR) * (len - 1); /* remove trailing backslash */
1533 if (!(spec = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1534 spec->SymbolicLinkNameOffset = sizeof(*spec);
1535 spec->SymbolicLinkNameLength = size - sizeof(*spec);
1536 name = (WCHAR *)((char *)spec + spec->SymbolicLinkNameOffset);
1537 memcpy( name, volumename, size - sizeof(*spec) );
1538 name[1] = '?'; /* map \\?\ to \??\ */
1540 target = query_mount_points( mgr, spec, size );
1541 HeapFree( GetProcessHeap(), 0, spec );
1542 if (!target)
1544 goto done;
1546 if (!target->NumberOfMountPoints)
1548 SetLastError( ERROR_FILE_NOT_FOUND );
1549 goto done;
1551 len = 0;
1552 path = volumepathname;
1553 for (i = 0; i < target->NumberOfMountPoints; i++)
1555 link = NULL;
1556 if (target->MountPoints[i].DeviceNameOffset)
1558 const WCHAR *device = (const WCHAR *)((const char *)target + target->MountPoints[i].DeviceNameOffset);
1559 USHORT device_len = target->MountPoints[i].DeviceNameLength;
1561 size = sizeof(*spec) + device_len;
1562 if (!(spec = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1563 spec->DeviceNameOffset = sizeof(*spec);
1564 spec->DeviceNameLength = device_len;
1565 memcpy( (char *)spec + spec->DeviceNameOffset, device, device_len );
1567 link = query_mount_points( mgr, spec, size );
1568 HeapFree( GetProcessHeap(), 0, spec );
1570 else if (target->MountPoints[i].UniqueIdOffset)
1572 const WCHAR *id = (const WCHAR *)((const char *)target + target->MountPoints[i].UniqueIdOffset);
1573 USHORT id_len = target->MountPoints[i].UniqueIdLength;
1575 size = sizeof(*spec) + id_len;
1576 if (!(spec = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, size ))) goto done;
1577 spec->UniqueIdOffset = sizeof(*spec);
1578 spec->UniqueIdLength = id_len;
1579 memcpy( (char *)spec + spec->UniqueIdOffset, id, id_len );
1581 link = query_mount_points( mgr, spec, size );
1582 HeapFree( GetProcessHeap(), 0, spec );
1584 if (!link) continue;
1585 for (j = 0; j < link->NumberOfMountPoints; j++)
1587 const WCHAR *linkname;
1589 if (!link->MountPoints[j].SymbolicLinkNameOffset) continue;
1590 linkname = (const WCHAR *)((const char *)link + link->MountPoints[j].SymbolicLinkNameOffset);
1592 if (link->MountPoints[j].SymbolicLinkNameLength == sizeof(dosdevicesW) + 2 * sizeof(WCHAR) &&
1593 !wcsnicmp( linkname, dosdevicesW, ARRAY_SIZE( dosdevicesW )))
1595 len += 4;
1596 if (volumepathname && len < buflen)
1598 path[0] = linkname[ARRAY_SIZE( dosdevicesW )];
1599 path[1] = ':';
1600 path[2] = '\\';
1601 path[3] = 0;
1602 path += 4;
1606 HeapFree( GetProcessHeap(), 0, link );
1608 if (buflen <= len) SetLastError( ERROR_MORE_DATA );
1609 else if (volumepathname)
1611 volumepathname[len] = 0;
1612 ret = TRUE;
1614 if (returnlen) *returnlen = len + 1;
1616 done:
1617 HeapFree( GetProcessHeap(), 0, target );
1618 CloseHandle( mgr );
1619 return ret;
1623 /***********************************************************************
1624 * FindFirstVolumeW (kernelbase.@)
1626 HANDLE WINAPI DECLSPEC_HOTPATCH FindFirstVolumeW( LPWSTR volume, DWORD len )
1628 DWORD size = 1024;
1629 DWORD br;
1630 HANDLE mgr = CreateFileW( MOUNTMGR_DOS_DEVICE_NAME, 0, FILE_SHARE_READ|FILE_SHARE_WRITE,
1631 NULL, OPEN_EXISTING, 0, 0 );
1632 if (mgr == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;
1634 for (;;)
1636 MOUNTMGR_MOUNT_POINT input;
1637 MOUNTMGR_MOUNT_POINTS *output;
1639 if (!(output = HeapAlloc( GetProcessHeap(), 0, size )))
1641 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
1642 break;
1644 memset( &input, 0, sizeof(input) );
1646 if (!DeviceIoControl( mgr, IOCTL_MOUNTMGR_QUERY_POINTS, &input, sizeof(input),
1647 output, size, &br, NULL ))
1649 if (GetLastError() != ERROR_MORE_DATA) break;
1650 size = output->Size;
1651 HeapFree( GetProcessHeap(), 0, output );
1652 continue;
1654 CloseHandle( mgr );
1655 /* abuse the Size field to store the current index */
1656 output->Size = 0;
1657 if (!FindNextVolumeW( output, volume, len ))
1659 HeapFree( GetProcessHeap(), 0, output );
1660 return INVALID_HANDLE_VALUE;
1662 return output;
1664 CloseHandle( mgr );
1665 return INVALID_HANDLE_VALUE;
1669 /***********************************************************************
1670 * FindNextVolumeW (kernelbase.@)
1672 BOOL WINAPI DECLSPEC_HOTPATCH FindNextVolumeW( HANDLE handle, LPWSTR volume, DWORD len )
1674 MOUNTMGR_MOUNT_POINTS *data = handle;
1676 while (data->Size < data->NumberOfMountPoints)
1678 static const WCHAR volumeW[] = {'\\','?','?','\\','V','o','l','u','m','e','{',};
1679 WCHAR *link = (WCHAR *)((char *)data + data->MountPoints[data->Size].SymbolicLinkNameOffset);
1680 DWORD size = data->MountPoints[data->Size].SymbolicLinkNameLength;
1681 data->Size++;
1682 /* skip non-volumes */
1683 if (size < sizeof(volumeW) || memcmp( link, volumeW, sizeof(volumeW) )) continue;
1684 if (size + sizeof(WCHAR) >= len * sizeof(WCHAR))
1686 SetLastError( ERROR_FILENAME_EXCED_RANGE );
1687 return FALSE;
1689 memcpy( volume, link, size );
1690 volume[1] = '\\'; /* map \??\ to \\?\ */
1691 volume[size / sizeof(WCHAR)] = '\\'; /* Windows appends a backslash */
1692 volume[size / sizeof(WCHAR) + 1] = 0;
1693 TRACE( "returning entry %u %s\n", data->Size - 1, debugstr_w(volume) );
1694 return TRUE;
1696 SetLastError( ERROR_NO_MORE_FILES );
1697 return FALSE;
1701 /***********************************************************************
1702 * FindVolumeClose (kernelbase.@)
1704 BOOL WINAPI DECLSPEC_HOTPATCH FindVolumeClose( HANDLE handle )
1706 return HeapFree( GetProcessHeap(), 0, handle );
1710 /***********************************************************************
1711 * DeleteVolumeMountPointW (kernelbase.@)
1713 BOOL WINAPI /* DECLSPEC_HOTPATCH */ DeleteVolumeMountPointW( LPCWSTR mountpoint )
1715 FIXME("(%s), stub!\n", debugstr_w(mountpoint));
1716 return FALSE;
1720 /***********************************************************************
1721 * GetVolumeInformationByHandleW (kernelbase.@)
1723 BOOL WINAPI GetVolumeInformationByHandleW( HANDLE handle, WCHAR *label, DWORD label_len,
1724 DWORD *serial, DWORD *filename_len, DWORD *flags,
1725 WCHAR *fsname, DWORD fsname_len )
1727 IO_STATUS_BLOCK io;
1729 TRACE( "%p\n", handle );
1731 if (label || serial)
1733 char buffer[sizeof(FILE_FS_VOLUME_INFORMATION) + MAX_PATH * sizeof(WCHAR)];
1734 FILE_FS_VOLUME_INFORMATION *info = (FILE_FS_VOLUME_INFORMATION *)buffer;
1736 if (!set_ntstatus( NtQueryVolumeInformationFile( handle, &io, info, sizeof(buffer),
1737 FileFsVolumeInformation ) ))
1738 return FALSE;
1740 if (label)
1742 if (label_len < info->VolumeLabelLength / sizeof(WCHAR) + 1)
1744 SetLastError( ERROR_BAD_LENGTH );
1745 return FALSE;
1747 memcpy( label, info->VolumeLabel, info->VolumeLabelLength );
1748 label[info->VolumeLabelLength / sizeof(WCHAR)] = 0;
1750 if (serial) *serial = info->VolumeSerialNumber;
1753 if (filename_len || flags || fsname)
1755 char buffer[sizeof(FILE_FS_ATTRIBUTE_INFORMATION) + MAX_PATH * sizeof(WCHAR)];
1756 FILE_FS_ATTRIBUTE_INFORMATION *info = (FILE_FS_ATTRIBUTE_INFORMATION *)buffer;
1758 if (!set_ntstatus( NtQueryVolumeInformationFile( handle, &io, info, sizeof(buffer),
1759 FileFsAttributeInformation ) ))
1760 return FALSE;
1762 if (fsname)
1764 if (fsname_len < info->FileSystemNameLength / sizeof(WCHAR) + 1)
1766 SetLastError( ERROR_BAD_LENGTH );
1767 return FALSE;
1769 memcpy( fsname, info->FileSystemName, info->FileSystemNameLength );
1770 fsname[info->FileSystemNameLength / sizeof(WCHAR)] = 0;
1772 if (filename_len) *filename_len = info->MaximumComponentNameLength;
1773 if (flags) *flags = info->FileSystemAttributes;
1776 return TRUE;