2 * Copyright (c) 1999-2001 Apple Computer, Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
20 * @APPLE_LICENSE_HEADER_END@
23 Copyright (c) 1987-99 Apple Computer, Inc.
27 Contains code to implement hfs utility used by the WorkSpace to mount HFS.
30 5-Jan-1999 Don Brady Write hfs.label names in UTF-8.
31 10-Dec-1998 Pat Dirks Changed to try built-in hfs filesystem first.
32 3-Sep-1998 Don Brady Disable the daylight savings time stuff.
33 28-Aug-1998 chw Fixed parse args and verify args to indicate that the
34 flags (fixed or removable) are required in the probe case.
35 22-Jun-1998 Pat Dirks Changed HFSToUFSStr table to switch ":" and "/".
36 13-Jan-1998 jwc first cut (derived from old NextStep macfs.util code and cdrom.util code).
40 /* ************************************** I N C L U D E S ***************************************** */
42 #include <sys/types.h>
45 #include <sys/sysctl.h>
46 #include <sys/resource.h>
47 #include <sys/vmmeter.h>
48 #include <sys/mount.h>
52 #include <sys/loadable_fs.h>
53 #include <hfs/hfs_format.h>
63 #include <CoreFoundation/CFString.h>
65 #define READ_DEFAULT_ENCODING 1
67 #ifndef FSUR_MOUNT_HIDDEN
68 #define FSUR_MOUNT_HIDDEN (-9)
72 #define FSUC_ADOPT 'a'
76 #define FSUC_DISOWN 'd'
80 #define FSUC_GETUUID 'k'
84 #define FSUC_SETUUID 's'
89 /* **************************************** L O C A L S ******************************************* */
91 #define HFS_BLOCK_SIZE 512
93 char gHFS_FS_NAME
[] = "hfs";
94 char gHFS_FS_NAME_NAME
[] = "HFS";
96 char gNewlineString
[] = "\n";
98 char gMountCommand
[] = "/sbin/mount";
100 char gUnmountCommand
[] = "/sbin/umount";
102 char gReadOnlyOption
[] = "-r";
103 char gReadWriteOption
[] = "-w";
105 char gSuidOption
[] = "suid";
106 char gNoSuidOption
[] = "nosuid";
108 char gDevOption
[] = "dev";
109 char gNoDevOption
[] = "nodev";
111 char gUsePermissionsOption
[] = "perm";
112 char gIgnorePermissionsOption
[] = "noperm";
114 boolean_t gIsEjectable
= 0;
116 #define AUTO_ADOPT_FIXED 1
117 #define AUTO_ENTER_FIXED 0
120 #define VOLUMEUUIDVALUESIZE 2
121 typedef union VolumeUUID
{
122 unsigned long value
[VOLUMEUUIDVALUESIZE
];
129 #define VOLUMEUUIDLENGTH 16
130 typedef char VolumeUUIDString
[VOLUMEUUIDLENGTH
+1];
132 #define VOLUME_RECORDED 0x80000000
133 #define VOLUME_USEPERMISSIONS 0x00000001
134 #define VOLUME_VALIDSTATUSBITS ( VOLUME_USEPERMISSIONS )
136 typedef void *VolumeStatusDBHandle
;
138 void GenerateVolumeUUID(VolumeUUID
*newVolumeID
);
139 void ConvertVolumeUUIDStringToUUID(const char *UUIDString
, VolumeUUID
*volumeID
);
140 void ConvertVolumeUUIDToString(VolumeUUID
*volumeID
, char *UUIDString
);
141 int OpenVolumeStatusDB(VolumeStatusDBHandle
*DBHandlePtr
);
142 int GetVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
, unsigned long *VolumeStatus
);
143 int SetVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
, unsigned long VolumeStatus
);
144 int DeleteVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
);
145 int CloseVolumeStatusDB(VolumeStatusDBHandle DBHandle
);
147 /* ************************************ P R O T O T Y P E S *************************************** */
148 static void DoDisplayUsage( const char * argv
[] );
149 static void DoFileSystemFile( char * theFileNameSuffixPtr
, char * theContentsPtr
);
150 static int DoMount( char * theDeviceNamePtr
, const char * theMountPointPtr
, boolean_t isLocked
, boolean_t isSetuid
, boolean_t isDev
);
151 static int DoProbe( char * theDeviceNamePtr
);
152 static int DoUnmount( const char * theMountPointPtr
);
153 static int DoGetUUIDKey( const char * theDeviceNamePtr
);
154 static int DoChangeUUIDKey( const char * theDeviceNamePtr
);
155 static int DoAdopt( const char * theDeviceNamePtr
);
156 static int DoDisown( const char * theDeviceNamePtr
);
157 static int ParseArgs( int argc
, const char * argv
[], const char ** actionPtr
, const char ** mountPointPtr
, boolean_t
* isEjectablePtr
, boolean_t
* isLockedPtr
, boolean_t
* isSetuidPtr
, boolean_t
* isDevPtr
);
159 static int GetVolumeUUID(const char *deviceNamePtr
, VolumeUUID
*volumeUUIDPtr
, boolean_t generate
);
160 static int SetVolumeUUID(const char *deviceNamePtr
, VolumeUUID
*volumeUUIDPtr
);
161 static int GetEmbeddedHFSPlusVol(HFSMasterDirectoryBlock
* hfsMasterDirectoryBlockPtr
, off_t
* startOffsetPtr
);
162 static int GetNameFromHFSPlusVolumeStartingAt(int fd
, off_t hfsPlusVolumeOffset
, char * name_o
);
163 static int GetBTreeNodeInfo(int fd
, off_t hfsPlusVolumeOffset
, u_int32_t blockSize
,
164 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
,
165 u_int32_t
*nodeSize
, u_int32_t
*firstLeafNode
);
166 static int GetCatalogOverflowExtents(int fd
, off_t hfsPlusVolumeOffset
, HFSPlusVolumeHeader
*volHdrPtr
,
167 HFSPlusExtentDescriptor
**catalogExtents
, u_int32_t
*catalogExtCount
);
168 static int LogicalToPhysical(off_t logicalOffset
, ssize_t length
, u_int32_t blockSize
,
169 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
,
170 off_t
*physicalOffset
, ssize_t
*availableBytes
);
171 static int ReadFile(int fd
, void *buffer
, off_t offset
, ssize_t length
,
172 off_t volOffset
, u_int32_t blockSize
,
173 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
);
174 static ssize_t
readAt( int fd
, void * buf
, off_t offset
, ssize_t length
);
175 static ssize_t
writeAt( int fd
, void * buf
, off_t offset
, ssize_t length
);
179 * The fuction CFStringGetSystemEncoding does not work correctly in
180 * our context (autodiskmount deamon). We include a local copy here
181 * so that we can derive the default encoding. Radar 2516316.
183 #if READ_DEFAULT_ENCODING
184 #define __kCFUserEncodingFileName ("/.CFUserTextEncoding")
186 static unsigned int __CFStringGetDefaultEncodingForHFSUtil() {
187 struct passwd
*passwdp
;
189 if ((passwdp
= getpwuid(0))) { // root account
190 char buffer
[MAXPATHLEN
+ 1];
193 strcpy(buffer
, passwdp
->pw_dir
);
194 strcat(buffer
, __kCFUserEncodingFileName
);
196 if ((fd
= open(buffer
, O_RDONLY
, 0)) > 0) {
199 readSize
= read(fd
, buffer
, MAXPATHLEN
);
200 buffer
[(readSize
< 0 ? 0 : readSize
)] = '\0';
202 return strtol(buffer
, NULL
, 0);
205 return 0; // Fallback to smRoman
209 /* ******************************************** main ************************************************
211 This our main entry point to this utility. We get called by the WorkSpace. See ParseArgs
212 for detail info on input arguments.
214 argc - the number of arguments in argv.
215 argv - array of arguments.
217 returns FSUR_IO_SUCCESS if OK else one of the other FSUR_xyz errors in loadable_fs.h.
218 *************************************************************************************************** */
220 int main (int argc
, const char *argv
[])
222 const char * actionPtr
= NULL
;
223 char rawDeviceName
[MAXPATHLEN
];
224 char blockDeviceName
[MAXPATHLEN
];
225 const char * mountPointPtr
= NULL
;
226 int result
= FSUR_IO_SUCCESS
;
227 boolean_t isLocked
= 0; /* reasonable assumptions */
228 boolean_t isSetuid
= 0; /* reasonable assumptions */
229 boolean_t isDev
= 0; /* reasonable assumptions */
231 /* Verify our arguments */
232 if ( (result
= ParseArgs( argc
, argv
, & actionPtr
, & mountPointPtr
, & gIsEjectable
, & isLocked
, &isSetuid
, &isDev
)) != 0 ) {
237 -- Build our device name (full path), should end up with something like:
241 sprintf(rawDeviceName
, "/dev/r%s", argv
[2]);
242 sprintf(blockDeviceName
, "/dev/%s", argv
[2]);
244 /* call the appropriate routine to handle the given action argument after becoming root */
246 result
= seteuid( 0 );
252 result
= setegid( 0 ); // PPD - is this necessary?
254 switch( * actionPtr
) {
256 result
= DoProbe(rawDeviceName
);
260 case FSUC_MOUNT_FORCE
:
261 result
= DoMount(blockDeviceName
, mountPointPtr
, isLocked
, isSetuid
, isDev
);
265 result
= DoUnmount( mountPointPtr
);
268 result
= DoGetUUIDKey( blockDeviceName
);
272 result
= DoChangeUUIDKey( blockDeviceName
);
275 result
= DoAdopt( blockDeviceName
);
279 result
= DoDisown( blockDeviceName
);
283 /* should never get here since ParseArgs should handle this situation */
284 DoDisplayUsage( argv
);
293 return result
; /*...and make main fit the ANSI spec. */
297 /* ***************************** DoMount ********************************
299 This routine will fire off a system command to mount the given device at the given mountpoint.
300 autodiskmount will make sure the mountpoint exists and will remove it at Unmount time.
302 deviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
303 mountPointPtr - pointer to the mount point.
306 returns FSUR_IO_SUCCESS everything is cool else one of several other FSUR_xyz error codes.
307 *********************************************************************** */
309 DoMount(char *deviceNamePtr
, const char *mountPointPtr
, boolean_t isLocked
, boolean_t isSetuid
, boolean_t isDev
)
315 char *permissionsOption
;
316 int result
= FSUR_IO_FAIL
;
318 char encodeopt
[16] = "";
319 CFStringEncoding encoding
;
320 VolumeUUID targetVolumeUUID
;
321 VolumeStatusDBHandle vsdbhandle
= NULL
;
322 unsigned long targetVolumeStatus
;
324 if (mountPointPtr
== NULL
|| *mountPointPtr
== '\0')
325 return (FSUR_IO_FAIL
);
327 /* get the volume UUID to check if permissions should be used: */
328 targetVolumeStatus
= 0;
329 if (((result
= GetVolumeUUID(deviceNamePtr
, &targetVolumeUUID
, FALSE
)) != FSUR_IO_SUCCESS
) ||
330 (targetVolumeUUID
.v
.high
==0) ||
331 (targetVolumeUUID
.v
.low
== 0)) {
333 fprintf(stderr
, "hfs.util: DoMount: GetVolumeUUID returned %d.\n", result
);
336 if (gIsEjectable
== 0) {
337 result
= DoAdopt( deviceNamePtr
);
339 fprintf(stderr
, "hfs.util: DoMount: Auto-adopting %s; result = %d.\n", deviceNamePtr
, result
);
341 targetVolumeStatus
= VOLUME_USEPERMISSIONS
;
344 fprintf(stderr
, "hfs.util: DoMount: Not adopting ejectable %s.\n", deviceNamePtr
);
346 targetVolumeStatus
= 0;
350 /* We've got a real volume UUID! */
352 fprintf(stderr
, "hfs.util: DoMount: UUID = %08lX%08lX.\n", targetVolumeUUID
.v
.high
, targetVolumeUUID
.v
.low
);
354 if ((result
= OpenVolumeStatusDB(&vsdbhandle
)) != 0) {
355 /* Can't even get access to the volume info db; assume permissions are OK. */
357 fprintf(stderr
, "hfs.util: DoMount: OpenVolumeStatusDB returned %d; ignoring permissions.\n", result
);
359 targetVolumeStatus
= VOLUME_USEPERMISSIONS
;
362 fprintf(stderr
, "hfs.util: DoMount: Looking up volume status...\n");
364 if ((result
= GetVolumeStatusDBEntry(vsdbhandle
, &targetVolumeUUID
, &targetVolumeStatus
)) != 0) {
366 fprintf(stderr
, "hfs.util: DoMount: GetVolumeStatusDBEntry returned %d.\n", result
);
369 if (gIsEjectable
== 0) {
370 result
= DoAdopt( deviceNamePtr
);
372 fprintf(stderr
, "hfs.util: DoMount: Auto-adopting %s; result = %d.\n", deviceNamePtr
, result
);
374 targetVolumeStatus
= VOLUME_USEPERMISSIONS
;
377 fprintf(stderr
, "hfs.util: DoMount: Not adopting ejectable %s.\n", deviceNamePtr
);
379 targetVolumeStatus
= 0;
382 targetVolumeStatus
= 0;
385 (void)CloseVolumeStatusDB(vsdbhandle
);
392 isLockedstr
= isLocked
? gReadOnlyOption
: gReadWriteOption
;
393 isSetuidstr
= isSetuid
? gSuidOption
: gNoSuidOption
;
394 isDevstr
= isDev
? gDevOption
: gNoDevOption
;
397 (targetVolumeStatus
& VOLUME_USEPERMISSIONS
) ? gUsePermissionsOption
: gIgnorePermissionsOption
;
399 /* get default encoding value (for hfs volumes) */
400 #if READ_DEFAULT_ENCODING
401 encoding
= __CFStringGetDefaultEncodingForHFSUtil();
403 encoding
= CFStringGetSystemEncoding();
405 sprintf(encodeopt
, "-e=%d", (int)encoding
);
407 fprintf(stderr
, "hfs.util: %s %s -o -x -o %s -o %s -o -u=unknown,-g=unknown,-m=0777 -t %s %s %s ...\n",
408 gMountCommand
, isLockedstr
, encodeopt
, permissionsOption
, gHFS_FS_NAME
, deviceNamePtr
, mountPointPtr
);
410 (void) execl(gMountCommand
, gMountCommand
, isLockedstr
, "-o", isSetuidstr
, "-o", isDevstr
,
411 "-o", encodeopt
, "-o", permissionsOption
,
412 "-o", "-u=unknown,-g=unknown,-m=0777",
413 "-t", gHFS_FS_NAME
, deviceNamePtr
, mountPointPtr
, NULL
);
416 /* IF WE ARE HERE, WE WERE UNSUCCESFULL */
417 return (FSUR_IO_FAIL
);
421 return (FSUR_IO_FAIL
);
424 if ((wait4(pid
, (int *)&status
, 0, NULL
) == pid
) && (WIFEXITED(status
)))
425 result
= status
.w_retcode
;
429 return (result
== 0) ? FSUR_IO_SUCCESS
: FSUR_IO_FAIL
;
433 /* ****************************************** DoUnmount *********************************************
435 This routine will fire off a system command to unmount the given device.
437 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
439 returns FSUR_IO_SUCCESS everything is cool else FSUR_IO_FAIL.
440 *************************************************************************************************** */
442 DoUnmount(const char * theMountPointPtr
)
448 if (theMountPointPtr
== NULL
|| *theMountPointPtr
== '\0') return (FSUR_IO_FAIL
);
453 fprintf(stderr
, "hfs.util: %s %s ...\n", gUnmountCommand
, theMountPointPtr
);
455 (void) execl(gUnmountCommand
, gUnmountCommand
, theMountPointPtr
, NULL
);
457 /* IF WE ARE HERE, WE WERE UNSUCCESFULL */
458 return (FSUR_IO_FAIL
);
462 return (FSUR_IO_FAIL
);
465 if ((wait4(pid
, (int *)&status
, 0, NULL
) == pid
) && (WIFEXITED(status
)))
466 result
= status
.w_retcode
;
470 return (result
== 0 ? FSUR_IO_SUCCESS
: FSUR_IO_FAIL
);
475 /* ******************************************* DoProbe **********************************************
477 This routine will open the given raw device and check to make sure there is media that looks
480 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
482 returns FSUR_MOUNT_HIDDEN (previously FSUR_RECOGNIZED) if we can handle the media else one of the FSUR_xyz error codes.
483 *************************************************************************************************** */
485 DoProbe(char *deviceNamePtr
)
487 int result
= FSUR_UNRECOGNIZED
;
490 HFSMasterDirectoryBlock
* mdbPtr
;
491 HFSPlusVolumeHeader
* volHdrPtr
;
492 u_char volnameUTF8
[NAME_MAX
+1];
494 bufPtr
= (char *)malloc(HFS_BLOCK_SIZE
);
496 result
= FSUR_UNRECOGNIZED
;
500 mdbPtr
= (HFSMasterDirectoryBlock
*) bufPtr
;
501 volHdrPtr
= (HFSPlusVolumeHeader
*) bufPtr
;
503 fd
= open( deviceNamePtr
, O_RDONLY
, 0 );
505 result
= FSUR_IO_FAIL
;
510 * Read the HFS Master Directory Block from sector 2
512 result
= readAt(fd
, bufPtr
, (off_t
)(2 * HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
513 if (FSUR_IO_FAIL
== result
)
516 /* get classic HFS volume name (from MDB) */
517 if (mdbPtr
->drSigWord
== kHFSSigWord
&&
518 mdbPtr
->drEmbedSigWord
!= kHFSPlusSigWord
) {
521 CFStringEncoding encoding
;
523 /* Some poorly mastered HFS CDs have an empty MDB name field! */
524 if (mdbPtr
->drVN
[0] == '\0') {
525 strcpy(&mdbPtr
->drVN
[1], gHFS_FS_NAME_NAME
);
526 mdbPtr
->drVN
[0] = strlen(gHFS_FS_NAME_NAME
);
529 encoding
= CFStringGetSystemEncoding();
530 cfstr
= CFStringCreateWithPascalString(kCFAllocatorDefault
,
531 mdbPtr
->drVN
, encoding
);
532 cfOK
= CFStringGetCString(cfstr
, volnameUTF8
, NAME_MAX
,
533 kCFStringEncodingUTF8
);
536 if (!cfOK
&& encoding
!= kCFStringEncodingMacRoman
) {
538 /* default to MacRoman on conversion errors */
539 cfstr
= CFStringCreateWithPascalString(kCFAllocatorDefault
,
540 mdbPtr
->drVN
, kCFStringEncodingMacRoman
);
541 CFStringGetCString(cfstr
, volnameUTF8
, NAME_MAX
,
542 kCFStringEncodingUTF8
);
546 /* get HFS Plus volume name (from Catalog) */
547 } else if ((volHdrPtr
->signature
== kHFSPlusSigWord
) ||
548 (mdbPtr
->drSigWord
== kHFSSigWord
&&
549 mdbPtr
->drEmbedSigWord
== kHFSPlusSigWord
)) {
552 if (volHdrPtr
->signature
== kHFSPlusSigWord
) {
554 } else {/* embedded volume, first find offset */
555 result
= GetEmbeddedHFSPlusVol(mdbPtr
, &startOffset
);
556 if ( result
!= FSUR_IO_SUCCESS
)
560 result
= GetNameFromHFSPlusVolumeStartingAt(fd
, startOffset
,
563 result
= FSUR_UNRECOGNIZED
;
566 if (FSUR_IO_SUCCESS
== result
) {
569 CFMutableStringRef volumeName
;
570 CFIndex volumeNameLength
;
571 CFRange foundSubString
;
573 slash
= CFStringCreateWithCString(kCFAllocatorDefault
, "/", kCFStringEncodingUTF8
);
575 result
= FSUR_IO_FAIL
;
579 colon
= CFStringCreateWithCString(kCFAllocatorDefault
, ":", kCFStringEncodingUTF8
);
581 result
= FSUR_IO_FAIL
;
585 volumeName
= CFStringCreateMutableCopy(
588 CFStringCreateWithCString(kCFAllocatorDefault
, volnameUTF8
, kCFStringEncodingUTF8
));
589 if (volumeName
== NULL
) {
590 result
= FSUR_IO_FAIL
;
593 volumeNameLength
= CFStringGetLength(volumeName
);
595 while (CFStringFindWithOptions(volumeName
, slash
, CFRangeMake(0, volumeNameLength
-1), 0, &foundSubString
)) {
596 CFStringReplace(volumeName
, foundSubString
, colon
);
599 CFStringGetCString(volumeName
, volnameUTF8
, NAME_MAX
, kCFStringEncodingUTF8
);
600 write(1, volnameUTF8
, strlen(volnameUTF8
));
602 /* backwards compatibility */
603 DoFileSystemFile( FS_NAME_SUFFIX
, gHFS_FS_NAME
);
604 DoFileSystemFile( FS_LABEL_SUFFIX
, volnameUTF8
);
605 result
= FSUR_MOUNT_HIDDEN
;
622 /* **************************************** DoGetUUIDKey *******************************************
624 This routine will open the given block device and return the volume UUID in text form written to stdout.
626 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
628 returns FSUR_IO_SUCCESS or else one of the FSUR_xyz error codes.
629 *************************************************************************************************** */
631 DoGetUUIDKey( const char * theDeviceNamePtr
) {
633 VolumeUUID targetVolumeUUID
;
634 VolumeUUIDString UUIDString
;
635 char uuidLine
[VOLUMEUUIDLENGTH
+2];
637 if ((result
= GetVolumeUUID(theDeviceNamePtr
, &targetVolumeUUID
, FALSE
)) != FSUR_IO_SUCCESS
) goto Err_Exit
;
639 ConvertVolumeUUIDToString( &targetVolumeUUID
, UUIDString
);
640 strncpy(uuidLine
, UUIDString
, VOLUMEUUIDLENGTH
+1);
641 write(1, uuidLine
, strlen(uuidLine
));
642 result
= FSUR_IO_SUCCESS
;
650 /* *************************************** DoChangeUUIDKey ******************************************
652 This routine will change the UUID on the specified block device.
654 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
656 returns FSUR_IO_SUCCESS or else one of the FSUR_xyz error codes.
657 *************************************************************************************************** */
659 DoChangeUUIDKey( const char * theDeviceNamePtr
) {
661 VolumeUUID newVolumeUUID
;
663 GenerateVolumeUUID(&newVolumeUUID
);
664 result
= SetVolumeUUID(theDeviceNamePtr
, &newVolumeUUID
);
671 /* **************************************** DoAdopt *******************************************
673 This routine will add the UUID of the specified block device to the list of local volumes.
675 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
677 returns FSUR_IO_SUCCESS or else one of the FSUR_xyz error codes.
678 *************************************************************************************************** */
680 DoAdopt( const char * theDeviceNamePtr
) {
681 int result
, closeresult
;
682 VolumeUUID targetVolumeUUID
;
683 VolumeStatusDBHandle vsdbhandle
= NULL
;
684 unsigned long targetVolumeStatus
;
686 if ((result
= GetVolumeUUID(theDeviceNamePtr
, &targetVolumeUUID
, TRUE
)) != FSUR_IO_SUCCESS
) goto Err_Return
;
688 if ((result
= OpenVolumeStatusDB(&vsdbhandle
)) != 0) goto Err_Exit
;
689 if ((result
= GetVolumeStatusDBEntry(vsdbhandle
, &targetVolumeUUID
, &targetVolumeStatus
)) != 0) {
690 targetVolumeStatus
= 0;
692 targetVolumeStatus
= (targetVolumeStatus
& VOLUME_VALIDSTATUSBITS
) | VOLUME_USEPERMISSIONS
;
693 if ((result
= SetVolumeStatusDBEntry(vsdbhandle
, &targetVolumeUUID
, targetVolumeStatus
)) != 0) goto Err_Exit
;
695 result
= FSUR_IO_SUCCESS
;
699 closeresult
= CloseVolumeStatusDB(vsdbhandle
);
701 if (result
== FSUR_IO_SUCCESS
) result
= closeresult
;
704 if ((result
!= 0) && (result
!= FSUR_IO_SUCCESS
)) result
= FSUR_IO_FAIL
;
708 if (result
!= FSUR_IO_SUCCESS
) fprintf(stderr
, "DoAdopt: returning %d...\n", result
);
715 /* **************************************** DoDisown *******************************************
717 This routine will change the status of the specified block device to ignore its permissions.
719 theDeviceNamePtr - pointer to the device name (full path, like /dev/disk0s2).
721 returns FSUR_IO_SUCCESS or else one of the FSUR_xyz error codes.
722 *************************************************************************************************** */
724 DoDisown( const char * theDeviceNamePtr
) {
725 int result
, closeresult
;
726 VolumeUUID targetVolumeUUID
;
727 VolumeStatusDBHandle vsdbhandle
= NULL
;
728 unsigned long targetVolumeStatus
;
730 if ((result
= GetVolumeUUID(theDeviceNamePtr
, &targetVolumeUUID
, TRUE
)) != FSUR_IO_SUCCESS
) goto Err_Return
;
732 if ((result
= OpenVolumeStatusDB(&vsdbhandle
)) != 0) goto Err_Exit
;
733 if ((result
= GetVolumeStatusDBEntry(vsdbhandle
, &targetVolumeUUID
, &targetVolumeStatus
)) != 0) {
734 targetVolumeStatus
= 0;
736 targetVolumeStatus
= (targetVolumeStatus
& VOLUME_VALIDSTATUSBITS
) & ~VOLUME_USEPERMISSIONS
;
737 if ((result
= SetVolumeStatusDBEntry(vsdbhandle
, &targetVolumeUUID
, targetVolumeStatus
)) != 0) goto Err_Exit
;
739 result
= FSUR_IO_SUCCESS
;
743 closeresult
= CloseVolumeStatusDB(vsdbhandle
);
745 if (result
== FSUR_IO_SUCCESS
) result
= closeresult
;
748 if ((result
!= 0) && (result
!= FSUR_IO_SUCCESS
)) {
750 if (result
!= 0) fprintf(stderr
, "DoDisown: result = %d; changing to %d...\n", result
, FSUR_IO_FAIL
);
752 result
= FSUR_IO_FAIL
;
757 if (result
!= FSUR_IO_SUCCESS
) fprintf(stderr
, "DoDisown: returning %d...\n", result
);
764 /* **************************************** ParseArgs ********************************************
766 This routine will make sure the arguments passed in to us are cool.
767 Here is how this utility is used:
769 usage: hfs.util actionArg deviceArg [mountPointArg] [flagsArg]
771 -p (Probe for mounting)
772 -P (Probe for initializing - not supported)
774 -r (Repair - not supported)
777 -i (Initialize - not supported)
780 disk0s2 (for example)
783 /foo/bar/ (required for Mount and Force Mount actions)
786 (these are ignored for CDROMs)
787 either "readonly" OR "writable"
788 either "removable" OR "fixed"
789 either "nosuid" or "suid"
792 hfs.util -p disk0s2 removable writable
793 hfs.util -p disk0s2 removable readonly
794 hfs.util -m disk0s2 /my/hfs
797 argc - the number of arguments in argv.
798 argv - array of arguments.
800 returns FSUR_INVAL if we find a bad argument else 0.
801 *************************************************************************************************** */
803 ParseArgs(int argc
, const char *argv
[], const char ** actionPtr
,
804 const char ** mountPointPtr
, boolean_t
* isEjectablePtr
,
805 boolean_t
* isLockedPtr
, boolean_t
* isSetuidPtr
, boolean_t
* isDevPtr
)
807 int result
= FSUR_INVAL
;
812 /* Must have at least 3 arguments and the action argument must start with a '-' */
813 if ( (argc
< 3) || (argv
[1][0] != '-') ) {
814 DoDisplayUsage( argv
);
818 /* we only support actions Probe, Mount, Force Mount, and Unmount */
820 * actionPtr
= & argv
[1][1];
822 switch ( argv
[1][1] ) {
824 /* action Probe and requires 5 arguments (need the flags) */
826 DoDisplayUsage( argv
);
834 /* Note: the device argument in argv[2] is checked further down but ignored. */
835 * mountPointPtr
= argv
[3];
836 index
= 0; /* No isEjectable/isLocked flags for unmount. */
840 case FSUC_MOUNT_FORCE
:
841 /* action Mount and ForceMount require 7 arguments (need the mountpoint and the flags) */
843 DoDisplayUsage( argv
);
846 * mountPointPtr
= argv
[3];
869 DoDisplayUsage( argv
);
874 /* Make sure device (argv[2]) is something reasonable */
875 deviceLength
= strlen( argv
[2] );
876 if ( deviceLength
< 3 || deviceLength
> NAME_MAX
) {
877 DoDisplayUsage( argv
);
882 /* Flags: removable/fixed. */
883 if ( 0 == strcmp(argv
[index
],"removable") ) {
884 * isEjectablePtr
= 1;
885 } else if ( 0 == strcmp(argv
[index
],"fixed") ) {
886 * isEjectablePtr
= 0;
888 printf("hfs.util: ERROR: unrecognized flag (removable/fixed) argv[%d]='%s'\n",index
,argv
[index
]);
891 /* Flags: readonly/writable. */
892 if ( 0 == strcmp(argv
[index
+1],"readonly") ) {
894 } else if ( 0 == strcmp(argv
[index
+1],"writable") ) {
897 printf("hfs.util: ERROR: unrecognized flag (readonly/writable) argv[%d]='%s'\n",index
,argv
[index
+1]);
901 /* Flags: suid/nosuid. */
902 if ( 0 == strcmp(argv
[index
+2],"suid") ) {
904 } else if ( 0 == strcmp(argv
[index
+2],"nosuid") ) {
907 printf("hfs.util: ERROR: unrecognized flag (suid/nosuid) argv[%d]='%s'\n",index
,argv
[index
+2]);
910 /* Flags: dev/nodev. */
911 if ( 0 == strcmp(argv
[index
+3],"dev") ) {
913 } else if ( 0 == strcmp(argv
[index
+3],"nodev") ) {
916 printf("hfs.util: ERROR: unrecognized flag (dev/nodev) argv[%d]='%s'\n",index
,argv
[index
+3]);
931 /* *************************************** DoDisplayUsage ********************************************
933 This routine will do a printf of the correct usage for this utility.
935 argv - array of arguments.
938 *************************************************************************************************** */
940 DoDisplayUsage(const char *argv
[])
942 printf("usage: %s action_arg device_arg [mount_point_arg] [Flags] \n", argv
[0]);
943 printf("action_arg:\n");
944 printf(" -%c (Probe for mounting)\n", FSUC_PROBE
);
945 printf(" -%c (Mount)\n", FSUC_MOUNT
);
946 printf(" -%c (Unmount)\n", FSUC_UNMOUNT
);
947 printf(" -%c (Force Mount)\n", FSUC_MOUNT_FORCE
);
948 #ifdef HFS_UUID_SUPPORT
949 printf(" -%c (Get UUID Key)\n", FSUC_GETUUID
);
950 printf(" -%c (Set UUID Key)\n", FSUC_SETUUID
);
951 #endif HFS_UUID_SUPPORT
952 printf(" -%c (Adopt permissions)\n", FSUC_ADOPT
);
953 printf("device_arg:\n");
954 printf(" device we are acting upon (for example, 'disk0s2')\n");
955 printf("mount_point_arg:\n");
956 printf(" required for Mount and Force Mount \n");
958 printf(" required for Mount, Force Mount and Probe\n");
959 printf(" indicates removable or fixed (for example 'fixed')\n");
960 printf(" indicates readonly or writable (for example 'readonly')\n");
961 printf("Examples:\n");
962 printf(" %s -p disk0s2 fixed writable\n", argv
[0]);
963 printf(" %s -m disk0s2 /my/hfs removable readonly\n", argv
[0]);
967 } /* DoDisplayUsage */
970 /* ************************************** DoFileSystemFile *******************************************
972 This routine will create a file system info file that is used by WorkSpace. After creating the
973 file it will write whatever theContentsPtr points to the new file.
974 We end up with a file something like:
975 /System/Library/Filesystems/hfs.fs/hfs.name
976 when our file system name is "hfs" and theFileNameSuffixPtr points to ".name"
978 theFileNameSuffixPtr - pointer to a suffix we add to the file name we're creating.
979 theContentsPtr - pointer to C string to write into the file.
982 *************************************************************************************************** */
984 DoFileSystemFile(char *fileNameSuffixPtr
, char *contentsPtr
)
987 char fileName
[MAXPATHLEN
];
989 sprintf(fileName
, "%s/%s%s/%s", FS_DIR_LOCATION
, gHFS_FS_NAME
,
990 FS_DIR_SUFFIX
, gHFS_FS_NAME
);
991 strcat(fileName
, fileNameSuffixPtr
);
992 unlink(fileName
); /* delete existing string */
994 if ( strlen( fileNameSuffixPtr
) ) {
995 int oldMask
= umask(0);
997 fd
= open( & fileName
[0], O_CREAT
| O_TRUNC
| O_WRONLY
, 0644 );
1000 write( fd
, contentsPtr
, strlen( contentsPtr
) );
1007 } /* DoFileSystemFile */
1012 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1016 GetVolumeUUID(const char *deviceNamePtr
, VolumeUUID
*volumeUUIDPtr
, boolean_t generate
) {
1019 HFSMasterDirectoryBlock
* mdbPtr
;
1020 HFSPlusVolumeHeader
* volHdrPtr
;
1021 VolumeUUID
*finderInfoUUIDPtr
;
1024 bufPtr
= (char *)malloc(HFS_BLOCK_SIZE
);
1026 result
= FSUR_UNRECOGNIZED
;
1030 mdbPtr
= (HFSMasterDirectoryBlock
*) bufPtr
;
1031 volHdrPtr
= (HFSPlusVolumeHeader
*) bufPtr
;
1033 fd
= open( deviceNamePtr
, O_RDWR
, 0 );
1035 fd
= open( deviceNamePtr
, O_RDONLY
, 0);
1038 fprintf(stderr
, "hfs.util: GetVolumeUUID: device open failed (errno = %d).\n", errno
);
1040 result
= FSUR_IO_FAIL
;
1046 * Read the HFS Master Directory Block from sector 2
1048 result
= readAt(fd
, volHdrPtr
, (off_t
)(2 * HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1049 if (result
!= FSUR_IO_SUCCESS
) {
1053 if (mdbPtr
->drSigWord
== kHFSSigWord
&&
1054 mdbPtr
->drEmbedSigWord
!= kHFSPlusSigWord
) {
1055 finderInfoUUIDPtr
= (VolumeUUID
*)(&mdbPtr
->drFndrInfo
[6]);
1056 if (generate
&& ((finderInfoUUIDPtr
->v
.high
== 0) || (finderInfoUUIDPtr
->v
.low
== 0))) {
1057 GenerateVolumeUUID(volumeUUIDPtr
);
1058 bcopy(volumeUUIDPtr
, finderInfoUUIDPtr
, sizeof(*finderInfoUUIDPtr
));
1059 result
= writeAt(fd
, volHdrPtr
, (off_t
)(2 * HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1060 if (result
!= FSUR_IO_SUCCESS
) goto Err_Exit
;
1062 bcopy(finderInfoUUIDPtr
, volumeUUIDPtr
, sizeof(*volumeUUIDPtr
));
1063 result
= FSUR_IO_SUCCESS
;
1064 } else if ((volHdrPtr
->signature
== kHFSPlusSigWord
) ||
1065 ((mdbPtr
->drSigWord
== kHFSSigWord
) &&
1066 (mdbPtr
->drEmbedSigWord
== kHFSPlusSigWord
))) {
1069 if (volHdrPtr
->signature
== kHFSPlusSigWord
) {
1071 } else {/* embedded volume, first find offset */
1072 result
= GetEmbeddedHFSPlusVol(mdbPtr
, &startOffset
);
1073 if ( result
!= FSUR_IO_SUCCESS
) {
1078 result
= readAt( fd
, volHdrPtr
, startOffset
+ (off_t
)(2*HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1079 if (result
!= FSUR_IO_SUCCESS
) {
1080 goto Err_Exit
; // return FSUR_IO_FAIL
1083 /* Verify that it is an HFS+ volume. */
1085 if (volHdrPtr
->signature
!= kHFSPlusSigWord
) {
1086 result
= FSUR_IO_FAIL
;
1090 finderInfoUUIDPtr
= (VolumeUUID
*)&volHdrPtr
->finderInfo
[24];
1091 if (generate
&& ((finderInfoUUIDPtr
->v
.high
== 0) || (finderInfoUUIDPtr
->v
.low
== 0))) {
1092 GenerateVolumeUUID(volumeUUIDPtr
);
1093 bcopy(volumeUUIDPtr
, finderInfoUUIDPtr
, sizeof(*finderInfoUUIDPtr
));
1094 result
= writeAt( fd
, volHdrPtr
, startOffset
+ (off_t
)(2*HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1095 if (result
!= FSUR_IO_SUCCESS
) {
1099 bcopy(finderInfoUUIDPtr
, volumeUUIDPtr
, sizeof(*volumeUUIDPtr
));
1100 result
= FSUR_IO_SUCCESS
;
1102 result
= FSUR_UNRECOGNIZED
;
1106 if (fd
> 0) close(fd
);
1107 if (bufPtr
) free(bufPtr
);
1110 if (result
!= FSUR_IO_SUCCESS
) fprintf(stderr
, "hfs.util: GetVolumeUUID: result = %d...\n", result
);
1112 return (result
== FSUR_IO_SUCCESS
) ? FSUR_IO_SUCCESS
: FSUR_IO_FAIL
;
1120 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1124 SetVolumeUUID(const char *deviceNamePtr
, VolumeUUID
*volumeUUIDPtr
) {
1127 HFSMasterDirectoryBlock
* mdbPtr
;
1128 HFSPlusVolumeHeader
* volHdrPtr
;
1129 VolumeUUID
*finderInfoUUIDPtr
;
1132 bufPtr
= (char *)malloc(HFS_BLOCK_SIZE
);
1134 result
= FSUR_UNRECOGNIZED
;
1138 mdbPtr
= (HFSMasterDirectoryBlock
*) bufPtr
;
1139 volHdrPtr
= (HFSPlusVolumeHeader
*) bufPtr
;
1141 fd
= open( deviceNamePtr
, O_RDWR
, 0 );
1144 fprintf(stderr
, "hfs.util: SetVolumeUUID: device open failed (errno = %d).\n", errno
);
1146 result
= FSUR_IO_FAIL
;
1151 * Read the HFS Master Directory Block from sector 2
1153 result
= readAt(fd
, volHdrPtr
, (off_t
)(2 * HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1154 if (result
!= FSUR_IO_SUCCESS
) {
1158 if (mdbPtr
->drSigWord
== kHFSSigWord
&&
1159 mdbPtr
->drEmbedSigWord
!= kHFSPlusSigWord
) {
1160 finderInfoUUIDPtr
= (VolumeUUID
*)(&mdbPtr
->drFndrInfo
[6]);
1161 bcopy(volumeUUIDPtr
, finderInfoUUIDPtr
, sizeof(*finderInfoUUIDPtr
));
1162 result
= writeAt(fd
, volHdrPtr
, (off_t
)(2 * HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1163 } else if ((volHdrPtr
->signature
== kHFSPlusSigWord
) ||
1164 ((mdbPtr
->drSigWord
== kHFSSigWord
) &&
1165 (mdbPtr
->drEmbedSigWord
== kHFSPlusSigWord
))) {
1168 if (volHdrPtr
->signature
== kHFSPlusSigWord
) {
1170 } else {/* embedded volume, first find offset */
1171 result
= GetEmbeddedHFSPlusVol(mdbPtr
, &startOffset
);
1172 if ( result
!= FSUR_IO_SUCCESS
) {
1177 result
= readAt( fd
, volHdrPtr
, startOffset
+ (off_t
)(2*HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1178 if (result
!= FSUR_IO_SUCCESS
) {
1179 goto Err_Exit
; // return FSUR_IO_FAIL
1182 /* Verify that it is an HFS+ volume. */
1184 if (volHdrPtr
->signature
!= kHFSPlusSigWord
) {
1185 result
= FSUR_IO_FAIL
;
1189 finderInfoUUIDPtr
= (VolumeUUID
*)&volHdrPtr
->finderInfo
[24];
1190 bcopy(volumeUUIDPtr
, finderInfoUUIDPtr
, sizeof(*finderInfoUUIDPtr
));
1191 result
= writeAt( fd
, volHdrPtr
, startOffset
+ (off_t
)(2*HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1192 if (result
!= FSUR_IO_SUCCESS
) {
1195 result
= FSUR_IO_SUCCESS
;
1197 result
= FSUR_UNRECOGNIZED
;
1201 if (fd
> 0) close(fd
);
1202 if (bufPtr
) free(bufPtr
);
1205 if (result
!= FSUR_IO_SUCCESS
) fprintf(stderr
, "hfs.util: SetVolumeUUID: result = %d...\n", result
);
1207 return (result
== FSUR_IO_SUCCESS
) ? FSUR_IO_SUCCESS
: FSUR_IO_FAIL
;
1213 -- GetEmbeddedHFSPlusVol
1215 -- In: hfsMasterDirectoryBlockPtr
1216 -- Out: startOffsetPtr - the disk offset at which the HFS+ volume starts
1217 (that is, 2 blocks before the volume header)
1222 GetEmbeddedHFSPlusVol (HFSMasterDirectoryBlock
* hfsMasterDirectoryBlockPtr
, off_t
* startOffsetPtr
)
1224 int result
= FSUR_IO_SUCCESS
;
1225 u_int32_t allocationBlockSize
, firstAllocationBlock
, startBlock
, blockCount
;
1227 if (hfsMasterDirectoryBlockPtr
->drSigWord
!= kHFSSigWord
) {
1228 result
= FSUR_UNRECOGNIZED
;
1232 allocationBlockSize
= hfsMasterDirectoryBlockPtr
->drAlBlkSiz
;
1233 firstAllocationBlock
= hfsMasterDirectoryBlockPtr
->drAlBlSt
;
1235 if (hfsMasterDirectoryBlockPtr
->drEmbedSigWord
!= kHFSPlusSigWord
) {
1236 result
= FSUR_UNRECOGNIZED
;
1240 startBlock
= hfsMasterDirectoryBlockPtr
->drEmbedExtent
.startBlock
;
1241 blockCount
= hfsMasterDirectoryBlockPtr
->drEmbedExtent
.blockCount
;
1243 if ( startOffsetPtr
)
1244 *startOffsetPtr
= ((u_int64_t
)startBlock
* (u_int64_t
)allocationBlockSize
) +
1245 ((u_int64_t
)firstAllocationBlock
* (u_int64_t
)HFS_BLOCK_SIZE
);
1255 -- GetNameFromHFSPlusVolumeStartingAt
1257 -- Caller's responsibility to allocate and release memory for the converted string.
1259 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1263 GetNameFromHFSPlusVolumeStartingAt(int fd
, off_t hfsPlusVolumeOffset
, char * name_o
)
1265 int result
= FSUR_IO_SUCCESS
;
1266 u_int32_t blockSize
;
1267 char * bufPtr
= NULL
;
1268 HFSPlusVolumeHeader
* volHdrPtr
;
1269 BTNodeDescriptor
* bTreeNodeDescriptorPtr
;
1270 u_int32_t catalogNodeSize
;
1272 u_int32_t catalogExtCount
;
1273 HFSPlusExtentDescriptor
*catalogExtents
= NULL
;
1275 volHdrPtr
= (HFSPlusVolumeHeader
*)malloc(HFS_BLOCK_SIZE
);
1276 if ( ! volHdrPtr
) {
1277 result
= FSUR_IO_FAIL
;
1282 * Read the Volume Header
1283 * (This is a little redundant for a pure, unwrapped HFS+ volume)
1285 result
= readAt( fd
, volHdrPtr
, hfsPlusVolumeOffset
+ (off_t
)(2*HFS_BLOCK_SIZE
), HFS_BLOCK_SIZE
);
1286 if (result
== FSUR_IO_FAIL
) {
1288 fprintf(stderr
, "hfs.util: GetNameFromHFSPlusVolumeStartingAt: readAt failed\n");
1290 goto Return
; // return FSUR_IO_FAIL
1293 /* Verify that it is an HFS+ volume. */
1295 if (volHdrPtr
->signature
!= kHFSPlusSigWord
) {
1296 result
= FSUR_IO_FAIL
;
1298 fprintf(stderr
, "hfs.util: GetNameFromHFSPlusVolumeStartingAt: volHdrPtr->signature != kHFSPlusSigWord\n");
1303 blockSize
= volHdrPtr
->blockSize
;
1304 catalogExtents
= (HFSPlusExtentDescriptor
*) malloc(sizeof(HFSPlusExtentRecord
));
1305 if ( ! catalogExtents
) {
1306 result
= FSUR_IO_FAIL
;
1309 bcopy(volHdrPtr
->catalogFile
.extents
, catalogExtents
, sizeof(HFSPlusExtentRecord
));
1310 catalogExtCount
= kHFSPlusExtentDensity
;
1312 /* if there are overflow catalog extents, then go get them */
1313 if (catalogExtents
[7].blockCount
!= 0) {
1314 result
= GetCatalogOverflowExtents(fd
, hfsPlusVolumeOffset
, volHdrPtr
, &catalogExtents
, &catalogExtCount
);
1315 if (result
!= FSUR_IO_SUCCESS
)
1319 /* Read the header node of the catalog B-Tree */
1321 result
= GetBTreeNodeInfo(fd
, hfsPlusVolumeOffset
, blockSize
,
1322 catalogExtCount
, catalogExtents
,
1323 &catalogNodeSize
, &leafNode
);
1324 if (result
!= FSUR_IO_SUCCESS
)
1327 /* Read the first leaf node of the catalog b-tree */
1329 bufPtr
= (char *)malloc(catalogNodeSize
);
1331 result
= FSUR_IO_FAIL
;
1335 bTreeNodeDescriptorPtr
= (BTNodeDescriptor
*)bufPtr
;
1337 result
= ReadFile(fd
, bufPtr
, (off_t
) leafNode
* (off_t
) catalogNodeSize
, catalogNodeSize
,
1338 hfsPlusVolumeOffset
, blockSize
,
1339 catalogExtCount
, catalogExtents
);
1340 if (result
== FSUR_IO_FAIL
) {
1342 fprintf(stderr
, "hfs.util: ERROR: reading first leaf failed\n");
1344 goto Return
; // return FSUR_IO_FAIL
1350 HFSPlusCatalogKey
* k
;
1353 if ( bTreeNodeDescriptorPtr
->numRecords
< 1) {
1354 result
= FSUR_IO_FAIL
;
1356 fprintf(stderr
, "hfs.util: ERROR: bTreeNodeDescriptorPtr->numRecords < 1\n");
1361 // Get the offset (in bytes) of the first record from the list of offsets at the end of the node.
1363 p
= bufPtr
+ catalogNodeSize
- sizeof(u_int16_t
); // pointer arithmetic in bytes
1366 // Get a pointer to the first record.
1368 p
= bufPtr
+ *v
; // pointer arithmetic in bytes
1369 k
= (HFSPlusCatalogKey
*)p
;
1371 // There should be only one record whose parent is the root parent. It should be the first record.
1373 if (k
->parentID
!= kHFSRootParentID
) {
1374 result
= FSUR_IO_FAIL
;
1376 fprintf(stderr
, "hfs.util: ERROR: k->parentID != kHFSRootParentID\n");
1381 /* Extract the name of the root directory */
1383 cfstr
= CFStringCreateWithCharacters(kCFAllocatorDefault
, k
->nodeName
.unicode
, k
->nodeName
.length
);
1384 (void) CFStringGetCString(cfstr
, name_o
, NAME_MAX
, kCFStringEncodingUTF8
);
1388 result
= FSUR_IO_SUCCESS
;
1392 free((char*) volHdrPtr
);
1395 free((char*) catalogExtents
);
1398 free((char*)bufPtr
);
1402 } /* GetNameFromHFSPlusVolumeStartingAt */
1405 #pragma options align=mac68k
1407 BTNodeDescriptor node
;
1409 } HeaderRec
, *HeaderPtr
;
1410 #pragma options align=reset
1415 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1419 GetBTreeNodeInfo(int fd
, off_t hfsPlusVolumeOffset
, u_int32_t blockSize
,
1420 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
,
1421 u_int32_t
*nodeSize
, u_int32_t
*firstLeafNode
)
1424 HeaderRec
* bTreeHeaderPtr
= NULL
;
1426 bTreeHeaderPtr
= (HeaderRec
*) malloc(HFS_BLOCK_SIZE
);
1427 if (bTreeHeaderPtr
== NULL
)
1428 return (FSUR_IO_FAIL
);
1430 /* Read the b-tree header node */
1432 result
= ReadFile(fd
, bTreeHeaderPtr
, 0, HFS_BLOCK_SIZE
,
1433 hfsPlusVolumeOffset
, blockSize
,
1434 extentCount
, extentList
);
1435 if ( result
== FSUR_IO_FAIL
) {
1437 fprintf(stderr
, "hfs.util: ERROR: reading header node failed\n");
1442 if ( bTreeHeaderPtr
->node
.kind
!= kBTHeaderNode
) {
1443 result
= FSUR_IO_FAIL
;
1445 fprintf(stderr
, "hfs.util: ERROR: bTreeHeaderPtr->node.kind != kBTHeaderNode\n");
1450 *nodeSize
= bTreeHeaderPtr
->header
.nodeSize
;
1452 if (bTreeHeaderPtr
->header
.leafRecords
== 0)
1455 *firstLeafNode
= bTreeHeaderPtr
->header
.firstLeafNode
;
1458 free((char*) bTreeHeaderPtr
);
1462 } /* GetBTreeNodeInfo */
1468 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1472 GetCatalogOverflowExtents(int fd
, off_t hfsPlusVolumeOffset
,
1473 HFSPlusVolumeHeader
*volHdrPtr
,
1474 HFSPlusExtentDescriptor
**catalogExtents
,
1475 u_int32_t
*catalogExtCount
)
1480 BTNodeDescriptor
* bTreeNodeDescriptorPtr
;
1481 HFSPlusExtentDescriptor
* extents
;
1483 char * bufPtr
= NULL
;
1487 listsize
= *catalogExtCount
* sizeof(HFSPlusExtentDescriptor
);
1488 extents
= *catalogExtents
;
1489 offset
= (off_t
)volHdrPtr
->extentsFile
.extents
[0].startBlock
*
1490 (off_t
)volHdrPtr
->blockSize
;
1492 /* Read the header node of the extents B-Tree */
1494 result
= GetBTreeNodeInfo(fd
, hfsPlusVolumeOffset
, volHdrPtr
->blockSize
,
1495 kHFSPlusExtentDensity
, volHdrPtr
->extentsFile
.extents
,
1496 &nodeSize
, &leafNode
);
1497 if (result
!= FSUR_IO_SUCCESS
|| leafNode
== 0)
1500 /* Calculate the logical position of the first leaf node */
1502 offset
= (off_t
) leafNode
* (off_t
) nodeSize
;
1504 /* Read the first leaf node of the extents b-tree */
1506 bufPtr
= (char *)malloc(nodeSize
);
1508 result
= FSUR_IO_FAIL
;
1512 bTreeNodeDescriptorPtr
= (BTNodeDescriptor
*)bufPtr
;
1515 result
= ReadFile(fd
, bufPtr
, offset
, nodeSize
,
1516 hfsPlusVolumeOffset
, volHdrPtr
->blockSize
,
1517 kHFSPlusExtentDensity
, volHdrPtr
->extentsFile
.extents
);
1518 if ( result
== FSUR_IO_FAIL
) {
1520 fprintf(stderr
, "hfs.util: ERROR: reading first leaf failed\n");
1525 if (bTreeNodeDescriptorPtr
->kind
!= kBTLeafNode
) {
1526 result
= FSUR_IO_FAIL
;
1530 for (i
= 1; i
<= bTreeNodeDescriptorPtr
->numRecords
; ++i
) {
1533 HFSPlusExtentKey
* k
;
1536 * Get the offset (in bytes) of the record from the
1537 * list of offsets at the end of the node
1539 p
= bufPtr
+ nodeSize
- (sizeof(u_int16_t
) * i
);
1542 /* Get a pointer to the record */
1544 p
= bufPtr
+ *v
; /* pointer arithmetic in bytes */
1545 k
= (HFSPlusExtentKey
*)p
;
1547 if (k
->fileID
!= kHFSCatalogFileID
)
1550 /* grow list and copy additional extents */
1551 listsize
+= sizeof(HFSPlusExtentRecord
);
1552 extents
= (HFSPlusExtentDescriptor
*) realloc(extents
, listsize
);
1553 bcopy(p
+ k
->keyLength
+ sizeof(u_int16_t
),
1554 &extents
[*catalogExtCount
], sizeof(HFSPlusExtentRecord
));
1556 *catalogExtCount
+= kHFSPlusExtentDensity
;
1557 *catalogExtents
= extents
;
1560 if ((leafNode
= bTreeNodeDescriptorPtr
->fLink
) != 0) {
1562 offset
= (off_t
) leafNode
* (off_t
) nodeSize
;
1577 * LogicalToPhysical - Map a logical file position and size to volume-relative physical
1578 * position and number of contiguous bytes at that position.
1581 * logicalOffset Logical offset in bytes from start of file
1582 * length Maximum number of bytes to map
1583 * blockSize Number of bytes per allocation block
1584 * extentCount Number of extents in file
1585 * extentList The file's extents
1588 * physicalOffset Physical offset in bytes from start of volume
1589 * availableBytes Number of bytes physically contiguous (up to length)
1591 * Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1593 static int LogicalToPhysical(off_t offset
, ssize_t length
, u_int32_t blockSize
,
1594 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
,
1595 off_t
*physicalOffset
, ssize_t
*availableBytes
)
1598 u_int32_t logicalBlock
;
1600 u_int32_t blockCount
= 0;
1602 /* Determine allocation block containing logicalOffset */
1603 logicalBlock
= offset
/ blockSize
; /* This can't overflow for valid volumes */
1604 offset
%= blockSize
; /* Offset from start of allocation block */
1606 /* Find the extent containing logicalBlock */
1607 for (extent
= 0; extent
< extentCount
; ++extent
)
1609 blockCount
= extentList
[extent
].blockCount
;
1611 if (blockCount
== 0)
1612 return FSUR_IO_FAIL
; /* Tried to map past physical end of file */
1614 if (logicalBlock
< blockCount
)
1615 break; /* Found it! */
1617 logicalBlock
-= blockCount
;
1620 if (extent
>= extentCount
)
1621 return FSUR_IO_FAIL
; /* Tried to map past physical end of file */
1624 * When we get here, extentList[extent] is the extent containing logicalOffset.
1625 * The desired allocation block is logicalBlock blocks into the extent.
1628 /* Compute the physical starting position */
1629 temp
= extentList
[extent
].startBlock
+ logicalBlock
; /* First physical block */
1630 temp
*= blockSize
; /* Byte offset of first physical block */
1631 *physicalOffset
= temp
+ offset
;
1633 /* Compute the available contiguous bytes. */
1634 temp
= blockCount
- logicalBlock
; /* Number of blocks available in extent */
1636 temp
-= offset
; /* Number of bytes available */
1639 *availableBytes
= temp
;
1641 *availableBytes
= length
;
1643 return FSUR_IO_SUCCESS
;
1649 * ReadFile - Read bytes from a file. Handles cases where the starting and/or
1650 * ending position are not allocation or device block aligned.
1653 * fd Descriptor for reading the volume
1654 * buffer The bytes are read into here
1655 * offset Offset in file to start reading
1656 * length Number of bytes to read
1657 * volOffset Byte offset from start of device to start of volume
1658 * blockSize Number of bytes per allocation block
1659 * extentCount Number of extents in file
1660 * extentList The file's exents
1662 * Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1664 static int ReadFile(int fd
, void *buffer
, off_t offset
, ssize_t length
,
1665 off_t volOffset
, u_int32_t blockSize
,
1666 u_int32_t extentCount
, const HFSPlusExtentDescriptor
*extentList
)
1668 int result
= FSUR_IO_SUCCESS
;
1674 result
= LogicalToPhysical(offset
, length
, blockSize
, extentCount
, extentList
,
1675 &physOffset
, &physLength
);
1676 if (result
!= FSUR_IO_SUCCESS
)
1679 result
= readAt(fd
, buffer
, volOffset
+physOffset
, physLength
);
1680 if (result
!= FSUR_IO_SUCCESS
)
1683 length
-= physLength
;
1684 offset
+= physLength
;
1685 buffer
= (char *) buffer
+ physLength
;
1692 -- readAt = lseek() + read()
1694 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1699 readAt( int fd
, void * bufPtr
, off_t offset
, ssize_t length
)
1704 void * rawData
= NULL
;
1707 ssize_t dataOffset
= 0;
1708 int result
= FSUR_IO_SUCCESS
;
1710 if (ioctl(fd
, DKIOCBLKSIZE
, &blocksize
) < 0) {
1712 fprintf(stderr
, "hfs.util: readAt: couldn't determine block size of device.\n");
1714 result
= FSUR_IO_FAIL
;
1717 /* put offset and length in terms of device blocksize */
1718 rawOffset
= offset
/ blocksize
* blocksize
;
1719 dataOffset
= offset
- rawOffset
;
1720 rawLength
= ((length
+ dataOffset
+ blocksize
- 1) / blocksize
) * blocksize
;
1721 rawData
= malloc(rawLength
);
1722 if (rawData
== NULL
) {
1723 result
= FSUR_IO_FAIL
;
1727 lseekResult
= lseek( fd
, rawOffset
, SEEK_SET
);
1728 if ( lseekResult
!= rawOffset
) {
1729 result
= FSUR_IO_FAIL
;
1733 readResult
= read(fd
, rawData
, rawLength
);
1734 if ( readResult
!= rawLength
) {
1736 fprintf(stderr
, "hfs.util: readAt: attempt to read data from device failed (errno = %d)?\n", errno
);
1738 result
= FSUR_IO_FAIL
;
1741 bcopy(rawData
+ dataOffset
, bufPtr
, length
);
1752 -- writeAt = lseek() + write()
1754 -- Returns: FSUR_IO_SUCCESS, FSUR_IO_FAIL
1759 writeAt( int fd
, void * bufPtr
, off_t offset
, ssize_t length
)
1763 ssize_t bytestransferred
;
1764 void * rawData
= NULL
;
1767 ssize_t dataOffset
= 0;
1768 int result
= FSUR_IO_SUCCESS
;
1770 if (ioctl(fd
, DKIOCBLKSIZE
, &blocksize
) < 0) {
1772 fprintf(stderr
, "hfs.util: couldn't determine block size of device.\n");
1774 result
= FSUR_IO_FAIL
;
1777 /* put offset and length in terms of device blocksize */
1778 rawOffset
= offset
/ blocksize
* blocksize
;
1779 dataOffset
= offset
- rawOffset
;
1780 rawLength
= ((length
+ dataOffset
+ blocksize
- 1) / blocksize
) * blocksize
;
1781 rawData
= malloc(rawLength
);
1782 if (rawData
== NULL
) {
1783 result
= FSUR_IO_FAIL
;
1787 deviceoffset
= lseek( fd
, rawOffset
, SEEK_SET
);
1788 if ( deviceoffset
!= rawOffset
) {
1789 result
= FSUR_IO_FAIL
;
1793 /* If the write isn't block-aligned, read the existing data before writing the new data: */
1794 if (((rawOffset
% blocksize
) != 0) || ((rawLength
% blocksize
) != 0)) {
1795 bytestransferred
= read(fd
, rawData
, rawLength
);
1796 if ( bytestransferred
!= rawLength
) {
1798 fprintf(stderr
, "writeAt: attempt to pre-read data from device failed (errno = %d)\n", errno
);
1800 result
= FSUR_IO_FAIL
;
1805 bcopy(bufPtr
, rawData
+ dataOffset
, length
); /* Copy in the new data */
1807 deviceoffset
= lseek( fd
, rawOffset
, SEEK_SET
);
1808 if ( deviceoffset
!= rawOffset
) {
1809 result
= FSUR_IO_FAIL
;
1813 bytestransferred
= write(fd
, rawData
, rawLength
);
1814 if ( bytestransferred
!= rawLength
) {
1816 fprintf(stderr
, "writeAt: attempt to write data to device failed?!");
1818 result
= FSUR_IO_FAIL
;
1823 if (rawData
) free(rawData
);
1830 /******************************************************************************
1832 * V O L U M E S T A T U S D A T A B A S E R O U T I N E S
1834 *****************************************************************************/
1836 #define DBHANDLESIGNATURE 0x75917737
1838 /* Flag values for operation options: */
1839 #define DBMARKPOSITION 1
1841 static char gVSDBPath
[] = "/var/db/volinfo.database";
1843 #define MAXIOMALLOC 16384
1845 /* Database layout: */
1852 char statusFlags
[8];
1859 struct VSDBRecord record
;
1863 #define DBKEYSEPARATOR ':'
1864 #define DBBLANKSPACE ' '
1865 #define DBRECORDTERMINATOR '\n'
1867 /* In-memory data structures: */
1870 unsigned long signature
;
1873 off_t recordPosition
;
1876 typedef struct VSDBState
*VSDBStatePtr
;
1879 unsigned long state
[5];
1880 unsigned long count
[2];
1881 unsigned char buffer
[64];
1886 /* Internal function prototypes: */
1887 static int LockDB(VSDBStatePtr dbstateptr
, int lockmode
);
1888 static int UnlockDB(VSDBStatePtr dbstateptr
);
1890 static int FindVolumeRecordByUUID(VSDBStatePtr dbstateptr
, VolumeUUID
*volumeID
, struct VSDBEntry
*dbentry
, unsigned long options
);
1891 static int AddVolumeRecord(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
);
1892 static int UpdateVolumeRecord(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
);
1893 static int GetVSDBEntry(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
);
1894 static int CompareVSDBKeys(struct VSDBKey
*key1
, struct VSDBKey
*key2
);
1896 static void FormatULong(unsigned long u
, char *s
);
1897 static void FormatUUID(VolumeUUID
*volumeID
, char *UUIDField
);
1898 static void FormatDBKey(VolumeUUID
*volumeID
, struct VSDBKey
*dbkey
);
1899 static void FormatDBRecord(unsigned long volumeStatusFlags
, struct VSDBRecord
*dbrecord
);
1900 static void FormatDBEntry(VolumeUUID
*volumeID
, unsigned long volumeStatusFlags
, struct VSDBEntry
*dbentry
);
1901 static unsigned long ConvertHexStringToULong(const char *hs
, long maxdigits
);
1903 static void SHA1Transform(unsigned long state
[5], unsigned char buffer
[64]);
1904 static void SHA1Init(SHA1_CTX
* context
);
1905 static void SHA1Update(SHA1_CTX
* context
, void* data
, size_t len
);
1906 static void SHA1Final(unsigned char digest
[20], SHA1_CTX
* context
);
1910 /******************************************************************************
1912 * P U B L I S H E D I N T E R F A C E R O U T I N E S
1914 *****************************************************************************/
1916 void GenerateVolumeUUID(VolumeUUID
*newVolumeID
) {
1918 char randomInputBuffer
[26];
1919 unsigned char digest
[20];
1924 char sysctlstring
[128];
1926 struct loadavg sysloadavg
;
1927 struct vmtotal sysvmtotal
;
1930 /* Initialize the SHA-1 context for processing: */
1933 /* Now process successive bits of "random" input to seed the process: */
1935 /* The current system's uptime: */
1937 SHA1Update(&context
, &uptime
, sizeof(uptime
));
1939 /* The kernel's boot time: */
1941 mib
[1] = KERN_BOOTTIME
;
1942 datalen
= sizeof(sysdata
);
1943 sysctl(mib
, 2, &sysdata
, &datalen
, NULL
, 0);
1944 SHA1Update(&context
, &sysdata
, datalen
);
1946 /* The system's host id: */
1948 mib
[1] = KERN_HOSTID
;
1949 datalen
= sizeof(sysdata
);
1950 sysctl(mib
, 2, &sysdata
, &datalen
, NULL
, 0);
1951 SHA1Update(&context
, &sysdata
, datalen
);
1953 /* The system's host name: */
1955 mib
[1] = KERN_HOSTNAME
;
1956 datalen
= sizeof(sysctlstring
);
1957 sysctl(mib
, 2, sysctlstring
, &datalen
, NULL
, 0);
1958 SHA1Update(&context
, sysctlstring
, datalen
);
1960 /* The running kernel's OS release string: */
1962 mib
[1] = KERN_OSRELEASE
;
1963 datalen
= sizeof(sysctlstring
);
1964 sysctl(mib
, 2, sysctlstring
, &datalen
, NULL
, 0);
1965 SHA1Update(&context
, sysctlstring
, datalen
);
1967 /* The running kernel's version string: */
1969 mib
[1] = KERN_VERSION
;
1970 datalen
= sizeof(sysctlstring
);
1971 sysctl(mib
, 2, sysctlstring
, &datalen
, NULL
, 0);
1972 SHA1Update(&context
, sysctlstring
, datalen
);
1974 /* The system's load average: */
1976 mib
[1] = VM_LOADAVG
;
1977 datalen
= sizeof(sysloadavg
);
1978 sysctl(mib
, 2, &sysloadavg
, &datalen
, NULL
, 0);
1979 SHA1Update(&context
, &sysloadavg
, datalen
);
1981 /* The system's VM statistics: */
1984 datalen
= sizeof(sysvmtotal
);
1985 sysctl(mib
, 2, &sysvmtotal
, &datalen
, NULL
, 0);
1986 SHA1Update(&context
, &sysvmtotal
, datalen
);
1988 /* The current GMT (26 ASCII characters): */
1990 strncpy(randomInputBuffer
, asctime(gmtime(&now
)), 26); /* "Mon Mar 27 13:46:26 2000" */
1991 SHA1Update(&context
, randomInputBuffer
, 26);
1993 /* Pad the accumulated input and extract the final digest hash: */
1994 SHA1Final(digest
, &context
);
1996 memcpy(newVolumeID
, digest
, sizeof(*newVolumeID
));
1997 } while ((newVolumeID
->v
.high
== 0) || (newVolumeID
->v
.low
== 0));
2002 void ConvertVolumeUUIDStringToUUID(const char *UUIDString
, VolumeUUID
*volumeID
) {
2005 unsigned long nextdigit
;
2006 unsigned long high
= 0;
2007 unsigned long low
= 0;
2008 unsigned long carry
;
2010 for (i
= 0; (i
< VOLUMEUUIDLENGTH
) && ((c
= UUIDString
[i
]) != (char)0) ; ++i
) {
2011 if ((c
>= '0') && (c
<= '9')) {
2012 nextdigit
= c
- '0';
2013 } else if ((c
>= 'A') && (c
<= 'F')) {
2014 nextdigit
= c
- 'A' + 10;
2015 } else if ((c
>= 'a') && (c
<= 'f')) {
2016 nextdigit
= c
- 'a' + 10;
2020 carry
= ((low
& 0xF0000000) >> 28) & 0x0000000F;
2021 high
= (high
<< 4) | carry
;
2022 low
= (low
<< 4) | nextdigit
;
2025 volumeID
->v
.high
= high
;
2026 volumeID
->v
.low
= low
;
2031 void ConvertVolumeUUIDToString(VolumeUUID
*volumeID
, char *UUIDString
) {
2032 FormatUUID(volumeID
, UUIDString
);
2033 *(UUIDString
+16) = (char)0; /* Append a terminating null character */
2038 int OpenVolumeStatusDB(VolumeStatusDBHandle
*DBHandlePtr
) {
2039 VSDBStatePtr dbstateptr
;
2041 *DBHandlePtr
= NULL
;
2043 dbstateptr
= (VSDBStatePtr
)malloc(sizeof(*dbstateptr
));
2044 if (dbstateptr
== NULL
) {
2048 dbstateptr
->dbmode
= O_RDWR
;
2049 dbstateptr
->dbfile
= open(gVSDBPath
, O_RDWR
| O_CREAT
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
);
2050 if (dbstateptr
->dbfile
== -1) {
2052 The file couldn't be opened for read/write access:
2053 try read-only access before giving up altogether.
2055 dbstateptr
->dbmode
= O_RDONLY
;
2056 dbstateptr
->dbfile
= open(gVSDBPath
, O_RDONLY
| O_CREAT
, S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IROTH
);
2057 if (dbstateptr
->dbfile
== -1) {
2062 dbstateptr
->signature
= DBHANDLESIGNATURE
;
2063 *DBHandlePtr
= (VolumeStatusDBHandle
)dbstateptr
;
2069 int GetVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
, unsigned long *VolumeStatus
) {
2070 VSDBStatePtr dbstateptr
= (VSDBStatePtr
)DBHandle
;
2071 struct VSDBEntry dbentry
;
2074 if (dbstateptr
->signature
!= DBHANDLESIGNATURE
) return EINVAL
;
2076 if ((result
= LockDB(dbstateptr
, LOCK_SH
)) != 0) return result
;
2078 if ((result
= FindVolumeRecordByUUID(dbstateptr
, volumeID
, &dbentry
, 0)) != 0) {
2081 *VolumeStatus
= VOLUME_RECORDED
| ConvertHexStringToULong(dbentry
.record
.statusFlags
, sizeof(dbentry
.record
.statusFlags
));
2086 UnlockDB(dbstateptr
);
2092 int SetVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
, unsigned long VolumeStatus
) {
2093 VSDBStatePtr dbstateptr
= (VSDBStatePtr
)DBHandle
;
2094 struct VSDBEntry dbentry
;
2097 if (dbstateptr
->signature
!= DBHANDLESIGNATURE
) return EINVAL
;
2098 if (VolumeStatus
& ~VOLUME_VALIDSTATUSBITS
) return EINVAL
;
2100 if ((result
= LockDB(dbstateptr
, LOCK_EX
)) != 0) return result
;
2102 FormatDBEntry(volumeID
, VolumeStatus
, &dbentry
);
2103 if ((result
= FindVolumeRecordByUUID(dbstateptr
, volumeID
, NULL
, DBMARKPOSITION
)) == 0) {
2105 fprintf(stderr
,"AddLocalVolumeUUID: found record in database; updating in place.\n");
2107 result
= UpdateVolumeRecord(dbstateptr
, &dbentry
);
2108 } else if (result
== -1) {
2110 fprintf(stderr
,"AddLocalVolumeUUID: record not found in database; appending at end.\n");
2112 result
= AddVolumeRecord(dbstateptr
, &dbentry
);
2117 fsync(dbstateptr
->dbfile
);
2122 UnlockDB(dbstateptr
);
2128 int DeleteVolumeStatusDBEntry(VolumeStatusDBHandle DBHandle
, VolumeUUID
*volumeID
) {
2129 VSDBStatePtr dbstateptr
= (VSDBStatePtr
)DBHandle
;
2132 unsigned long iobuffersize
;
2133 void *iobuffer
= NULL
;
2135 unsigned long iotransfersize
;
2136 unsigned long bytestransferred
;
2138 if (dbstateptr
->signature
!= DBHANDLESIGNATURE
) return EINVAL
;
2140 if ((result
= LockDB(dbstateptr
, LOCK_EX
)) != 0) return result
;
2142 if ((result
= FindVolumeRecordByUUID(dbstateptr
, volumeID
, NULL
, DBMARKPOSITION
)) != 0) {
2144 fprintf(stderr
, "DeleteLocalVolumeUUID: No record with matching volume UUID in DB (result = %d).\n", result
);
2146 if (result
== -1) result
= 0; /* Entry wasn't in the database to begin with? */
2150 fprintf(stderr
, "DeleteLocalVolumeUUID: Found record with matching volume UUID...\n");
2152 if ((result
= stat(gVSDBPath
, &dbinfo
)) != 0) goto ErrExit
;
2153 if ((dbinfo
.st_size
- dbstateptr
->recordPosition
- sizeof(struct VSDBEntry
)) <= MAXIOMALLOC
) {
2154 iobuffersize
= dbinfo
.st_size
- dbstateptr
->recordPosition
- sizeof(struct VSDBEntry
);
2156 iobuffersize
= MAXIOMALLOC
;
2159 fprintf(stderr
, "DeleteLocalVolumeUUID: DB size = 0x%08lx; recordPosition = 0x%08lx;\n",
2160 (unsigned long)dbinfo
.st_size
, (unsigned long)dbstateptr
->recordPosition
);
2161 fprintf(stderr
, "DeleteLocalVolumeUUID: I/O buffer size = 0x%lx\n", iobuffersize
);
2163 if (iobuffersize
> 0) {
2164 iobuffer
= malloc(iobuffersize
);
2165 if (iobuffer
== NULL
) {
2170 dataoffset
= dbstateptr
->recordPosition
+ sizeof(struct VSDBEntry
);
2172 iotransfersize
= dbinfo
.st_size
- dataoffset
;
2173 if (iotransfersize
> 0) {
2174 if (iotransfersize
> iobuffersize
) iotransfersize
= iobuffersize
;
2177 fprintf(stderr
, "DeleteLocalVolumeUUID: reading 0x%08lx bytes starting at 0x%08lx ...\n", iotransfersize
, (unsigned long)dataoffset
);
2179 lseek(dbstateptr
->dbfile
, dataoffset
, SEEK_SET
);
2180 bytestransferred
= read(dbstateptr
->dbfile
, iobuffer
, iotransfersize
);
2181 if (bytestransferred
!= iotransfersize
) {
2187 fprintf(stderr
, "DeleteLocalVolumeUUID: writing 0x%08lx bytes starting at 0x%08lx ...\n", iotransfersize
, (unsigned long)(dataoffset
- (off_t
)sizeof(struct VSDBEntry
)));
2189 lseek(dbstateptr
->dbfile
, dataoffset
- (off_t
)sizeof(struct VSDBEntry
), SEEK_SET
);
2190 bytestransferred
= write(dbstateptr
->dbfile
, iobuffer
, iotransfersize
);
2191 if (bytestransferred
!= iotransfersize
) {
2196 dataoffset
+= (off_t
)iotransfersize
;
2198 } while (iotransfersize
> 0);
2201 fprintf(stderr
, "DeleteLocalVolumeUUID: truncating database file to 0x%08lx bytes.\n", (unsigned long)(dbinfo
.st_size
- (off_t
)(sizeof(struct VSDBEntry
))));
2203 if ((result
= ftruncate(dbstateptr
->dbfile
, dbinfo
.st_size
- (off_t
)(sizeof(struct VSDBEntry
)))) != 0) {
2207 fsync(dbstateptr
->dbfile
);
2213 if (iobuffer
) free(iobuffer
);
2214 UnlockDB(dbstateptr
);
2222 int CloseVolumeStatusDB(VolumeStatusDBHandle DBHandle
) {
2223 VSDBStatePtr dbstateptr
= (VSDBStatePtr
)DBHandle
;
2225 if (dbstateptr
->signature
!= DBHANDLESIGNATURE
) return EINVAL
;
2227 dbstateptr
->signature
= 0;
2229 close(dbstateptr
->dbfile
); /* Nothing we can do about any errors... */
2230 dbstateptr
->dbfile
= 0;
2239 /******************************************************************************
2241 * I N T E R N A L O N L Y D A T A B A S E R O U T I N E S
2243 *****************************************************************************/
2245 static int LockDB(VSDBStatePtr dbstateptr
, int lockmode
) {
2247 fprintf(stderr
, "LockDB: Locking VSDB file...\n");
2249 return flock(dbstateptr
->dbfile
, lockmode
);
2254 static int UnlockDB(VSDBStatePtr dbstateptr
) {
2256 fprintf(stderr
, "UnlockDB: Unlocking VSDB file...\n");
2258 return flock(dbstateptr
->dbfile
, LOCK_UN
);
2263 static int FindVolumeRecordByUUID(VSDBStatePtr dbstateptr
, VolumeUUID
*volumeID
, struct VSDBEntry
*targetEntry
, unsigned long options
) {
2264 struct VSDBKey searchkey
;
2265 struct VSDBEntry dbentry
;
2268 FormatDBKey(volumeID
, &searchkey
);
2269 lseek(dbstateptr
->dbfile
, 0, SEEK_SET
);
2272 result
= GetVSDBEntry(dbstateptr
, &dbentry
);
2273 if ((result
== 0) && (CompareVSDBKeys(&dbentry
.key
, &searchkey
) == 0)) {
2274 if (targetEntry
!= NULL
) {
2276 fprintf(stderr
, "FindVolumeRecordByUUID: copying %d. bytes from %08xl to %08l...\n", sizeof(*targetEntry
), &dbentry
, targetEntry
);
2278 memcpy(targetEntry
, &dbentry
, sizeof(*targetEntry
));
2282 } while (result
== 0);
2289 static int AddVolumeRecord(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
) {
2291 VolumeUUIDString id
;
2295 strncpy(id
, dbentry
->key
.uuid
, sizeof(dbentry
->key
.uuid
));
2296 id
[sizeof(dbentry
->key
.uuid
)] = (char)0;
2297 fprintf(stderr
, "AddVolumeRecord: Adding record for UUID #%s...\n", id
);
2299 lseek(dbstateptr
->dbfile
, 0, SEEK_END
);
2300 return write(dbstateptr
->dbfile
, dbentry
, sizeof(struct VSDBEntry
));
2306 static int UpdateVolumeRecord(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
) {
2308 VolumeUUIDString id
;
2312 strncpy(id
, dbentry
->key
.uuid
, sizeof(dbentry
->key
.uuid
));
2313 id
[sizeof(dbentry
->key
.uuid
)] = (char)0;
2314 fprintf(stderr
, "UpdateVolumeRecord: Updating record for UUID #%s at offset 0x%08lx in database...\n", id
, (unsigned long)dbstateptr
->recordPosition
);
2316 lseek(dbstateptr
->dbfile
, dbstateptr
->recordPosition
, SEEK_SET
);
2318 fprintf(stderr
, "UpdateVolumeRecord: Writing %d. bytes...\n", sizeof(*dbentry
));
2320 return write(dbstateptr
->dbfile
, dbentry
, sizeof(*dbentry
));
2325 static int GetVSDBEntry(VSDBStatePtr dbstateptr
, struct VSDBEntry
*dbentry
) {
2326 struct VSDBEntry entry
;
2329 VolumeUUIDString id
;
2332 dbstateptr
->recordPosition
= lseek(dbstateptr
->dbfile
, 0, SEEK_CUR
);
2333 #if 0 // DEBUG_TRACE
2334 fprintf(stderr
, "GetVSDBEntry: starting reading record at offset 0x%08lx...\n", (unsigned long)dbstateptr
->recordPosition
);
2336 result
= read(dbstateptr
->dbfile
, &entry
, sizeof(entry
));
2337 if ((result
!= sizeof(entry
)) ||
2338 (entry
.keySeparator
!= DBKEYSEPARATOR
) ||
2339 (entry
.space
!= DBBLANKSPACE
) ||
2340 (entry
.terminator
!= DBRECORDTERMINATOR
)) {
2345 strncpy(id
, entry
.key
.uuid
, sizeof(entry
.key
.uuid
));
2346 id
[sizeof(entry
.key
.uuid
)] = (char)0;
2347 fprintf(stderr
, "GetVSDBEntry: returning entry for UUID #%s...\n", id
);
2349 memcpy(dbentry
, &entry
, sizeof(*dbentry
));
2355 static int CompareVSDBKeys(struct VSDBKey
*key1
, struct VSDBKey
*key2
) {
2356 #if 0 // DEBUG_TRACE
2357 VolumeUUIDString id
;
2359 strncpy(id
, key1
->uuid
, sizeof(key1
->uuid
));
2360 id
[sizeof(key1
->uuid
)] = (char)0;
2361 fprintf(stderr
, "CompareVSDBKeys: comparing #%s to ", id
);
2362 strncpy(id
, key2
->uuid
, sizeof(key2
->uuid
));
2363 id
[sizeof(key2
->uuid
)] = (char)0;
2364 fprintf(stderr
, "%s (%d.)...\n", id
, sizeof(key1
->uuid
));
2367 return memcmp(key1
->uuid
, key2
->uuid
, sizeof(key1
->uuid
));
2372 /******************************************************************************
2374 * F O R M A T T I N G A N D C O N V E R S I O N R O U T I N E S
2376 *****************************************************************************/
2378 static void FormatULong(unsigned long u
, char *s
) {
2383 for (i
= 0; i
< 8; ++i
) {
2384 d
= ((u
& 0xF0000000) >> 28) & 0x0000000F;
2386 *digitptr
++ = (char)(d
+ '0');
2388 *digitptr
++ = (char)(d
- 10 + 'A');
2396 static void FormatUUID(VolumeUUID
*volumeID
, char *UUIDField
) {
2397 FormatULong(volumeID
->v
.high
, UUIDField
);
2398 FormatULong(volumeID
->v
.low
, UUIDField
+8);
2404 static void FormatDBKey(VolumeUUID
*volumeID
, struct VSDBKey
*dbkey
) {
2405 FormatUUID(volumeID
, dbkey
->uuid
);
2410 static void FormatDBRecord(unsigned long volumeStatusFlags
, struct VSDBRecord
*dbrecord
) {
2411 FormatULong(volumeStatusFlags
, dbrecord
->statusFlags
);
2416 static void FormatDBEntry(VolumeUUID
*volumeID
, unsigned long volumeStatusFlags
, struct VSDBEntry
*dbentry
) {
2417 FormatDBKey(volumeID
, &dbentry
->key
);
2418 dbentry
->keySeparator
= DBKEYSEPARATOR
;
2419 dbentry
->space
= DBBLANKSPACE
;
2420 FormatDBRecord(volumeStatusFlags
, &dbentry
->record
);
2421 #if 0 // DEBUG_TRACE
2422 dbentry
->terminator
= (char)0;
2423 fprintf(stderr
, "FormatDBEntry: '%s' (%d.)\n", dbentry
, sizeof(*dbentry
));
2425 dbentry
->terminator
= DBRECORDTERMINATOR
;
2430 static unsigned long ConvertHexStringToULong(const char *hs
, long maxdigits
) {
2433 unsigned long nextdigit
;
2437 for (i
= 0; (i
< 8) && ((c
= hs
[i
]) != (char)0) ; ++i
) {
2438 if ((c
>= '0') && (c
<= '9')) {
2439 nextdigit
= c
- '0';
2440 } else if ((c
>= 'A') && (c
<= 'F')) {
2441 nextdigit
= c
- 'A' + 10;
2442 } else if ((c
>= 'a') && (c
<= 'f')) {
2443 nextdigit
= c
- 'a' + 10;
2447 n
= (n
<< 4) + nextdigit
;
2455 /******************************************************************************
2457 * S H A - 1 I M P L E M E N T A T I O N R O U T I N E S
2459 *****************************************************************************/
2462 Derived from SHA-1 in C
2463 By Steve Reid <steve@edmweb.com>
2466 Test Vectors (from FIPS PUB 180-1)
2468 A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
2469 "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
2470 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
2471 A million repetitions of "a"
2472 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
2475 /* #define LITTLE_ENDIAN * This should be #define'd if true. */
2476 /* #define SHA1HANDSOFF * Copies data before messing with it. */
2478 #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
2480 /* blk0() and blk() perform the initial expand. */
2481 /* I got the idea of expanding during the round function from SSLeay */
2482 #ifdef LITTLE_ENDIAN
2483 #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
2484 |(rol(block->l[i],8)&0x00FF00FF))
2486 #define blk0(i) block->l[i]
2488 #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
2489 ^block->l[(i+2)&15]^block->l[i&15],1))
2491 /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
2493 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);printf("t = %2d: %08lX %08lX %08lX %08lX %08lX\n", i, a, b, c, d, e);
2494 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);printf("t = %2d: %08lX %08lX %08lX %08lX %08lX\n", i, a, b, c, d, e);
2495 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);printf("t = %2d: %08lX %08lX %08lX %08lX %08lX\n", i, a, b, c, d, e);
2496 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);printf("t = %2d: %08lX %08lX %08lX %08lX %08lX\n", i, a, b, c, d, e);
2497 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);printf("t = %2d: %08lX %08lX %08lX %08lX %08lX\n", i, a, b, c, d, e);
2499 #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
2500 #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
2501 #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
2502 #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
2503 #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
2507 /* Hash a single 512-bit block. This is the core of the algorithm. */
2509 static void SHA1Transform(unsigned long state
[5], unsigned char buffer
[64])
2511 unsigned long a
, b
, c
, d
, e
;
2513 unsigned char c
[64];
2514 unsigned long l
[16];
2516 CHAR64LONG16
* block
;
2518 static unsigned char workspace
[64];
2519 block
= (CHAR64LONG16
*)workspace
;
2520 memcpy(block
, buffer
, 64);
2522 block
= (CHAR64LONG16
*)buffer
;
2524 /* Copy context->state[] to working vars */
2531 printf(" A B C D E\n");
2532 printf(" -------- -------- -------- -------- --------\n");
2533 printf(" %08lX %08lX %08lX %08lX %08lX\n", a
, b
, c
, d
, e
);
2535 /* 4 rounds of 20 operations each. Loop unrolled. */
2536 R0(a
,b
,c
,d
,e
, 0); R0(e
,a
,b
,c
,d
, 1); R0(d
,e
,a
,b
,c
, 2); R0(c
,d
,e
,a
,b
, 3);
2537 R0(b
,c
,d
,e
,a
, 4); R0(a
,b
,c
,d
,e
, 5); R0(e
,a
,b
,c
,d
, 6); R0(d
,e
,a
,b
,c
, 7);
2538 R0(c
,d
,e
,a
,b
, 8); R0(b
,c
,d
,e
,a
, 9); R0(a
,b
,c
,d
,e
,10); R0(e
,a
,b
,c
,d
,11);
2539 R0(d
,e
,a
,b
,c
,12); R0(c
,d
,e
,a
,b
,13); R0(b
,c
,d
,e
,a
,14); R0(a
,b
,c
,d
,e
,15);
2540 R1(e
,a
,b
,c
,d
,16); R1(d
,e
,a
,b
,c
,17); R1(c
,d
,e
,a
,b
,18); R1(b
,c
,d
,e
,a
,19);
2541 R2(a
,b
,c
,d
,e
,20); R2(e
,a
,b
,c
,d
,21); R2(d
,e
,a
,b
,c
,22); R2(c
,d
,e
,a
,b
,23);
2542 R2(b
,c
,d
,e
,a
,24); R2(a
,b
,c
,d
,e
,25); R2(e
,a
,b
,c
,d
,26); R2(d
,e
,a
,b
,c
,27);
2543 R2(c
,d
,e
,a
,b
,28); R2(b
,c
,d
,e
,a
,29); R2(a
,b
,c
,d
,e
,30); R2(e
,a
,b
,c
,d
,31);
2544 R2(d
,e
,a
,b
,c
,32); R2(c
,d
,e
,a
,b
,33); R2(b
,c
,d
,e
,a
,34); R2(a
,b
,c
,d
,e
,35);
2545 R2(e
,a
,b
,c
,d
,36); R2(d
,e
,a
,b
,c
,37); R2(c
,d
,e
,a
,b
,38); R2(b
,c
,d
,e
,a
,39);
2546 R3(a
,b
,c
,d
,e
,40); R3(e
,a
,b
,c
,d
,41); R3(d
,e
,a
,b
,c
,42); R3(c
,d
,e
,a
,b
,43);
2547 R3(b
,c
,d
,e
,a
,44); R3(a
,b
,c
,d
,e
,45); R3(e
,a
,b
,c
,d
,46); R3(d
,e
,a
,b
,c
,47);
2548 R3(c
,d
,e
,a
,b
,48); R3(b
,c
,d
,e
,a
,49); R3(a
,b
,c
,d
,e
,50); R3(e
,a
,b
,c
,d
,51);
2549 R3(d
,e
,a
,b
,c
,52); R3(c
,d
,e
,a
,b
,53); R3(b
,c
,d
,e
,a
,54); R3(a
,b
,c
,d
,e
,55);
2550 R3(e
,a
,b
,c
,d
,56); R3(d
,e
,a
,b
,c
,57); R3(c
,d
,e
,a
,b
,58); R3(b
,c
,d
,e
,a
,59);
2551 R4(a
,b
,c
,d
,e
,60); R4(e
,a
,b
,c
,d
,61); R4(d
,e
,a
,b
,c
,62); R4(c
,d
,e
,a
,b
,63);
2552 R4(b
,c
,d
,e
,a
,64); R4(a
,b
,c
,d
,e
,65); R4(e
,a
,b
,c
,d
,66); R4(d
,e
,a
,b
,c
,67);
2553 R4(c
,d
,e
,a
,b
,68); R4(b
,c
,d
,e
,a
,69); R4(a
,b
,c
,d
,e
,70); R4(e
,a
,b
,c
,d
,71);
2554 R4(d
,e
,a
,b
,c
,72); R4(c
,d
,e
,a
,b
,73); R4(b
,c
,d
,e
,a
,74); R4(a
,b
,c
,d
,e
,75);
2555 R4(e
,a
,b
,c
,d
,76); R4(d
,e
,a
,b
,c
,77); R4(c
,d
,e
,a
,b
,78); R4(b
,c
,d
,e
,a
,79);
2556 /* Add the working vars back into context.state[] */
2562 /* Wipe variables */
2563 a
= b
= c
= d
= e
= 0;
2567 /* SHA1Init - Initialize new context */
2569 static void SHA1Init(SHA1_CTX
* context
)
2571 /* SHA1 initialization constants */
2572 context
->state
[0] = 0x67452301;
2573 context
->state
[1] = 0xEFCDAB89;
2574 context
->state
[2] = 0x98BADCFE;
2575 context
->state
[3] = 0x10325476;
2576 context
->state
[4] = 0xC3D2E1F0;
2577 context
->count
[0] = context
->count
[1] = 0;
2581 /* Run your data through this. */
2583 static void SHA1Update(SHA1_CTX
* context
, void* data
, size_t len
)
2585 unsigned char *dataptr
= (char *)data
;
2588 j
= (context
->count
[0] >> 3) & 63;
2589 if ((context
->count
[0] += len
<< 3) < (len
<< 3)) context
->count
[1]++;
2590 context
->count
[1] += (len
>> 29);
2591 if ((j
+ len
) > 63) {
2592 memcpy(&context
->buffer
[j
], dataptr
, (i
= 64-j
));
2593 SHA1Transform(context
->state
, context
->buffer
);
2594 for ( ; i
+ 63 < len
; i
+= 64) {
2595 SHA1Transform(context
->state
, &dataptr
[i
]);
2600 memcpy(&context
->buffer
[j
], &dataptr
[i
], len
- i
);
2604 /* Add padding and return the message digest. */
2606 static void SHA1Final(unsigned char digest
[20], SHA1_CTX
* context
)
2609 unsigned char finalcount
[8];
2611 for (i
= 0; i
< 8; i
++) {
2612 finalcount
[i
] = (unsigned char)((context
->count
[(i
>= 4 ? 0 : 1)]
2613 >> ((3-(i
& 3)) * 8) ) & 255); /* Endian independent */
2615 SHA1Update(context
, (unsigned char *)"\200", 1);
2616 while ((context
->count
[0] & 504) != 448) {
2617 SHA1Update(context
, (unsigned char *)"\0", 1);
2619 SHA1Update(context
, finalcount
, 8); /* Should cause a SHA1Transform() */
2620 for (i
= 0; i
< 20; i
++) {
2621 digest
[i
] = (unsigned char)
2622 ((context
->state
[i
>>2] >> ((3-(i
& 3)) * 8) ) & 255);
2624 /* Wipe variables */
2626 memset(context
->buffer
, 0, 64);
2627 memset(context
->state
, 0, 20);
2628 memset(context
->count
, 0, 8);
2629 memset(&finalcount
, 0, 8);
2630 #ifdef SHA1HANDSOFF /* make SHA1Transform overwrite it's own static vars */
2631 SHA1Transform(context
->state
, context
->buffer
);