Home | History | Annotate | Line # | Download | only in hfs
libhfs.c revision 1.16
      1 /*	$NetBSD: libhfs.c,v 1.16 2023/03/01 16:21:14 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2005, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Yevgeny Binder, Dieter Baron, and Pelle Johansson.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  *  All functions and variable types have the prefix "hfs_". All constants
     34  *  have the prefix "HFS_".
     35  *
     36  *  Naming convention for functions which read/write raw, linear data
     37  *	into/from a structured form:
     38  *
     39  *  hfs_read/write[d][a]_foo_bar
     40  *      [d] - read/write from/to [d]isk instead of a memory buffer
     41  *      [a] - [a]llocate output buffer instead of using an existing one
     42  *            (not applicable for writing functions)
     43  *
     44  *  Most functions do not have either of these options, so they will read from
     45  *	or write to a memory buffer, which has been previously allocated by the
     46  *	caller.
     47  */
     48 
     49 #include <sys/cdefs.h>
     50 __KERNEL_RCSID(0, "$NetBSD: libhfs.c,v 1.16 2023/03/01 16:21:14 riastradh Exp $");
     51 
     52 #include "libhfs.h"
     53 
     54 /* global private file/folder keys */
     55 hfs_catalog_key_t hfs_gMetadataDirectoryKey; /* contains HFS+ inodes */
     56 hfs_catalog_key_t hfs_gJournalInfoBlockFileKey;
     57 hfs_catalog_key_t hfs_gJournalBufferFileKey;
     58 hfs_catalog_key_t* hfs_gPrivateObjectKeys[4] = {
     59 	&hfs_gMetadataDirectoryKey,
     60 	&hfs_gJournalInfoBlockFileKey,
     61 	&hfs_gJournalBufferFileKey,
     62 	NULL
     63 };
     64 
     65 
     66 extern uint16_t be16tohp(void** inout_ptr);
     67 extern uint32_t be32tohp(void** inout_ptr);
     68 extern uint64_t be64tohp(void** inout_ptr);
     69 
     70 hfs_callbacks	hfs_gcb;	/* global callbacks */
     71 
     72 /*
     73  * global case folding table
     74  * (lazily initialized; see comments at bottom of hfs_open_volume())
     75  */
     76 unichar_t* hfs_gcft;
     77 
     78 
     79 int hfslib_create_casefolding_table(void);
     80 
     81 #ifdef DLO_DEBUG
     82 #include <stdio.h>
     83 void
     84 dlo_print_key(hfs_catalog_key_t *key)
     85 {
     86 	int i;
     87 
     88 	printf("%ld:[", (long)key->parent_cnid);
     89 	for (i=0; i<key->name.length; i++) {
     90 		if (key->name.unicode[i] < 256
     91 		    && isprint(key->name.unicode[i]))
     92 			putchar(key->name.unicode[i]);
     93 		else
     94 			printf("<%04x>", key->name.unicode[i]);
     95 	}
     96 	printf("]");
     97 }
     98 #endif
     99 
    100 void
    101 hfslib_init(hfs_callbacks* in_callbacks)
    102 {
    103 	unichar_t	temp[256];
    104 
    105 	if (in_callbacks != NULL)
    106 		memcpy(&hfs_gcb, in_callbacks, sizeof(hfs_callbacks));
    107 
    108 	hfs_gcft = NULL;
    109 
    110 	/*
    111 	 * Create keys for the HFS+ "private" files so we can reuse them whenever
    112 	 * we perform a user-visible operation, such as listing directory contents.
    113 	 */
    114 
    115 #define ATOU(str, len) /* quick & dirty ascii-to-unicode conversion */ \
    116 	do{ int i; for(i=0; i<len; i++) temp[i]=str[i]; } \
    117 	while( /*CONSTCOND*/ 0)
    118 
    119 	ATOU("\0\0\0\0HFS+ Private Data", 21);
    120 	hfslib_make_catalog_key(HFS_CNID_ROOT_FOLDER, 21, temp,
    121 		&hfs_gMetadataDirectoryKey);
    122 
    123 	ATOU(".journal_info_block", 19);
    124 	hfslib_make_catalog_key(HFS_CNID_ROOT_FOLDER, 19, temp,
    125 		&hfs_gJournalInfoBlockFileKey);
    126 
    127 	ATOU(".journal", 8);
    128 	hfslib_make_catalog_key(HFS_CNID_ROOT_FOLDER, 8, temp,
    129 		&hfs_gJournalBufferFileKey);
    130 
    131 #undef ATOU
    132 }
    133 
    134 void
    135 hfslib_done(void)
    136 {
    137 	hfs_callback_args	cbargs;
    138 
    139 	if (hfs_gcft != NULL) {
    140 		hfslib_init_cbargs(&cbargs);
    141 		hfslib_free(hfs_gcft, &cbargs);
    142 		hfs_gcft = NULL;
    143 	}
    144 
    145 	return;
    146 }
    147 
    148 void
    149 hfslib_init_cbargs(hfs_callback_args* ptr)
    150 {
    151 	memset(ptr, 0, sizeof(hfs_callback_args));
    152 }
    153 
    154 #if 0
    155 #pragma mark -
    156 #pragma mark High-Level Routines
    157 #endif
    158 
    159 int
    160 hfslib_open_volume(
    161 	const char* in_device,
    162 	int in_readonly,
    163 	hfs_volume* out_vol,
    164 	hfs_callback_args* cbargs)
    165 {
    166 	hfs_catalog_key_t		rootkey;
    167 	hfs_thread_record_t	rootthread;
    168 	hfs_hfs_master_directory_block_t mdb;
    169 	uint16_t	node_rec_sizes[1];
    170 	void*		node_recs[1];
    171 	void*		buffer;
    172 	void*		buffer2;	/* used as temporary pointer for realloc() */
    173 	int			result;
    174 	int		isopen = 0;
    175 
    176 	result = 1;
    177 	buffer = NULL;
    178 
    179 	if (in_device == NULL || out_vol == NULL)
    180 		return 1;
    181 
    182 	out_vol->readonly = in_readonly;
    183 	out_vol->offset = 0;
    184 
    185 	if (hfslib_openvoldevice(out_vol, in_device, cbargs) != 0)
    186 		HFS_LIBERR("could not open device");
    187 	isopen = 1;
    188 
    189 	/*
    190 	 * Read the volume header.
    191 	 */
    192 	buffer = hfslib_malloc(max(sizeof(hfs_volume_header_t),
    193 		sizeof(hfs_hfs_master_directory_block_t)), cbargs);
    194 	if (buffer == NULL)
    195 		HFS_LIBERR("could not allocate volume header");
    196 	if (hfslib_readd(out_vol, buffer, max(sizeof(hfs_volume_header_t),
    197 	    sizeof(hfs_hfs_master_directory_block_t)),
    198 	    HFS_VOLUME_HEAD_RESERVE_SIZE, cbargs) != 0)
    199 		HFS_LIBERR("could not read volume header");
    200 
    201 	if (be16toh(*((uint16_t *)buffer)) == HFS_SIG_HFS) {
    202 		if (hfslib_read_master_directory_block(buffer, &mdb) == 0)
    203 			HFS_LIBERR("could not parse master directory block");
    204 		if (mdb.embedded_signature == HFS_SIG_HFSP) {
    205 			/* XXX: is 512 always correct? */
    206 			out_vol->offset =
    207 			    mdb.first_block * 512
    208 			    + mdb.embedded_extent.start_block
    209 			    * (uint64_t)mdb.block_size;
    210 
    211 			if (hfslib_readd(out_vol, buffer,
    212 			    sizeof(hfs_volume_header_t),
    213 			    HFS_VOLUME_HEAD_RESERVE_SIZE, cbargs) != 0)
    214 				HFS_LIBERR("could not read volume header");
    215 		} else
    216 			HFS_LIBERR("Plain HFS volumes not currently supported");
    217 	}
    218 
    219 	if (hfslib_read_volume_header(buffer, &(out_vol->vh)) == 0)
    220 		HFS_LIBERR("could not parse volume header");
    221 
    222 	/*
    223 	 * Check the volume signature to see if this is a legitimate HFS+ or HFSX
    224 	 * volume. If so, set the key comparison function pointers appropriately.
    225 	 */
    226 	switch(out_vol->vh.signature) {
    227 		case HFS_SIG_HFSP:
    228 			out_vol->keycmp = hfslib_compare_catalog_keys_cf;
    229 			break;
    230 		case HFS_SIG_HFSX:
    231 			out_vol->keycmp = NULL; /* will be set below */
    232 			break;
    233 		default:
    234 			/* HFS_LIBERR("unrecognized volume format"); */
    235 			goto error;
    236 			break;
    237 	}
    238 
    239 	/*
    240 	 * Read the catalog header.
    241 	 */
    242 	buffer2 = hfslib_realloc(buffer, 512, cbargs);
    243 	if (buffer2 == NULL)
    244 		HFS_LIBERR("could not allocate catalog header node");
    245 	buffer = buffer2;
    246 
    247 	/*
    248 	 * We are only interested in the node header, so read the first
    249 	 * 512 bytes and construct the node descriptor by hand.
    250 	 */
    251 	if (hfslib_readd(out_vol, buffer, 512,
    252 	    out_vol->vh.catalog_file.extents[0].start_block *
    253 	    (uint64_t)out_vol->vh.block_size, cbargs) != 0)
    254 		HFS_LIBERR("could not read catalog header node");
    255 	node_recs[0] = (char *)buffer+14;
    256 	node_rec_sizes[0] = 120;
    257 	if (hfslib_read_header_node(node_recs, node_rec_sizes, 1,
    258 	    &out_vol->chr, NULL, NULL) == 0)
    259 		HFS_LIBERR("could not parse catalog header node");
    260 
    261 	/*
    262 	 * If this is an HFSX volume, the catalog header specifies the type of
    263 	 * key comparison method (case-folding or binary compare) we should
    264 	 * use.
    265 	 */
    266 	if (out_vol->keycmp == NULL) {
    267 		if (out_vol->chr.keycomp_type == HFS_KEY_CASEFOLD)
    268 			out_vol->keycmp = hfslib_compare_catalog_keys_cf;
    269 		else if (out_vol->chr.keycomp_type == HFS_KEY_BINARY)
    270 			out_vol->keycmp = hfslib_compare_catalog_keys_bc;
    271 		else
    272 			HFS_LIBERR("undefined key compare method");
    273 	}
    274 
    275 	out_vol->catkeysizefieldsize
    276 	    = (out_vol->chr.attributes & HFS_BIG_KEYS_MASK) ?
    277 	    sizeof(uint16_t) : sizeof(uint8_t);
    278 
    279 	/*
    280 	 * Read the extent overflow header.
    281 	 */
    282 	/*
    283 	 * We are only interested in the node header, so read the first
    284 	 * 512 bytes and construct the node descriptor by hand.
    285 	 * buffer is already 512 bytes long.
    286 	 */
    287 	if (hfslib_readd(out_vol, buffer, 512,
    288 	    out_vol->vh.extents_file.extents[0].start_block *
    289 	    (uint64_t)out_vol->vh.block_size, cbargs) != 0)
    290 		HFS_LIBERR("could not read extent header node");
    291 
    292 	node_recs[0] = (char *)buffer+14;
    293 	node_rec_sizes[0] = 120;
    294 	if (hfslib_read_header_node(node_recs, node_rec_sizes, 1,
    295 	    &out_vol->ehr, NULL, NULL) == 0)
    296 		HFS_LIBERR("could not parse extent header node");
    297 	out_vol->extkeysizefieldsize
    298 	    = (out_vol->ehr.attributes & HFS_BIG_KEYS_MASK) ?
    299 	    sizeof(uint16_t):sizeof(uint8_t);
    300 	/*
    301 	 * Read the journal info block and journal header (if volume journaled).
    302 	 */
    303 	if (out_vol->vh.attributes & (1<<HFS_VOL_JOURNALED)) {
    304 		/* journal info block */
    305 		buffer2 = hfslib_realloc(buffer, sizeof(hfs_journal_info_t), cbargs);
    306 		if (buffer2 == NULL)
    307 			HFS_LIBERR("could not allocate journal info block");
    308 		buffer = buffer2;
    309 
    310 		if (hfslib_readd(out_vol, buffer, sizeof(hfs_journal_info_t),
    311 		    out_vol->vh.journal_info_block * out_vol->vh.block_size,
    312 		    cbargs) != 0)
    313 			HFS_LIBERR("could not read journal info block");
    314 
    315 		if (hfslib_read_journal_info(buffer, &out_vol->jib) == 0)
    316 			HFS_LIBERR("could not parse journal info block");
    317 
    318 		/* journal header */
    319 		buffer2 = hfslib_realloc(buffer, sizeof(hfs_journal_header_t), cbargs);
    320 		if (buffer2 == NULL)
    321 			HFS_LIBERR("could not allocate journal header");
    322 		buffer = buffer2;
    323 
    324 		if (hfslib_readd(out_vol, buffer, sizeof(hfs_journal_header_t),
    325 		    out_vol->jib.offset, cbargs) != 0)
    326 			HFS_LIBERR("could not read journal header");
    327 
    328 		if (hfslib_read_journal_header(buffer, &out_vol->jh) == 0)
    329 			HFS_LIBERR("could not parse journal header");
    330 
    331 		out_vol->journaled = 1;
    332 	} else {
    333 		out_vol->journaled = 0;
    334 	}
    335 
    336 	/*
    337 	 * If this volume uses case-folding comparison and the folding table hasn't
    338 	 * been created yet, do that here. (We don't do this in hfslib_init()
    339 	 * because the table is large and we might never even need to use it.)
    340 	 */
    341 	if (out_vol->keycmp == hfslib_compare_catalog_keys_cf && hfs_gcft == NULL)
    342 		result = hfslib_create_casefolding_table();
    343 	else
    344 		result = 0;
    345 
    346 	/*
    347 	 * Find and store the volume name.
    348 	 */
    349 	if (hfslib_make_catalog_key(HFS_CNID_ROOT_FOLDER, 0, NULL, &rootkey) == 0)
    350 		HFS_LIBERR("could not make root search key");
    351 
    352 	if (hfslib_find_catalog_record_with_key(out_vol, &rootkey,
    353 	    (hfs_catalog_keyed_record_t*)&rootthread, cbargs)!=0)
    354 		HFS_LIBERR("could not find root parent");
    355 
    356 	memcpy(&out_vol->name, &rootthread.name, sizeof(hfs_unistr255_t));
    357 
    358 	/* FALLTHROUGH */
    359 error:
    360 	if (result != 0 && isopen)
    361 		hfslib_close_volume(out_vol, cbargs);
    362 	if (buffer != NULL)
    363 		hfslib_free(buffer, cbargs);
    364 	return result;
    365 }
    366 
    367 void
    368 hfslib_close_volume(hfs_volume* in_vol, hfs_callback_args* cbargs)
    369 {
    370 	if (in_vol == NULL)
    371 		return;
    372 	hfslib_closevoldevice(in_vol, cbargs);
    373 }
    374 
    375 int
    376 hfslib_path_to_cnid(hfs_volume* in_vol,
    377 	hfs_cnid_t in_cnid,
    378 	char** out_unicode,
    379 	uint16_t* out_length,
    380 	hfs_callback_args* cbargs)
    381 {
    382 	hfs_thread_record_t	parent_thread;
    383 	hfs_cnid_t	parent_cnid, child_cnid;
    384 	char*		newpath;
    385 	char*		path;
    386 	int			path_offset = 0;
    387 	int			result;
    388 	uint16_t*	ptr;	/* dummy var */
    389 	uint16_t	uchar;	/* dummy var */
    390 	uint16_t	total_path_length;
    391 
    392 	if (in_vol == NULL || in_cnid == 0 || out_unicode == NULL ||
    393 	    out_length == NULL)
    394 		return 1;
    395 
    396 	result = 1;
    397 	*out_unicode = NULL;
    398 	*out_length = 0;
    399 	path = NULL;
    400 	total_path_length = 0;
    401 
    402 	path = hfslib_malloc(514, cbargs); /* 256 unichars plus a forward slash */
    403 	if (path == NULL)
    404 		return 1;
    405 
    406 	child_cnid = in_cnid;
    407 	parent_cnid = child_cnid; /* skips loop in case in_cnid is root id */
    408 	while (parent_cnid != HFS_CNID_ROOT_FOLDER &&
    409 	    parent_cnid != HFS_CNID_ROOT_PARENT)
    410 	{
    411 		if (child_cnid != in_cnid) {
    412 			newpath = hfslib_realloc(path, 514 + total_path_length*2, cbargs);
    413 			if (newpath == NULL)
    414 				goto exit;
    415 			path = newpath;
    416 			memmove(path + 514, path + path_offset, total_path_length*2);
    417 		}
    418 
    419 		parent_cnid = hfslib_find_parent_thread(in_vol, child_cnid,
    420 		    &parent_thread, cbargs);
    421 		if (parent_cnid == 0)
    422 			goto exit;
    423 
    424 		path_offset = 512 - parent_thread.name.length*2;
    425 
    426 		memcpy(path + path_offset, parent_thread.name.unicode,
    427 			parent_thread.name.length*2);
    428 
    429 		/* Add a forward slash. The unicode string was specified in big endian
    430 		 * format, so convert to core format if necessary. */
    431 		path[512] = 0x00;
    432 		path[513] = 0x2F;
    433 
    434 		ptr = (uint16_t*)path + 256;
    435 		uchar = be16tohp((void*)&ptr);
    436 		*(ptr-1) = uchar;
    437 
    438 		total_path_length += parent_thread.name.length + 1;
    439 		child_cnid = parent_cnid;
    440 	}
    441 
    442 	/*
    443 	 * At this point, 'path' holds a sequence of unicode characters which
    444 	 * represent the absolute path to the given cnid. This string is missing
    445 	 * a terminating null char and an initial forward slash that represents
    446 	 * the root of the filesystem. It most likely also has extra space in
    447 	 * the beginning, due to the fact that we reserve 512 bytes for each path
    448 	 * component and won't usually use all that space. So, we allocate the
    449 	 * final string based on the actual length of the absolute path, plus four
    450 	 * additional bytes (two unichars) for the forward slash and the null char.
    451 	 */
    452 
    453 	*out_unicode = hfslib_malloc((total_path_length+2)*2, cbargs);
    454 	if (*out_unicode == NULL)
    455 		goto exit;
    456 
    457 	/* copy only the bytes that are actually used */
    458 	memcpy(*out_unicode + 2, path + path_offset, total_path_length*2);
    459 
    460 	/* insert forward slash at start */
    461 	uchar = be16toh(0x2F);
    462 	memcpy(*out_unicode, &uchar, sizeof(uchar));
    463 
    464 	/* insert null char at end */
    465 	(*out_unicode)[total_path_length*2+2] = 0x00;
    466 	(*out_unicode)[total_path_length*2+3] = 0x00;
    467 
    468 	*out_length = total_path_length + 1 /* extra for forward slash */ ;
    469 
    470 	result = 0;
    471 
    472 exit:
    473 	if (path != NULL)
    474 		hfslib_free(path, cbargs);
    475 	return result;
    476 }
    477 
    478 hfs_cnid_t
    479 hfslib_find_parent_thread(
    480 	hfs_volume* in_vol,
    481 	hfs_cnid_t in_child,
    482 	hfs_thread_record_t* out_thread,
    483 	hfs_callback_args* cbargs)
    484 {
    485 	hfs_catalog_key_t	childkey;
    486 
    487 	if (in_vol == NULL || in_child == 0 || out_thread == NULL)
    488 		return 0;
    489 
    490 	if (hfslib_make_catalog_key(in_child, 0, NULL, &childkey) == 0)
    491 		return 0;
    492 
    493 	if (hfslib_find_catalog_record_with_key(in_vol, &childkey,
    494 		(hfs_catalog_keyed_record_t*)out_thread, cbargs) != 0)
    495 		return 0;
    496 
    497 	return out_thread->parent_cnid;
    498 }
    499 
    500 /*
    501  * hfslib_find_catalog_record_with_cnid()
    502  *
    503  * Looks up a catalog record by calling hfslib_find_parent_thread() and
    504  * hfslib_find_catalog_record_with_key(). out_key may be NULL; if not, the key
    505  * corresponding to this cnid is stuffed in it. Returns 0 on success.
    506  */
    507 int
    508 hfslib_find_catalog_record_with_cnid(
    509 	hfs_volume* in_vol,
    510 	hfs_cnid_t in_cnid,
    511 	hfs_catalog_keyed_record_t* out_rec,
    512 	hfs_catalog_key_t* out_key,
    513 	hfs_callback_args* cbargs)
    514 {
    515 	hfs_cnid_t					parentcnid;
    516 	hfs_thread_record_t		parentthread;
    517 	hfs_catalog_key_t			key;
    518 
    519 	if (in_vol == NULL || in_cnid == 0 || out_rec == NULL)
    520 		return 0;
    521 
    522 	parentcnid =
    523 		hfslib_find_parent_thread(in_vol, in_cnid, &parentthread, cbargs);
    524 	if (parentcnid == 0)
    525 		HFS_LIBERR("could not find parent thread for cnid %i", in_cnid);
    526 
    527 	if (hfslib_make_catalog_key(parentthread.parent_cnid,
    528 		parentthread.name.length, parentthread.name.unicode, &key) == 0)
    529 		HFS_LIBERR("could not make catalog search key");
    530 
    531 	if (out_key != NULL)
    532 		memcpy(out_key, &key, sizeof(key));
    533 
    534 	return hfslib_find_catalog_record_with_key(in_vol, &key, out_rec, cbargs);
    535 
    536 error:
    537 	return 1;
    538 }
    539 
    540 /* Returns 0 on success, 1 on error, and -1 if record was not found. */
    541 int
    542 hfslib_find_catalog_record_with_key(
    543 	hfs_volume* in_vol,
    544 	hfs_catalog_key_t* in_key,
    545 	hfs_catalog_keyed_record_t* out_rec,
    546 	hfs_callback_args* cbargs)
    547 {
    548 	hfs_node_descriptor_t			nd;
    549 	hfs_extent_descriptor_t*		extents;
    550 	hfs_catalog_keyed_record_t		lastrec;
    551 	hfs_catalog_key_t*	curkey;
    552 	void**				recs;
    553 	void*				buffer;
    554 	uint64_t			bytesread;
    555 	uint32_t			curnode;
    556 	uint16_t*			recsizes;
    557 	uint16_t			numextents;
    558 	uint16_t			recnum;
    559 	int16_t				leaftype;
    560 	int					keycompare;
    561 	int					result;
    562 
    563 	if (in_key == NULL || out_rec == NULL || in_vol == NULL)
    564 		return 1;
    565 
    566 	result = 1;
    567 	buffer = NULL;
    568 	curkey = NULL;
    569 	extents = NULL;
    570 	recs = NULL;
    571 	recsizes = NULL;
    572 
    573 	/* The key takes up over half a kb of ram, which is a lot for the BSD
    574 	 * kernel stack. So allocate it in the heap instead to play it safe. */
    575 	curkey = hfslib_malloc(sizeof(hfs_catalog_key_t), cbargs);
    576 	if (curkey == NULL)
    577 		HFS_LIBERR("could not allocate catalog search key");
    578 
    579 	buffer = hfslib_malloc(in_vol->chr.node_size, cbargs);
    580 	if (buffer == NULL)
    581 		HFS_LIBERR("could not allocate node buffer");
    582 
    583 	numextents = hfslib_get_file_extents(in_vol, HFS_CNID_CATALOG,
    584 		HFS_DATAFORK, &extents, cbargs);
    585 	if (numextents == 0)
    586 		HFS_LIBERR("could not locate fork extents");
    587 
    588 	nd.num_recs = 0;
    589 	curnode = in_vol->chr.root_node;
    590 
    591 #ifdef DLO_DEBUG
    592 	printf("-> key ");
    593 	dlo_print_key(in_key);
    594 	printf("\n");
    595 #endif
    596 
    597 	do {
    598 #ifdef DLO_DEBUG
    599 		printf("--> node %d\n", curnode);
    600 #endif
    601 
    602 		if (hfslib_readd_with_extents(in_vol, buffer,
    603 			&bytesread,in_vol->chr.node_size, curnode * in_vol->chr.node_size,
    604 			extents, numextents, cbargs) != 0)
    605 			HFS_LIBERR("could not read catalog node #%i", curnode);
    606 
    607 		if (hfslib_reada_node(buffer, &nd, &recs, &recsizes, HFS_CATALOG_FILE,
    608 			in_vol, cbargs) == 0)
    609 			HFS_LIBERR("could not parse catalog node #%i", curnode);
    610 
    611 		for (recnum = 0; recnum < nd.num_recs; recnum++)
    612 		{
    613 			leaftype = nd.kind;
    614 			if (hfslib_read_catalog_keyed_record(recs[recnum], out_rec,
    615 				&leaftype, curkey, in_vol) == 0)
    616 				HFS_LIBERR("could not read catalog record #%i",recnum);
    617 
    618 #ifdef DLO_DEBUG
    619 			printf("---> record %d: ", recnum);
    620 			dlo_print_key(curkey);
    621 			fflush(stdout);
    622 #endif
    623 			keycompare = in_vol->keycmp(in_key, curkey);
    624 #ifdef DLO_DEBUG
    625 			printf(" %c\n",
    626 			       keycompare < 0 ? '<'
    627 			       : keycompare == 0 ? '=' : '>');
    628 #endif
    629 
    630 			if (keycompare < 0) {
    631 				/* Check if key is less than *every* record, which should never
    632 				 * happen if the volume is consistent and the key legit. */
    633 				if (recnum == 0)
    634 					HFS_LIBERR("all records greater than key");
    635 
    636 				/* Otherwise, we've found the first record that exceeds our key,
    637 				 * so retrieve the previous record, which is still less... */
    638 				memcpy(out_rec, &lastrec,
    639 					sizeof(hfs_catalog_keyed_record_t));
    640 
    641 				/* ...unless this is a leaf node, which means we've gone from
    642 				 * a key which is smaller than the search key, in the previous
    643 				 * loop, to a key which is larger, in this loop, and that
    644 				 * implies that our search key does not exist on the volume. */
    645 				if (nd.kind == HFS_LEAFNODE)
    646 					result = -1;
    647 				break;
    648 			} else if (keycompare == 0) {
    649 				/* If leaf node, found an exact match. */
    650 				result = 0;
    651 				break;
    652 			} else if (recnum == nd.num_recs-1 && keycompare > 0) {
    653 				/* If leaf node, we've reached the last record with no match,
    654 				 * which means this key is not present on the volume. */
    655 				result = -1;
    656 				break;
    657 			}
    658 
    659 			memcpy(&lastrec, out_rec, sizeof(hfs_catalog_keyed_record_t));
    660 		}
    661 
    662 		if (nd.kind == HFS_INDEXNODE)
    663 			curnode = out_rec->child;
    664 		else if (nd.kind == HFS_LEAFNODE)
    665 			break;
    666 		hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
    667 	} while (nd.kind != HFS_LEAFNODE);
    668 
    669 	/* FALLTHROUGH */
    670 error:
    671 	if (extents != NULL)
    672 		hfslib_free(extents, cbargs);
    673 	hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
    674 	if (curkey != NULL)
    675 		hfslib_free(curkey, cbargs);
    676 	if (buffer != NULL)
    677 		hfslib_free(buffer, cbargs);
    678 	return result;
    679 }
    680 
    681 /* returns 0 on success */
    682 /* XXX Need to look this over and make sure it gracefully handles cases where
    683  * XXX the key is not found. */
    684 int
    685 hfslib_find_extent_record_with_key(hfs_volume* in_vol,
    686 	hfs_extent_key_t* in_key,
    687 	hfs_extent_record_t* out_rec,
    688 	hfs_callback_args* cbargs)
    689 {
    690 	hfs_node_descriptor_t		nd;
    691 	hfs_extent_descriptor_t*	extents;
    692 	hfs_extent_record_t		lastrec;
    693 	hfs_extent_key_t	curkey;
    694 	void**				recs;
    695 	void*				buffer;
    696 	uint64_t			bytesread;
    697 	uint32_t			curnode;
    698 	uint16_t*			recsizes;
    699 	uint16_t			numextents;
    700 	uint16_t			recnum;
    701 	int					keycompare;
    702 	int					result;
    703 
    704 	if (in_vol == NULL || in_key == NULL || out_rec == NULL)
    705 		return 1;
    706 
    707 	result = 1;
    708 	buffer = NULL;
    709 	extents = NULL;
    710 	recs = NULL;
    711 	recsizes = NULL;
    712 
    713 	buffer = hfslib_malloc(in_vol->ehr.node_size, cbargs);
    714 	if (buffer == NULL)
    715 		HFS_LIBERR("could not allocate node buffer");
    716 
    717 	numextents = hfslib_get_file_extents(in_vol, HFS_CNID_EXTENTS,
    718 		HFS_DATAFORK, &extents, cbargs);
    719 	if (numextents == 0)
    720 		HFS_LIBERR("could not locate fork extents");
    721 
    722 	nd.num_recs = 0;
    723 	curnode = in_vol->ehr.root_node;
    724 
    725 	do {
    726 		hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
    727 		recnum = 0;
    728 
    729 		if (hfslib_readd_with_extents(in_vol, buffer, &bytesread,
    730 			in_vol->ehr.node_size, curnode * in_vol->ehr.node_size, extents,
    731 			numextents, cbargs) != 0)
    732 			HFS_LIBERR("could not read extents overflow node #%i", curnode);
    733 
    734 		if (hfslib_reada_node(buffer, &nd, &recs, &recsizes, HFS_EXTENTS_FILE,
    735 			in_vol, cbargs) == 0)
    736 			HFS_LIBERR("could not parse extents overflow node #%i",curnode);
    737 
    738 		for (recnum = 0; recnum < nd.num_recs; recnum++) {
    739 			memcpy(&lastrec, out_rec, sizeof(hfs_extent_record_t));
    740 
    741 			if (hfslib_read_extent_record(recs[recnum], out_rec, nd.kind,
    742 				&curkey, in_vol) == 0)
    743 				HFS_LIBERR("could not read extents record #%i",recnum);
    744 
    745 			keycompare = hfslib_compare_extent_keys(in_key, &curkey);
    746 			if (keycompare < 0) {
    747 				/* this should never happen for any legitimate key */
    748 				if (recnum == 0)
    749 					return 1;
    750 				memcpy(out_rec, &lastrec, sizeof(hfs_extent_record_t));
    751 				break;
    752 			} else if (keycompare == 0 ||
    753 			    (recnum == nd.num_recs-1 && keycompare > 0))
    754 				break;
    755 		}
    756 
    757 		if (nd.kind == HFS_INDEXNODE)
    758 			curnode = *((uint32_t *)out_rec); /* out_rec is a node ptr in this case */
    759 		else if (nd.kind == HFS_LEAFNODE)
    760 			break;
    761 		else
    762 		    HFS_LIBERR("unknwon node type for extents overflow node #%i",curnode);
    763 	} while (nd.kind != HFS_LEAFNODE);
    764 
    765 	result = 0;
    766 
    767 	/* FALLTHROUGH */
    768 
    769 error:
    770 	if (buffer != NULL)
    771 		hfslib_free(buffer, cbargs);
    772 	if (extents != NULL)
    773 		hfslib_free(extents, cbargs);
    774 	hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
    775 	return result;
    776 }
    777 
    778 /* out_extents may be NULL. */
    779 uint16_t
    780 hfslib_get_file_extents(hfs_volume* in_vol,
    781 	hfs_cnid_t in_cnid,
    782 	uint8_t in_forktype,
    783 	hfs_extent_descriptor_t** out_extents,
    784 	hfs_callback_args* cbargs)
    785 {
    786 	hfs_extent_descriptor_t*	dummy;
    787 	hfs_extent_key_t		extentkey;
    788 	hfs_file_record_t		file;
    789 	hfs_catalog_key_t		filekey;
    790 	hfs_thread_record_t	fileparent;
    791 	hfs_fork_t		fork = {.logical_size = 0};
    792 	hfs_extent_record_t	nextextentrec;
    793 	uint32_t	numblocks;
    794 	uint16_t	numextents, n;
    795 
    796 	if (in_vol == NULL || in_cnid == 0)
    797 		return 0;
    798 
    799 	if (out_extents != NULL) {
    800 		*out_extents = hfslib_malloc(sizeof(hfs_extent_descriptor_t), cbargs);
    801 		if (*out_extents == NULL)
    802 			return 0;
    803 	}
    804 
    805 	switch(in_cnid)
    806 	{
    807 		case HFS_CNID_CATALOG:
    808 			fork = in_vol->vh.catalog_file;
    809 			break;
    810 
    811 		case HFS_CNID_EXTENTS:
    812 			fork = in_vol->vh.extents_file;
    813 			break;
    814 
    815 		case HFS_CNID_ALLOCATION:
    816 			fork = in_vol->vh.allocation_file;
    817 			break;
    818 
    819 		case HFS_CNID_ATTRIBUTES:
    820 			fork = in_vol->vh.attributes_file;
    821 			break;
    822 
    823 		case HFS_CNID_STARTUP:
    824 			fork = in_vol->vh.startup_file;
    825 			break;
    826 
    827 		default:
    828 			if (hfslib_find_parent_thread(in_vol, in_cnid, &fileparent,
    829 				cbargs) == 0)
    830 				goto error;
    831 
    832 			if (hfslib_make_catalog_key(fileparent.parent_cnid,
    833 				fileparent.name.length, fileparent.name.unicode, &filekey) == 0)
    834 				goto error;
    835 
    836 			if (hfslib_find_catalog_record_with_key(in_vol, &filekey,
    837 				(hfs_catalog_keyed_record_t*)&file, cbargs) != 0)
    838 				goto error;
    839 
    840 			/* only files have extents, not folders or threads */
    841 			if (file.rec_type != HFS_REC_FILE)
    842 				goto error;
    843 
    844 			if (in_forktype == HFS_DATAFORK)
    845 				fork = file.data_fork;
    846 			else if (in_forktype == HFS_RSRCFORK)
    847 				fork = file.rsrc_fork;
    848 	}
    849 
    850 	numextents = 0;
    851 	numblocks = 0;
    852 	memcpy(&nextextentrec, &fork.extents, sizeof(hfs_extent_record_t));
    853 
    854 	while (1) {
    855 		for (n = 0; n < 8; n++) {
    856 			if (nextextentrec[n].block_count == 0)
    857 				break;
    858 			numblocks += nextextentrec[n].block_count;
    859 		}
    860 		if (out_extents != NULL) {
    861 			dummy = hfslib_realloc(*out_extents,
    862 			    (numextents+n) * sizeof(hfs_extent_descriptor_t),
    863 			    cbargs);
    864 			if (dummy == NULL)
    865 				goto error;
    866 			*out_extents = dummy;
    867 
    868 			memcpy(*out_extents + numextents,
    869 			    &nextextentrec, n*sizeof(hfs_extent_descriptor_t));
    870 		}
    871 		numextents += n;
    872 
    873 		if (numblocks >= fork.total_blocks)
    874 			break;
    875 
    876 		if (hfslib_make_extent_key(in_cnid, in_forktype, numblocks,
    877 			&extentkey) == 0)
    878 			goto error;
    879 
    880 		if (hfslib_find_extent_record_with_key(in_vol, &extentkey,
    881 			&nextextentrec, cbargs) != 0)
    882 			goto error;
    883 	}
    884 
    885 	goto exit;
    886 
    887 error:
    888 	if (out_extents != NULL && *out_extents != NULL) {
    889 		hfslib_free(*out_extents, cbargs);
    890 		*out_extents = NULL;
    891 	}
    892 	return 0;
    893 
    894 exit:
    895 	return numextents;
    896 }
    897 
    898 /*
    899  * hfslib_get_directory_contents()
    900  *
    901  * Finds the immediate children of a given directory CNID and places their
    902  * CNIDs in an array allocated here. The first child is found by doing a
    903  * catalog search that only compares parent CNIDs (ignoring file/folder names)
    904  * and skips over thread records. Then the remaining children are listed in
    905  * ascending order by name, according to the HFS+ spec, so just read off each
    906  * successive leaf node until a different parent CNID is found.
    907  *
    908  * If out_childnames is not NULL, it will be allocated and set to an array of
    909  * hfs_unistr255_t's which correspond to the name of the child with that same
    910  * index.
    911  *
    912  * out_children may be NULL.
    913  *
    914  * Returns 0 on success.
    915  */
    916 int
    917 hfslib_get_directory_contents(
    918 	hfs_volume* in_vol,
    919 	hfs_cnid_t in_dir,
    920 	hfs_catalog_keyed_record_t** out_children,
    921 	hfs_unistr255_t** out_childnames,
    922 	uint32_t* out_numchildren,
    923 	hfs_callback_args* cbargs)
    924 {
    925 	hfs_node_descriptor_t			nd;
    926 	hfs_extent_descriptor_t*		extents;
    927 	hfs_catalog_keyed_record_t		currec;
    928 	hfs_catalog_key_t	curkey;
    929 	void**				recs;
    930 	void*				buffer;
    931 	void*				ptr; /* temporary pointer for realloc() */
    932 	uint64_t			bytesread;
    933 	uint32_t			curnode;
    934 	uint32_t			lastnode;
    935 	uint16_t*			recsizes;
    936 	uint16_t			numextents;
    937 	uint16_t			recnum;
    938 	int16_t				leaftype;
    939 	int					keycompare;
    940 	int					result;
    941 
    942 	if (in_vol == NULL || in_dir == 0 || out_numchildren == NULL)
    943 		return 1;
    944 
    945 	result = 1;
    946 	buffer = NULL;
    947 	extents = NULL;
    948 	lastnode = 0;
    949 	recs = NULL;
    950 	recsizes = NULL;
    951 	*out_numchildren = 0;
    952 	if (out_children != NULL)
    953 		*out_children = NULL;
    954 	if (out_childnames != NULL)
    955 		*out_childnames = NULL;
    956 
    957 	buffer = hfslib_malloc(in_vol->chr.node_size, cbargs);
    958 	if (buffer == NULL)
    959 		HFS_LIBERR("could not allocate node buffer");
    960 
    961 	numextents = hfslib_get_file_extents(in_vol, HFS_CNID_CATALOG,
    962 		HFS_DATAFORK, &extents, cbargs);
    963 	if (numextents == 0)
    964 		HFS_LIBERR("could not locate fork extents");
    965 
    966 	nd.num_recs = 0;
    967 	curnode = in_vol->chr.root_node;
    968 
    969 	while (1)
    970 	{
    971 		hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
    972 		recnum = 0;
    973 
    974 		if (hfslib_readd_with_extents(in_vol, buffer, &bytesread,
    975 			in_vol->chr.node_size, curnode * in_vol->chr.node_size, extents,
    976 			numextents, cbargs) != 0)
    977 			HFS_LIBERR("could not read catalog node #%i", curnode);
    978 
    979 		if (hfslib_reada_node(buffer, &nd, &recs, &recsizes, HFS_CATALOG_FILE,
    980 			in_vol, cbargs) == 0)
    981 			HFS_LIBERR("could not parse catalog node #%i", curnode);
    982 
    983 		for (recnum = 0; recnum < nd.num_recs; recnum++)
    984 		{
    985 			leaftype = nd.kind; /* needed b/c leaftype might be modified now */
    986 			if (hfslib_read_catalog_keyed_record(recs[recnum], &currec,
    987 				&leaftype, &curkey, in_vol) == 0)
    988 				HFS_LIBERR("could not read cat record %i:%i", curnode, recnum);
    989 
    990 			if (nd.kind == HFS_INDEXNODE)
    991 			{
    992 				keycompare = in_dir - curkey.parent_cnid;
    993 				if (keycompare < 0) {
    994 					/* Check if key is less than *every* record, which should
    995 					 * never happen if the volume and key are good. */
    996 					if (recnum == 0)
    997 						HFS_LIBERR("all records greater than key");
    998 
    999 					/* Otherwise, we've found the first record that exceeds our
   1000 					 * key, so retrieve the previous, lesser record. */
   1001 					curnode = lastnode;
   1002 					break;
   1003 				} else if (keycompare == 0) {
   1004 					/*
   1005 					 * Normally, if we were doing a typical catalog lookup with
   1006 					 * both a parent cnid AND a name, keycompare==0 would be an
   1007 					 * exact match. However, since we are ignoring object names
   1008 					 * in this case and only comparing parent cnids, a direct
   1009 					 * match on only a parent cnid could mean that we've found
   1010 					 * an object with that parent cnid BUT which is NOT the
   1011 					 * first object (according to the HFS+ spec) with that
   1012 					 * parent cnid. Thus, when we find a parent cnid match, we
   1013 					 * still go back to the previously found leaf node and start
   1014 					 * checking it for a possible prior instance of an object
   1015 					 * with our desired parent cnid.
   1016 					 */
   1017 					curnode = lastnode;
   1018 					break;
   1019 				} else if (recnum == nd.num_recs-1 && keycompare > 0) {
   1020 					/* Descend to child node if we found an exact match, or if
   1021 					 * this is the last pointer record. */
   1022 					curnode = currec.child;
   1023 					break;
   1024 				}
   1025 
   1026 				lastnode = currec.child;
   1027 			} else {
   1028 				/*
   1029 				 * We have now descended down the hierarchy of index nodes into
   1030 				 * the leaf node that contains the first catalog record with a
   1031 				 * matching parent CNID. Since all leaf nodes are chained
   1032 				 * through their flink/blink, we can simply walk forward through
   1033 				 * this chain, copying every matching non-thread record, until
   1034 				 * we hit a record with a different parent CNID. At that point,
   1035 				 * we've retrieved all of our directory's items, if any.
   1036 				 */
   1037 				curnode = nd.flink;
   1038 
   1039 				if (curkey.parent_cnid < in_dir) {
   1040 					continue;
   1041 				} else if (curkey.parent_cnid == in_dir) {
   1042 					/* Hide files/folders which are supposed to be invisible
   1043 					 * to users, according to the hfs+ spec. */
   1044 					if (hfslib_is_private_file(&curkey))
   1045 						continue;
   1046 
   1047 					/* leaftype has now been set to the catalog record type */
   1048 					if (leaftype == HFS_REC_FLDR || leaftype == HFS_REC_FILE)
   1049 					{
   1050 						(*out_numchildren)++;
   1051 
   1052 						if (out_children != NULL) {
   1053 							ptr = hfslib_realloc(*out_children,
   1054 								*out_numchildren *
   1055 								sizeof(hfs_catalog_keyed_record_t), cbargs);
   1056 							if (ptr == NULL)
   1057 								HFS_LIBERR("could not allocate child record");
   1058 							*out_children = ptr;
   1059 
   1060 							memcpy(&((*out_children)[*out_numchildren-1]),
   1061 								&currec, sizeof(hfs_catalog_keyed_record_t));
   1062 						}
   1063 
   1064 						if (out_childnames != NULL) {
   1065 							ptr = hfslib_realloc(*out_childnames,
   1066 								*out_numchildren * sizeof(hfs_unistr255_t),
   1067 								cbargs);
   1068 							if (ptr == NULL)
   1069 								HFS_LIBERR("could not allocate child name");
   1070 							*out_childnames = ptr;
   1071 
   1072 							memcpy(&((*out_childnames)[*out_numchildren-1]),
   1073 								&curkey.name, sizeof(hfs_unistr255_t));
   1074 						}
   1075 					}
   1076 				} else {
   1077 					result = 0;
   1078 					/* We have just now passed the last item in the desired
   1079 					 * folder (or the folder was empty), so exit. */
   1080 					goto exit;
   1081 				}
   1082 			}
   1083 		}
   1084 	}
   1085 
   1086 	result = 0;
   1087 	goto exit;
   1088 
   1089 error:
   1090 	if (out_children != NULL && *out_children != NULL)
   1091 		hfslib_free(*out_children, cbargs);
   1092 	if (out_childnames != NULL && *out_childnames != NULL)
   1093 		hfslib_free(*out_childnames, cbargs);
   1094 	/* FALLTHROUGH */
   1095 
   1096 exit:
   1097 	if (extents != NULL)
   1098 		hfslib_free(extents, cbargs);
   1099 	hfslib_free_recs(&recs, &recsizes, &nd.num_recs, cbargs);
   1100 	if (buffer != NULL)
   1101 		hfslib_free(buffer, cbargs);
   1102 	return result;
   1103 }
   1104 
   1105 int
   1106 hfslib_is_journal_clean(hfs_volume* in_vol)
   1107 {
   1108 	if (in_vol == NULL)
   1109 		return 0;
   1110 
   1111 	/* return true if no journal */
   1112 	if (!(in_vol->vh.attributes & (1<<HFS_VOL_JOURNALED)))
   1113 		return 1;
   1114 
   1115 	return (in_vol->jh.start == in_vol->jh.end);
   1116 }
   1117 
   1118 /*
   1119  * hfslib_is_private_file()
   1120  *
   1121  * Given a file/folder's key and parent CNID, determines if it should be hidden
   1122  * from the user (e.g., the journal header file or the HFS+ Private Data folder)
   1123  */
   1124 int
   1125 hfslib_is_private_file(hfs_catalog_key_t *filekey)
   1126 {
   1127 	hfs_catalog_key_t* curkey = NULL;
   1128 	int i = 0;
   1129 
   1130 	/*
   1131 	 * According to the HFS+ spec to date, all special objects are located in
   1132 	 * the root directory of the volume, so don't bother going further if the
   1133 	 * requested object is not.
   1134 	 */
   1135 	if (filekey->parent_cnid != HFS_CNID_ROOT_FOLDER)
   1136 		return 0;
   1137 
   1138 	while ((curkey = hfs_gPrivateObjectKeys[i]) != NULL) {
   1139 		/* XXX Always use binary compare here, or use volume's specific key
   1140 		 * XXX comparison routine? */
   1141 		if (filekey->name.length == curkey->name.length &&
   1142 		    memcmp(filekey->name.unicode, curkey->name.unicode,
   1143 				2 * curkey->name.length) == 0)
   1144 			return 1;
   1145 		i++;
   1146 	}
   1147 
   1148 	return 0;
   1149 }
   1150 
   1151 
   1152 /* bool
   1153 hfslib_is_journal_valid(hfs_volume* in_vol)
   1154 {
   1155 	- check magic numbers
   1156 	- check Other Things
   1157 }*/
   1158 
   1159 #if 0
   1160 #pragma mark -
   1161 #pragma mark Major Structures
   1162 #endif
   1163 
   1164 /*
   1165  *	hfslib_read_volume_header()
   1166  *
   1167  *	Reads in_bytes, formats the data appropriately, and places the result
   1168  *	in out_header, which is assumed to be previously allocated. Returns number
   1169  *	of bytes read, 0 if failed.
   1170  */
   1171 
   1172 size_t
   1173 hfslib_read_volume_header(void* in_bytes, hfs_volume_header_t* out_header)
   1174 {
   1175 	void*	ptr;
   1176 	size_t	last_bytes_read;
   1177 	int		i;
   1178 
   1179 	if (in_bytes == NULL || out_header == NULL)
   1180 		return 0;
   1181 
   1182 	ptr = in_bytes;
   1183 
   1184 	out_header->signature = be16tohp(&ptr);
   1185 	out_header->version = be16tohp(&ptr);
   1186 	out_header->attributes = be32tohp(&ptr);
   1187 	out_header->last_mounting_version = be32tohp(&ptr);
   1188 	out_header->journal_info_block = be32tohp(&ptr);
   1189 
   1190 	out_header->date_created = be32tohp(&ptr);
   1191 	out_header->date_modified = be32tohp(&ptr);
   1192 	out_header->date_backedup = be32tohp(&ptr);
   1193 	out_header->date_checked = be32tohp(&ptr);
   1194 
   1195 	out_header->file_count = be32tohp(&ptr);
   1196 	out_header->folder_count = be32tohp(&ptr);
   1197 
   1198 	out_header->block_size = be32tohp(&ptr);
   1199 	out_header->total_blocks = be32tohp(&ptr);
   1200 	out_header->free_blocks = be32tohp(&ptr);
   1201 	out_header->next_alloc_block = be32tohp(&ptr);
   1202 	out_header->rsrc_clump_size = be32tohp(&ptr);
   1203 	out_header->data_clump_size = be32tohp(&ptr);
   1204 	out_header->next_cnid = be32tohp(&ptr);
   1205 
   1206 	out_header->write_count = be32tohp(&ptr);
   1207 	out_header->encodings = be64tohp(&ptr);
   1208 
   1209 	for (i =0 ; i < 8; i++)
   1210 		out_header->finder_info[i] = be32tohp(&ptr);
   1211 
   1212 	if ((last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1213 		&out_header->allocation_file)) == 0)
   1214 		return 0;
   1215 	ptr = (uint8_t*)ptr + last_bytes_read;
   1216 
   1217 	if ((last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1218 		&out_header->extents_file)) == 0)
   1219 		return 0;
   1220 	ptr = (uint8_t*)ptr + last_bytes_read;
   1221 
   1222 	if ((last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1223 		&out_header->catalog_file)) == 0)
   1224 		return 0;
   1225 	ptr = (uint8_t*)ptr + last_bytes_read;
   1226 
   1227 	if ((last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1228 		&out_header->attributes_file)) == 0)
   1229 		return 0;
   1230 	ptr = (uint8_t*)ptr + last_bytes_read;
   1231 
   1232 	if ((last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1233 		&out_header->startup_file)) == 0)
   1234 		return 0;
   1235 	ptr = (uint8_t*)ptr + last_bytes_read;
   1236 
   1237 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1238 }
   1239 
   1240 /*
   1241  *      hfsplib_read_master_directory_block()
   1242  *
   1243  *      Reads in_bytes, formats the data appropriately, and places the result
   1244  *      in out_header, which is assumed to be previously allocated. Returns numb
   1245 er
   1246  *      of bytes read, 0 if failed.
   1247  */
   1248 
   1249 size_t
   1250 hfslib_read_master_directory_block(void* in_bytes,
   1251     hfs_hfs_master_directory_block_t* out_mdr)
   1252 {
   1253 	void*   ptr;
   1254 	int     i;
   1255 
   1256 	if (in_bytes == NULL || out_mdr == NULL)
   1257 		return 0;
   1258 
   1259 	ptr = in_bytes;
   1260 
   1261 	out_mdr->signature = be16tohp(&ptr);
   1262 
   1263 	out_mdr->date_created = be32tohp(&ptr);
   1264 	out_mdr->date_modified = be32tohp(&ptr);
   1265 
   1266 	out_mdr->attributes = be16tohp(&ptr);
   1267 	out_mdr->root_file_count = be16tohp(&ptr);
   1268 	out_mdr->volume_bitmap = be16tohp(&ptr);
   1269 
   1270 	out_mdr->next_alloc_block = be16tohp(&ptr);
   1271 	out_mdr->total_blocks = be16tohp(&ptr);
   1272 	out_mdr->block_size = be32tohp(&ptr);
   1273 
   1274 	out_mdr->clump_size = be32tohp(&ptr);
   1275 	out_mdr->first_block = be16tohp(&ptr);
   1276 	out_mdr->next_cnid = be32tohp(&ptr);
   1277 	out_mdr->free_blocks = be16tohp(&ptr);
   1278 
   1279 	memcpy(out_mdr->volume_name, ptr, 28);
   1280 	ptr = (char *)ptr + 28;
   1281 
   1282 	out_mdr->date_backedup = be32tohp(&ptr);
   1283 	out_mdr->backup_seqnum = be16tohp(&ptr);
   1284 
   1285 	out_mdr->write_count = be32tohp(&ptr);
   1286 
   1287 	out_mdr->extents_clump_size = be32tohp(&ptr);
   1288 	out_mdr->catalog_clump_size = be32tohp(&ptr);
   1289 
   1290 	out_mdr->root_folder_count = be16tohp(&ptr);
   1291 	out_mdr->file_count = be32tohp(&ptr);
   1292 	out_mdr->folder_count = be32tohp(&ptr);
   1293 
   1294 	for (i = 0; i < 8; i++)
   1295 		out_mdr->finder_info[i] = be32tohp(&ptr);
   1296 
   1297 	out_mdr->embedded_signature = be16tohp(&ptr);
   1298 	out_mdr->embedded_extent.start_block = be16tohp(&ptr);
   1299 	out_mdr->embedded_extent.block_count = be16tohp(&ptr);
   1300 
   1301 	out_mdr->extents_size = be32tohp(&ptr);
   1302 	for (i = 0; i < 3; i++) {
   1303 		out_mdr->extents_extents[i].start_block = be16tohp(&ptr);
   1304 		out_mdr->extents_extents[i].block_count = be16tohp(&ptr);
   1305 	}
   1306 
   1307 	out_mdr->catalog_size = be32tohp(&ptr);
   1308 	for (i = 0; i < 3; i++) {
   1309 		out_mdr->catalog_extents[i].start_block = be16tohp(&ptr);
   1310 		out_mdr->catalog_extents[i].block_count = be16tohp(&ptr);
   1311 	}
   1312 
   1313 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1314 }
   1315 
   1316 /*
   1317  *	hfslib_reada_node()
   1318  *
   1319  *	Given the pointer to and size of a buffer containing the entire, raw
   1320  *	contents of any b-tree node from the disk, this function will:
   1321  *
   1322  *		1.	determine the type of node and read its contents
   1323  *		2.	allocate memory for each record and fill it appropriately
   1324  *		3.	set out_record_ptrs_array to point to an array (which it allocates)
   1325  *			which has out_node_descriptor->num_recs many pointers to the
   1326  *			records themselves
   1327  *		4.	allocate out_record_ptr_sizes_array and fill it with the sizes of
   1328  *			each record
   1329  *		5.	return the number of bytes read (i.e., the size of the node)
   1330  *			or 0 on failure
   1331  *
   1332  *	out_node_descriptor must be allocated by the caller and may not be NULL.
   1333  *
   1334  *	out_record_ptrs_array and out_record_ptr_sizes_array must both be specified,
   1335  *	or both be NULL if the caller is not interested in reading the records.
   1336  *
   1337  *	out_record_ptr_sizes_array may be NULL if the caller is not interested in
   1338  *	reading the records, but must not be NULL if out_record_ptrs_array is not.
   1339  *
   1340  *	in_parent_file is HFS_CATALOG_FILE, HFS_EXTENTS_FILE, or
   1341  *	HFS_ATTRIBUTES_FILE, depending on the special file in which this node
   1342  *	resides.
   1343  *
   1344  *	inout_volume must have its catnodesize or extnodesize field (depending on
   1345  *	the parent file) set to the correct value if this is an index, leaf, or map
   1346  *	node. If this is a header node, the field will be set to its correct value.
   1347  */
   1348 size_t
   1349 hfslib_reada_node(void* in_bytes,
   1350 	hfs_node_descriptor_t* out_node_descriptor,
   1351 	void** out_record_ptrs_array[],
   1352 	uint16_t* out_record_ptr_sizes_array[],
   1353 	hfs_btree_file_type in_parent_file,
   1354 	hfs_volume* inout_volume,
   1355 	hfs_callback_args* cbargs)
   1356 {
   1357 	void*		ptr;
   1358 	uint16_t*	rec_offsets;
   1359 	size_t		last_bytes_read;
   1360 	uint16_t	nodesize;
   1361 	uint16_t	numrecords;
   1362 	uint16_t	free_space_offset;	/* offset to free space in node */
   1363 	int			keysizefieldsize;
   1364 	int			i;
   1365 
   1366 	numrecords = 0;
   1367 	rec_offsets = NULL;
   1368 	if (out_record_ptrs_array != NULL)
   1369 		*out_record_ptrs_array = NULL;
   1370 	if (out_record_ptr_sizes_array != NULL)
   1371 		*out_record_ptr_sizes_array = NULL;
   1372 
   1373 	if (in_bytes == NULL || inout_volume == NULL || out_node_descriptor == NULL
   1374 		|| (out_record_ptrs_array == NULL && out_record_ptr_sizes_array != NULL)
   1375 		|| (out_record_ptrs_array != NULL && out_record_ptr_sizes_array == NULL) )
   1376 		goto error;
   1377 
   1378 	ptr = in_bytes;
   1379 
   1380 	out_node_descriptor->flink = be32tohp(&ptr);
   1381 	out_node_descriptor->blink = be32tohp(&ptr);
   1382 	out_node_descriptor->kind = *(((int8_t*)ptr));
   1383 	ptr = (uint8_t*)ptr + 1;
   1384 	out_node_descriptor->height = *(((uint8_t*)ptr));
   1385 	ptr = (uint8_t*)ptr + 1;
   1386 	out_node_descriptor->num_recs = be16tohp(&ptr);
   1387 	out_node_descriptor->reserved = be16tohp(&ptr);
   1388 
   1389 	numrecords = out_node_descriptor->num_recs;
   1390 
   1391 	/*
   1392 	 *	To go any further, we will need to know the size of this node, as well
   1393 	 *	as the width of keyed records' key_len parameters for this btree. If
   1394 	 *	this is an index, leaf, or map node, inout_volume already has the node
   1395 	 *	size set in its catnodesize or extnodesize field and the key length set
   1396 	 *	in the catkeysizefieldsize or extkeysizefieldsize for catalog files and
   1397 	 *	extent files, respectively. However, if this is a header node, this
   1398 	 *	information has not yet been determined, so this is the place to do it.
   1399 	 */
   1400 	if (out_node_descriptor->kind == HFS_HEADERNODE)
   1401 	{
   1402 		hfs_header_record_t	hr;
   1403 		void*		header_rec_offset[1];
   1404 		uint16_t	header_rec_size[1];
   1405 
   1406 		/* sanity check to ensure this is a good header node */
   1407 		if (numrecords != 3)
   1408 			HFS_LIBERR("header node does not have exactly 3 records");
   1409 
   1410 		header_rec_offset[0] = ptr;
   1411 		header_rec_size[0] = sizeof(hfs_header_record_t);
   1412 
   1413 		last_bytes_read = hfslib_read_header_node(header_rec_offset,
   1414 			header_rec_size, 1, &hr, NULL, NULL);
   1415 		if (last_bytes_read == 0)
   1416 			HFS_LIBERR("could not read header node");
   1417 
   1418 		switch(in_parent_file)
   1419 		{
   1420 			case HFS_CATALOG_FILE:
   1421 				inout_volume->chr.node_size = hr.node_size;
   1422 				inout_volume->catkeysizefieldsize =
   1423 					(hr.attributes & HFS_BIG_KEYS_MASK) ?
   1424 						sizeof(uint16_t):sizeof(uint8_t);
   1425 				break;
   1426 
   1427 			case HFS_EXTENTS_FILE:
   1428 				inout_volume->ehr.node_size = hr.node_size;
   1429 				inout_volume->extkeysizefieldsize =
   1430 					(hr.attributes & HFS_BIG_KEYS_MASK) ?
   1431 						sizeof(uint16_t):sizeof(uint8_t);
   1432 				break;
   1433 
   1434 			case HFS_ATTRIBUTES_FILE:
   1435 			default:
   1436 				HFS_LIBERR("invalid parent file type specified");
   1437 				/* NOTREACHED */
   1438 		}
   1439 	}
   1440 
   1441 	switch (in_parent_file)
   1442 	{
   1443 		case HFS_CATALOG_FILE:
   1444 			nodesize = inout_volume->chr.node_size;
   1445 			keysizefieldsize = inout_volume->catkeysizefieldsize;
   1446 			break;
   1447 
   1448 		case HFS_EXTENTS_FILE:
   1449 			nodesize = inout_volume->ehr.node_size;
   1450 			keysizefieldsize = inout_volume->extkeysizefieldsize;
   1451 			break;
   1452 
   1453 		case HFS_ATTRIBUTES_FILE:
   1454 		default:
   1455 			HFS_LIBERR("invalid parent file type specified");
   1456 			/* NOTREACHED */
   1457 	}
   1458 
   1459 	/*
   1460 	 *	Don't care about records so just exit after getting the node descriptor.
   1461 	 *	Note: This happens after the header node code, and not before it, in
   1462 	 *	case the caller calls this function and ignores the record data just to
   1463 	 *	get at the node descriptor, but then tries to call it again on a non-
   1464 	 *	header node without first setting inout_volume->cat/extnodesize.
   1465 	 */
   1466 	if (out_record_ptrs_array == NULL)
   1467 		return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1468 
   1469 	rec_offsets = hfslib_malloc(numrecords * sizeof(uint16_t), cbargs);
   1470 	*out_record_ptr_sizes_array =
   1471 		hfslib_malloc(numrecords * sizeof(uint16_t), cbargs);
   1472 	if (rec_offsets == NULL || *out_record_ptr_sizes_array == NULL)
   1473 		HFS_LIBERR("could not allocate node record offsets");
   1474 
   1475 	*out_record_ptrs_array = hfslib_malloc(numrecords * sizeof(void*), cbargs);
   1476 	if (*out_record_ptrs_array == NULL)
   1477 		HFS_LIBERR("could not allocate node records");
   1478 
   1479 	last_bytes_read = hfslib_reada_node_offsets((uint8_t*)in_bytes + nodesize -
   1480 			numrecords * sizeof(uint16_t), rec_offsets, numrecords);
   1481 	if (last_bytes_read == 0)
   1482 		HFS_LIBERR("could not read node record offsets");
   1483 
   1484 	/*	The size of the last record (i.e. the first one listed in the offsets)
   1485 	 *	must be determined using the offset to the node's free space. */
   1486 	free_space_offset = be16toh(*(uint16_t*)((uint8_t*)in_bytes + nodesize -
   1487 			(numrecords+1) * sizeof(uint16_t)));
   1488 
   1489 	(*out_record_ptr_sizes_array)[numrecords-1] =
   1490 		free_space_offset - rec_offsets[0];
   1491 	for (i = 1; i < numrecords; i++) {
   1492 		(*out_record_ptr_sizes_array)[numrecords-i-1] =
   1493 			rec_offsets[i-1] - rec_offsets[i];
   1494 	}
   1495 
   1496 	for (i = 0; i < numrecords; i++)
   1497 	{
   1498 		(*out_record_ptrs_array)[i] =
   1499 			hfslib_malloc((*out_record_ptr_sizes_array)[i], cbargs);
   1500 
   1501 		if ((*out_record_ptrs_array)[i] == NULL)
   1502 			HFS_LIBERR("could not allocate node record #%i",i);
   1503 
   1504 		/*
   1505 		 *	If this is a keyed node (i.e., a leaf or index node), there are two
   1506 		 *	boundary rules that each record must obey:
   1507 		 *
   1508 		 *		1.	A pad byte must be placed between the key and data if the
   1509 		 *			size of the key plus the size of the key_len field is odd.
   1510 		 *
   1511 		 *		2.	A pad byte must be placed after the data if the data size
   1512 		 *			is odd.
   1513 		 *
   1514 		 *	So in the first case we increment the starting point of the data
   1515 		 *	and correspondingly decrement the record size. In the second case
   1516 		 *	we decrement the record size.
   1517 		 */
   1518 		if (out_node_descriptor->kind == HFS_LEAFNODE ||
   1519 		    out_node_descriptor->kind == HFS_INDEXNODE)
   1520 		{
   1521 			hfs_catalog_key_t	reckey;
   1522 			uint16_t			rectype;
   1523 
   1524 			rectype = out_node_descriptor->kind;
   1525 			last_bytes_read = hfslib_read_catalog_keyed_record(ptr, NULL,
   1526 				&rectype, &reckey, inout_volume);
   1527 			if (last_bytes_read == 0)
   1528 				HFS_LIBERR("could not read node record");
   1529 
   1530 			if ((reckey.key_len + keysizefieldsize) % 2 == 1) {
   1531 				ptr = (uint8_t*)ptr + 1;
   1532 				(*out_record_ptr_sizes_array)[i]--;
   1533 			}
   1534 
   1535 			if ((*out_record_ptr_sizes_array)[i] % 2 == 1)
   1536 				(*out_record_ptr_sizes_array)[i]--;
   1537 		}
   1538 
   1539 		memcpy((*out_record_ptrs_array)[i], ptr,
   1540 				(*out_record_ptr_sizes_array)[i]);
   1541 		ptr = (uint8_t*)ptr + (*out_record_ptr_sizes_array)[i];
   1542 	}
   1543 
   1544 	goto exit;
   1545 
   1546 error:
   1547 	hfslib_free_recs(out_record_ptrs_array, out_record_ptr_sizes_array,
   1548 		&numrecords, cbargs);
   1549 
   1550 	ptr = in_bytes;
   1551 
   1552 	/* warn("error occurred in hfslib_reada_node()"); */
   1553 
   1554 	/* FALLTHROUGH */
   1555 
   1556 exit:
   1557 	if (rec_offsets != NULL)
   1558 		hfslib_free(rec_offsets, cbargs);
   1559 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1560 }
   1561 
   1562 /*
   1563  *	hfslib_reada_node_offsets()
   1564  *
   1565  *	Sets out_offset_array to contain the offsets to each record in the node,
   1566  *	in reverse order. Does not read the free space offset.
   1567  */
   1568 size_t
   1569 hfslib_reada_node_offsets(void* in_bytes, uint16_t* out_offset_array,
   1570     uint16_t numrecords)
   1571 {
   1572 	void*		ptr;
   1573 
   1574 	if (in_bytes == NULL || out_offset_array == NULL)
   1575 		return 0;
   1576 
   1577 	ptr = in_bytes;
   1578 
   1579 	/*
   1580 	 * The offset for record 0 (which is the very last offset in the node) is
   1581 	 * always equal to 14, the size of the node descriptor. So, once we hit
   1582 	 * offset=14, we know this is the last offset. In this way, we don't need
   1583 	 * to know the number of records beforehand.
   1584 	 */
   1585 	out_offset_array--;
   1586 	do {
   1587 		if (numrecords-- == 0)
   1588 			return 0;
   1589 		out_offset_array++;
   1590 		*out_offset_array = be16tohp(&ptr);
   1591 	} while (*out_offset_array != (uint16_t)14);
   1592 
   1593 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1594 }
   1595 
   1596 /*	hfslib_read_header_node()
   1597  *
   1598  *	out_header_record and/or out_map_record may be NULL if the caller doesn't
   1599  *	care about their contents.
   1600  */
   1601 size_t
   1602 hfslib_read_header_node(void** in_recs,
   1603 	uint16_t* in_rec_sizes,
   1604 	uint16_t in_num_recs,
   1605 	hfs_header_record_t* out_hr,
   1606 	void* out_userdata,
   1607 	void* out_map)
   1608 {
   1609 	void*	ptr;
   1610 	int		i;
   1611 
   1612 	KASSERT(out_hr != NULL);
   1613 
   1614 	if (in_recs == NULL || in_rec_sizes == NULL)
   1615 		return 0;
   1616 
   1617 	ptr = in_recs[0];
   1618 	out_hr->tree_depth = be16tohp(&ptr);
   1619 	out_hr->root_node = be32tohp(&ptr);
   1620 	out_hr->leaf_recs = be32tohp(&ptr);
   1621 	out_hr->first_leaf = be32tohp(&ptr);
   1622 	out_hr->last_leaf = be32tohp(&ptr);
   1623 	out_hr->node_size = be16tohp(&ptr);
   1624 	out_hr->max_key_len = be16tohp(&ptr);
   1625 	out_hr->total_nodes = be32tohp(&ptr);
   1626 	out_hr->free_nodes = be32tohp(&ptr);
   1627 	out_hr->reserved = be16tohp(&ptr);
   1628 	out_hr->clump_size = be32tohp(&ptr);
   1629 	out_hr->btree_type = *(((uint8_t*)ptr));
   1630 	ptr = (uint8_t*)ptr + 1;
   1631 	out_hr->keycomp_type = *(((uint8_t*)ptr));
   1632 	ptr = (uint8_t*)ptr + 1;
   1633 	out_hr->attributes = be32tohp(&ptr);
   1634 	for (i = 0; i < 16; i++)
   1635 		out_hr->reserved2[i] = be32tohp(&ptr);
   1636 
   1637 	if (out_userdata != NULL) {
   1638 		memcpy(out_userdata, in_recs[1], in_rec_sizes[1]);
   1639 	}
   1640 	ptr = (uint8_t*)ptr + in_rec_sizes[1];	/* size of user data record */
   1641 
   1642 	if (out_map != NULL) {
   1643 		memcpy(out_map, in_recs[2], in_rec_sizes[2]);
   1644 	}
   1645 	ptr = (uint8_t*)ptr + in_rec_sizes[2];	/* size of map record */
   1646 
   1647 	return ((uint8_t*)ptr - (uint8_t*)in_recs[0]);
   1648 }
   1649 
   1650 /*
   1651  *	hfslib_read_catalog_keyed_record()
   1652  *
   1653  *	out_recdata can be NULL. inout_rectype must be set to either HFS_LEAFNODE
   1654  *	or HFS_INDEXNODE upon calling this function, and will be set by the
   1655  *	function to one of HFS_REC_FLDR, HFS_REC_FILE, HFS_REC_FLDR_THREAD, or
   1656  *	HFS_REC_FLDR_THREAD upon return if the node is a leaf node. If it is an
   1657  *	index node, inout_rectype will not be changed.
   1658  */
   1659 size_t
   1660 hfslib_read_catalog_keyed_record(
   1661 	void* in_bytes,
   1662 	hfs_catalog_keyed_record_t* out_recdata,
   1663 	int16_t* inout_rectype,
   1664 	hfs_catalog_key_t* out_key,
   1665 	hfs_volume* in_volume)
   1666 {
   1667 	void*		ptr;
   1668 	size_t		last_bytes_read;
   1669 
   1670 	if (in_bytes == NULL || out_key == NULL || inout_rectype == NULL)
   1671 		return 0;
   1672 
   1673 	ptr = in_bytes;
   1674 
   1675 	/*	For HFS+, the key length is always a 2-byte number. This is indicated
   1676 	 *	by the HFS_BIG_KEYS_MASK bit in the attributes field of the catalog
   1677 	 *	header record. However, we just assume this bit is set, since all HFS+
   1678 	 *	volumes should have it set anyway. */
   1679 	if (in_volume->catkeysizefieldsize == sizeof(uint16_t))
   1680 		out_key->key_len = be16tohp(&ptr);
   1681 	else if (in_volume->catkeysizefieldsize == sizeof(uint8_t)) {
   1682 		out_key->key_len = *(((uint8_t*)ptr));
   1683 		ptr = (uint8_t*)ptr + 1;
   1684 	}
   1685 
   1686 	out_key->parent_cnid = be32tohp(&ptr);
   1687 
   1688 	last_bytes_read = hfslib_read_unistr255(ptr, &out_key->name);
   1689 	if (last_bytes_read == 0)
   1690 		return 0;
   1691 	ptr = (uint8_t*)ptr + last_bytes_read;
   1692 
   1693 	/* don't waste time if the user just wanted the key and/or record type */
   1694 	if (out_recdata == NULL) {
   1695 		if (*inout_rectype == HFS_LEAFNODE)
   1696 			*inout_rectype = be16tohp(&ptr);
   1697 		else if (*inout_rectype != HFS_INDEXNODE)
   1698 			return 0;	/* should not happen if we were given valid arguments */
   1699 
   1700 		return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1701 	}
   1702 
   1703 	if (*inout_rectype == HFS_INDEXNODE) {
   1704 		out_recdata->child = be32tohp(&ptr);
   1705 	} else {
   1706 		/* first need to determine what kind of record this is */
   1707 		*inout_rectype = be16tohp(&ptr);
   1708 		out_recdata->type = *inout_rectype;
   1709 
   1710 		switch(out_recdata->type)
   1711 		{
   1712 			case HFS_REC_FLDR:
   1713 			{
   1714 				out_recdata->folder.flags = be16tohp(&ptr);
   1715 				out_recdata->folder.valence = be32tohp(&ptr);
   1716 				out_recdata->folder.cnid = be32tohp(&ptr);
   1717 				out_recdata->folder.date_created = be32tohp(&ptr);
   1718 				out_recdata->folder.date_content_mod = be32tohp(&ptr);
   1719 				out_recdata->folder.date_attrib_mod = be32tohp(&ptr);
   1720 				out_recdata->folder.date_accessed = be32tohp(&ptr);
   1721 				out_recdata->folder.date_backedup = be32tohp(&ptr);
   1722 
   1723 				last_bytes_read = hfslib_read_bsd_data(ptr,
   1724 					&out_recdata->folder.bsd);
   1725 				if (last_bytes_read == 0)
   1726 					return 0;
   1727 				ptr = (uint8_t*)ptr + last_bytes_read;
   1728 
   1729 				last_bytes_read = hfslib_read_folder_userinfo(ptr,
   1730 					&out_recdata->folder.user_info);
   1731 				if (last_bytes_read == 0)
   1732 					return 0;
   1733 				ptr = (uint8_t*)ptr + last_bytes_read;
   1734 
   1735 				last_bytes_read = hfslib_read_folder_finderinfo(ptr,
   1736 					&out_recdata->folder.finder_info);
   1737 				if (last_bytes_read == 0)
   1738 					return 0;
   1739 				ptr = (uint8_t*)ptr + last_bytes_read;
   1740 
   1741 				out_recdata->folder.text_encoding = be32tohp(&ptr);
   1742 				out_recdata->folder.reserved = be32tohp(&ptr);
   1743 			}
   1744 			break;
   1745 
   1746 			case HFS_REC_FILE:
   1747 			{
   1748 				out_recdata->file.flags = be16tohp(&ptr);
   1749 				out_recdata->file.reserved = be32tohp(&ptr);
   1750 				out_recdata->file.cnid = be32tohp(&ptr);
   1751 				out_recdata->file.date_created = be32tohp(&ptr);
   1752 				out_recdata->file.date_content_mod = be32tohp(&ptr);
   1753 				out_recdata->file.date_attrib_mod = be32tohp(&ptr);
   1754 				out_recdata->file.date_accessed = be32tohp(&ptr);
   1755 				out_recdata->file.date_backedup = be32tohp(&ptr);
   1756 
   1757 				last_bytes_read = hfslib_read_bsd_data(ptr,
   1758 					&out_recdata->file.bsd);
   1759 				if (last_bytes_read == 0)
   1760 					return 0;
   1761 				ptr = (uint8_t*)ptr + last_bytes_read;
   1762 
   1763 				last_bytes_read = hfslib_read_file_userinfo(ptr,
   1764 					&out_recdata->file.user_info);
   1765 				if (last_bytes_read == 0)
   1766 					return 0;
   1767 				ptr = (uint8_t*)ptr + last_bytes_read;
   1768 
   1769 				last_bytes_read = hfslib_read_file_finderinfo(ptr,
   1770 					&out_recdata->file.finder_info);
   1771 				if (last_bytes_read == 0)
   1772 					return 0;
   1773 				ptr = (uint8_t*)ptr + last_bytes_read;
   1774 
   1775 				out_recdata->file.text_encoding = be32tohp(&ptr);
   1776 				out_recdata->file.reserved2 = be32tohp(&ptr);
   1777 
   1778 				last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1779 					&out_recdata->file.data_fork);
   1780 				if (last_bytes_read == 0)
   1781 					return 0;
   1782 				ptr = (uint8_t*)ptr + last_bytes_read;
   1783 
   1784 				last_bytes_read = hfslib_read_fork_descriptor(ptr,
   1785 					&out_recdata->file.rsrc_fork);
   1786 				if (last_bytes_read == 0)
   1787 					return 0;
   1788 				ptr = (uint8_t*)ptr + last_bytes_read;
   1789 			}
   1790 			break;
   1791 
   1792 			case HFS_REC_FLDR_THREAD:
   1793 			case HFS_REC_FILE_THREAD:
   1794 			{
   1795 				out_recdata->thread.reserved = be16tohp(&ptr);
   1796 				out_recdata->thread.parent_cnid = be32tohp(&ptr);
   1797 
   1798 				last_bytes_read = hfslib_read_unistr255(ptr,
   1799 					&out_recdata->thread.name);
   1800 				if (last_bytes_read == 0)
   1801 					return 0;
   1802 				ptr = (uint8_t*)ptr + last_bytes_read;
   1803 			}
   1804 			break;
   1805 
   1806 			default:
   1807 				return 1;
   1808 				/* NOTREACHED */
   1809 		}
   1810 	}
   1811 
   1812 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1813 }
   1814 
   1815 /* out_rec may be NULL */
   1816 size_t
   1817 hfslib_read_extent_record(
   1818 	void* in_bytes,
   1819 	hfs_extent_record_t* out_rec,
   1820 	hfs_node_kind in_nodekind,
   1821 	hfs_extent_key_t* out_key,
   1822 	hfs_volume* in_volume)
   1823 {
   1824 	void*		ptr;
   1825 	size_t		last_bytes_read;
   1826 
   1827 	if (in_bytes == NULL || out_key == NULL
   1828 	    || (in_nodekind!=HFS_LEAFNODE && in_nodekind!=HFS_INDEXNODE))
   1829 		return 0;
   1830 
   1831 	ptr = in_bytes;
   1832 
   1833 	/* For HFS+, the key length is always a 2-byte number. This is indicated
   1834 	 * by the HFS_BIG_KEYS_MASK bit in the attributes field of the extent
   1835 	 * overflow header record. However, we just assume this bit is set, since
   1836 	 * all HFS+ volumes should have it set anyway. */
   1837 	if (in_volume->extkeysizefieldsize == sizeof(uint16_t))
   1838 		out_key->key_length = be16tohp(&ptr);
   1839 	else if (in_volume->extkeysizefieldsize == sizeof(uint8_t)) {
   1840 		out_key->key_length = *(((uint8_t*)ptr));
   1841 		ptr = (uint8_t*)ptr + 1;
   1842 	}
   1843 
   1844 	out_key->fork_type = *(((uint8_t*)ptr));
   1845 	ptr = (uint8_t*)ptr + 1;
   1846 	out_key->padding = *(((uint8_t*)ptr));
   1847 	ptr = (uint8_t*)ptr + 1;
   1848 	out_key->file_cnid = be32tohp(&ptr);
   1849 	out_key->start_block = be32tohp(&ptr);
   1850 
   1851 	/* don't waste time if the user just wanted the key */
   1852 	if (out_rec == NULL)
   1853 		return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1854 
   1855 	if (in_nodekind == HFS_LEAFNODE) {
   1856 		last_bytes_read = hfslib_read_extent_descriptors(ptr, out_rec);
   1857 		if (last_bytes_read == 0)
   1858 			return 0;
   1859 		ptr = (uint8_t*)ptr + last_bytes_read;
   1860 	} else {
   1861 		/* XXX: this is completely bogus */
   1862 		/*      (uint32_t*)*out_rec = be32tohp(&ptr); */
   1863 	    uint32_t *ptr_32 = (uint32_t *)out_rec;
   1864 		*ptr_32 = be32tohp(&ptr);
   1865 		/* (*out_rec)[0].start_block = be32tohp(&ptr); */
   1866 	}
   1867 
   1868 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1869 }
   1870 
   1871 void
   1872 hfslib_free_recs(
   1873 	void*** inout_node_recs,
   1874 	uint16_t** inout_rec_sizes,
   1875 	uint16_t* inout_num_recs,
   1876 	hfs_callback_args* cbargs)
   1877 {
   1878 	uint16_t	i;
   1879 
   1880 	if (inout_num_recs == NULL || *inout_num_recs == 0)
   1881 		return;
   1882 
   1883 	if (inout_node_recs != NULL && *inout_node_recs != NULL) {
   1884 		for (i = 0 ; i < *inout_num_recs; i++) {
   1885 			if ((*inout_node_recs)[i] != NULL) {
   1886 				hfslib_free((*inout_node_recs)[i], cbargs);
   1887 				(*inout_node_recs)[i] = NULL;
   1888 			}
   1889 		}
   1890 		hfslib_free(*inout_node_recs, cbargs);
   1891 		*inout_node_recs = NULL;
   1892 	}
   1893 
   1894 	if (inout_rec_sizes != NULL && *inout_rec_sizes != NULL) {
   1895 		hfslib_free(*inout_rec_sizes, cbargs);
   1896 		*inout_rec_sizes = NULL;
   1897 	}
   1898 
   1899 	*inout_num_recs = 0;
   1900 }
   1901 
   1902 #if 0
   1903 #pragma mark -
   1904 #pragma mark Individual Fields
   1905 #endif
   1906 
   1907 size_t
   1908 hfslib_read_fork_descriptor(void* in_bytes, hfs_fork_t* out_forkdata)
   1909 {
   1910 	void*	ptr;
   1911 	size_t	last_bytes_read;
   1912 
   1913 	if (in_bytes == NULL || out_forkdata == NULL)
   1914 		return 0;
   1915 
   1916 	ptr = in_bytes;
   1917 
   1918 	out_forkdata->logical_size = be64tohp(&ptr);
   1919 	out_forkdata->clump_size = be32tohp(&ptr);
   1920 	out_forkdata->total_blocks = be32tohp(&ptr);
   1921 
   1922 	if ((last_bytes_read = hfslib_read_extent_descriptors(ptr,
   1923 		&out_forkdata->extents)) == 0)
   1924 		return 0;
   1925 	ptr = (uint8_t*)ptr + last_bytes_read;
   1926 
   1927 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1928 }
   1929 
   1930 size_t
   1931 hfslib_read_extent_descriptors(
   1932 	void* in_bytes,
   1933 	hfs_extent_record_t* out_extentrecord)
   1934 {
   1935 	void*	ptr;
   1936 	int		i;
   1937 
   1938 	if (in_bytes == NULL || out_extentrecord == NULL)
   1939 		return 0;
   1940 
   1941 	ptr = in_bytes;
   1942 
   1943 	for (i = 0; i < 8; i++) {
   1944 		(((hfs_extent_descriptor_t*)*out_extentrecord)[i]).start_block =
   1945 			be32tohp(&ptr);
   1946 		(((hfs_extent_descriptor_t*)*out_extentrecord)[i]).block_count =
   1947 			be32tohp(&ptr);
   1948 	}
   1949 
   1950 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1951 }
   1952 
   1953 size_t
   1954 hfslib_read_unistr255(void* in_bytes, hfs_unistr255_t* out_string)
   1955 {
   1956 	void*		ptr;
   1957 	uint16_t	i, length;
   1958 
   1959 	if (in_bytes == NULL || out_string == NULL)
   1960 		return 0;
   1961 
   1962 	ptr = in_bytes;
   1963 
   1964 	length = be16tohp(&ptr);
   1965 	if (length > 255)
   1966 		length = 255; /* hfs+ folder/file names have a limit of 255 chars */
   1967 	out_string->length = length;
   1968 
   1969 	for (i = 0; i < length; i++) {
   1970 		out_string->unicode[i] = be16tohp(&ptr);
   1971 	}
   1972 
   1973 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1974 }
   1975 
   1976 size_t
   1977 hfslib_read_bsd_data(void* in_bytes, hfs_bsd_data_t* out_perms)
   1978 {
   1979 	void*	ptr;
   1980 
   1981 	if (in_bytes == NULL || out_perms == NULL)
   1982 		return 0;
   1983 
   1984 	ptr = in_bytes;
   1985 
   1986 	out_perms->owner_id = be32tohp(&ptr);
   1987 	out_perms->group_id = be32tohp(&ptr);
   1988 	out_perms->admin_flags = *(((uint8_t*)ptr));
   1989 	ptr = (uint8_t*)ptr + 1;
   1990 	out_perms->owner_flags = *(((uint8_t*)ptr));
   1991 	ptr = (uint8_t*)ptr + 1;
   1992 	out_perms->file_mode = be16tohp(&ptr);
   1993 	out_perms->special.inode_num = be32tohp(&ptr); /* this field is a union */
   1994 
   1995 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   1996 }
   1997 
   1998 size_t
   1999 hfslib_read_file_userinfo(void* in_bytes, hfs_macos_file_info_t* out_info)
   2000 {
   2001 	void*	ptr;
   2002 
   2003 	if (in_bytes == NULL || out_info == NULL)
   2004 		return 0;
   2005 
   2006 	ptr = in_bytes;
   2007 
   2008 	out_info->file_type = be32tohp(&ptr);
   2009 	out_info->file_creator = be32tohp(&ptr);
   2010 	out_info->finder_flags = be16tohp(&ptr);
   2011 	out_info->location.v = be16tohp(&ptr);
   2012 	out_info->location.h = be16tohp(&ptr);
   2013 	out_info->reserved = be16tohp(&ptr);
   2014 
   2015 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2016 }
   2017 
   2018 size_t
   2019 hfslib_read_file_finderinfo(
   2020 	void* in_bytes,
   2021 	hfs_macos_extended_file_info_t* out_info)
   2022 {
   2023 	void*	ptr;
   2024 
   2025 	if (in_bytes == NULL || out_info == NULL)
   2026 		return 0;
   2027 
   2028 	ptr = in_bytes;
   2029 
   2030 #if 0
   2031 	#pragma warn Fill in with real code!
   2032 #endif
   2033 	/* FIXME: Fill in with real code! */
   2034 	memset(out_info, 0, sizeof(*out_info));
   2035 	ptr = (uint8_t*)ptr + sizeof(hfs_macos_extended_file_info_t);
   2036 
   2037 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2038 }
   2039 
   2040 size_t
   2041 hfslib_read_folder_userinfo(void* in_bytes, hfs_macos_folder_info_t* out_info)
   2042 {
   2043 	void*	ptr;
   2044 
   2045 	if (in_bytes == NULL || out_info == NULL)
   2046 		return 0;
   2047 
   2048 	ptr = in_bytes;
   2049 
   2050 #if 0
   2051 	#pragma warn Fill in with real code!
   2052 #endif
   2053 	/* FIXME: Fill in with real code! */
   2054 	memset(out_info, 0, sizeof(*out_info));
   2055 	ptr = (uint8_t*)ptr + sizeof(hfs_macos_folder_info_t);
   2056 
   2057 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2058 }
   2059 
   2060 size_t
   2061 hfslib_read_folder_finderinfo(
   2062 	void* in_bytes,
   2063 	hfs_macos_extended_folder_info_t* out_info)
   2064 {
   2065 	void*	ptr;
   2066 
   2067 	if (in_bytes == NULL || out_info == NULL)
   2068 		return 0;
   2069 
   2070 	ptr = in_bytes;
   2071 
   2072 #if 0
   2073 	#pragma warn Fill in with real code!
   2074 #endif
   2075 	/* FIXME: Fill in with real code! */
   2076 	memset(out_info, 0, sizeof(*out_info));
   2077 	ptr = (uint8_t*)ptr + sizeof(hfs_macos_extended_folder_info_t);
   2078 
   2079 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2080 }
   2081 
   2082 size_t
   2083 hfslib_read_journal_info(void* in_bytes, hfs_journal_info_t* out_info)
   2084 {
   2085 	void*	ptr;
   2086 	int		i;
   2087 
   2088 	if (in_bytes == NULL || out_info == NULL)
   2089 		return 0;
   2090 
   2091 	ptr = in_bytes;
   2092 
   2093 	out_info->flags = be32tohp(&ptr);
   2094 	for (i = 0; i < 8; i++) {
   2095 		out_info->device_signature[i] = be32tohp(&ptr);
   2096 	}
   2097 	out_info->offset = be64tohp(&ptr);
   2098 	out_info->size = be64tohp(&ptr);
   2099 	for (i = 0; i < 32; i++) {
   2100 		out_info->reserved[i] = be64tohp(&ptr);
   2101 	}
   2102 
   2103 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2104 }
   2105 
   2106 size_t
   2107 hfslib_read_journal_header(void* in_bytes, hfs_journal_header_t* out_header)
   2108 {
   2109 	void*	ptr;
   2110 
   2111 	if (in_bytes == NULL || out_header == NULL)
   2112 		return 0;
   2113 
   2114 	ptr = in_bytes;
   2115 
   2116 	out_header->magic = be32tohp(&ptr);
   2117 	out_header->endian = be32tohp(&ptr);
   2118 	out_header->start = be64tohp(&ptr);
   2119 	out_header->end = be64tohp(&ptr);
   2120 	out_header->size = be64tohp(&ptr);
   2121 	out_header->blocklist_header_size = be32tohp(&ptr);
   2122 	out_header->checksum = be32tohp(&ptr);
   2123 	out_header->journal_header_size = be32tohp(&ptr);
   2124 
   2125 	return ((uint8_t*)ptr - (uint8_t*)in_bytes);
   2126 }
   2127 
   2128 #if 0
   2129 #pragma mark -
   2130 #pragma mark Disk Access
   2131 #endif
   2132 
   2133 /*
   2134  *	hfslib_readd_with_extents()
   2135  *
   2136  *	This function reads the contents of a file from the volume, given an array
   2137  *	of extent descriptors which specify where every extent of the file is
   2138  *	located (in addition to the usual pread() arguments). out_bytes is presumed
   2139  *  to exist and be large enough to hold in_length number of bytes. Returns 0
   2140  *	on success.
   2141  */
   2142 int
   2143 hfslib_readd_with_extents(
   2144 	hfs_volume*	in_vol,
   2145 	void*		out_bytes,
   2146 	uint64_t*	out_bytesread,
   2147 	uint64_t	in_length,
   2148 	uint64_t	in_offset,
   2149 	hfs_extent_descriptor_t in_extents[],
   2150 	uint16_t	in_numextents,
   2151 	hfs_callback_args*	cbargs)
   2152 {
   2153 	uint64_t	ext_length, last_offset;
   2154 	uint16_t	i;
   2155 	int			error;
   2156 
   2157 	if (in_vol == NULL || out_bytes == NULL || in_extents == NULL ||
   2158 	    in_numextents == 0 || out_bytesread == NULL)
   2159 		return -1;
   2160 
   2161 	*out_bytesread = 0;
   2162 	last_offset = 0;
   2163 
   2164 	for (i = 0; i < in_numextents; i++)
   2165 	{
   2166 		if (in_extents[i].block_count == 0)
   2167 			continue;
   2168 
   2169 		ext_length = in_extents[i].block_count * in_vol->vh.block_size;
   2170 
   2171 		if (in_offset < last_offset+ext_length
   2172 			&& in_offset+in_length >= last_offset)
   2173 		{
   2174 			uint64_t	isect_start, isect_end;
   2175 
   2176 			isect_start = max(in_offset, last_offset);
   2177 			isect_end = min(in_offset+in_length, last_offset+ext_length);
   2178 			error = hfslib_readd(in_vol, out_bytes, isect_end-isect_start,
   2179 				isect_start - last_offset + (uint64_t)in_extents[i].start_block
   2180 					* in_vol->vh.block_size, cbargs);
   2181 
   2182 			if (error != 0)
   2183 				return error;
   2184 
   2185 			*out_bytesread += isect_end-isect_start;
   2186 			out_bytes = (uint8_t*)out_bytes + isect_end-isect_start;
   2187 		}
   2188 
   2189 		last_offset += ext_length;
   2190 	}
   2191 
   2192 	return 0;
   2193 }
   2194 
   2195 #if 0
   2196 #pragma mark -
   2197 #pragma mark Callback Wrappers
   2198 #endif
   2199 
   2200 void
   2201 hfslib_error(const char* in_format, const char* in_file, int in_line, ...)
   2202 {
   2203 	va_list		ap;
   2204 
   2205 	if (in_format == NULL)
   2206 		return;
   2207 
   2208 	if (hfs_gcb.error != NULL) {
   2209 		va_start(ap, in_line);
   2210 		hfs_gcb.error(in_format, in_file, in_line, ap);
   2211 		va_end(ap);
   2212 	}
   2213 }
   2214 
   2215 void*
   2216 hfslib_malloc(size_t size, hfs_callback_args* cbargs)
   2217 {
   2218 	if (hfs_gcb.allocmem != NULL)
   2219 		return hfs_gcb.allocmem(size, cbargs);
   2220 
   2221 	return NULL;
   2222 }
   2223 
   2224 void*
   2225 hfslib_realloc(void* ptr, size_t size, hfs_callback_args* cbargs)
   2226 {
   2227 	if (hfs_gcb.reallocmem != NULL)
   2228 		return hfs_gcb.reallocmem(ptr, size, cbargs);
   2229 
   2230 	return NULL;
   2231 }
   2232 
   2233 void
   2234 hfslib_free(void* ptr, hfs_callback_args* cbargs)
   2235 {
   2236 	if (hfs_gcb.freemem != NULL && ptr != NULL)
   2237 		hfs_gcb.freemem(ptr, cbargs);
   2238 }
   2239 
   2240 int
   2241 hfslib_openvoldevice(
   2242 	hfs_volume* in_vol,
   2243 	const char* in_device,
   2244 	hfs_callback_args* cbargs)
   2245 {
   2246 	if (hfs_gcb.openvol != NULL && in_device != NULL)
   2247 		return hfs_gcb.openvol(in_vol, in_device, cbargs);
   2248 
   2249 	return 1;
   2250 }
   2251 
   2252 void
   2253 hfslib_closevoldevice(hfs_volume* in_vol, hfs_callback_args* cbargs)
   2254 {
   2255 	if (hfs_gcb.closevol != NULL)
   2256 		hfs_gcb.closevol(in_vol, cbargs);
   2257 }
   2258 
   2259 int
   2260 hfslib_readd(
   2261 	hfs_volume* in_vol,
   2262 	void* out_bytes,
   2263 	uint64_t in_length,
   2264 	uint64_t in_offset,
   2265 	hfs_callback_args* cbargs)
   2266 {
   2267 	if (in_vol == NULL || out_bytes == NULL)
   2268 		return -1;
   2269 
   2270 	if (hfs_gcb.read != NULL)
   2271 		return hfs_gcb.read(in_vol, out_bytes, in_length, in_offset, cbargs);
   2272 
   2273 	return -1;
   2274 }
   2275 
   2276 #if 0
   2277 #pragma mark -
   2278 #pragma mark Other
   2279 #endif
   2280 
   2281 /* returns key length */
   2282 uint16_t
   2283 hfslib_make_catalog_key(
   2284 	hfs_cnid_t in_parent_cnid,
   2285 	uint16_t in_name_len,
   2286 	unichar_t* in_unicode,
   2287 	hfs_catalog_key_t* out_key)
   2288 {
   2289 	if (in_parent_cnid == 0 || (in_name_len > 0 && in_unicode == NULL) ||
   2290 	    out_key == 0)
   2291 		return 0;
   2292 
   2293 	if (in_name_len > 255)
   2294 		in_name_len = 255;
   2295 
   2296 	out_key->key_len = 6 + 2 * in_name_len;
   2297 	out_key->parent_cnid = in_parent_cnid;
   2298 	out_key->name.length = in_name_len;
   2299 	if (in_name_len > 0)
   2300 		memcpy(&out_key->name.unicode, in_unicode, in_name_len*2);
   2301 
   2302 	return out_key->key_len;
   2303 }
   2304 
   2305 /* returns key length */
   2306 uint16_t
   2307 hfslib_make_extent_key(
   2308 	hfs_cnid_t in_cnid,
   2309 	uint8_t in_forktype,
   2310 	uint32_t in_startblock,
   2311 	hfs_extent_key_t* out_key)
   2312 {
   2313 	if (in_cnid == 0 || out_key == 0)
   2314 		return 0;
   2315 
   2316 	out_key->key_length = HFS_MAX_EXT_KEY_LEN;
   2317 	out_key->fork_type = in_forktype;
   2318 	out_key->padding = 0;
   2319 	out_key->file_cnid = in_cnid;
   2320 	out_key->start_block = in_startblock;
   2321 
   2322 	return out_key->key_length;
   2323 }
   2324 
   2325 /* case-folding */
   2326 int
   2327 hfslib_compare_catalog_keys_cf (
   2328 	const void *ap,
   2329 	const void *bp)
   2330 {
   2331 	const hfs_catalog_key_t	*a, *b;
   2332 	unichar_t	ac, bc; /* current character from a, b */
   2333 	unichar_t	lc; /* lowercase version of current character */
   2334 	uint8_t		apos, bpos; /* current character indices */
   2335 
   2336 	a = (const hfs_catalog_key_t*)ap;
   2337 	b = (const hfs_catalog_key_t*)bp;
   2338 
   2339 	if (a->parent_cnid != b->parent_cnid) {
   2340 		return (a->parent_cnid - b->parent_cnid);
   2341 	} else {
   2342 		/*
   2343 		 * The following code implements the pseudocode suggested by
   2344 		 * the HFS+ technote.
   2345 		 */
   2346 
   2347 /*
   2348  * XXX These need to be revised to be endian-independent!
   2349  */
   2350 #define hbyte(x) ((x) >> 8)
   2351 #define lbyte(x) ((x) & 0x00FF)
   2352 
   2353 		apos = bpos = 0;
   2354 		while (1)
   2355 		{
   2356 			/* get next valid character from a */
   2357 			for (lc = 0; lc == 0 && apos < a->name.length; apos++) {
   2358 				ac = a->name.unicode[apos];
   2359 				lc = hfs_gcft[hbyte(ac)];
   2360 				if (lc == 0)
   2361 					lc = ac;
   2362 				else
   2363 					lc = hfs_gcft[lc + lbyte(ac)];
   2364 			};
   2365 			ac = lc;
   2366 
   2367 			/* get next valid character from b */
   2368 			for (lc = 0; lc == 0 && bpos < b->name.length; bpos++) {
   2369 				bc = b->name.unicode[bpos];
   2370 				lc = hfs_gcft[hbyte(bc)];
   2371 				if (lc == 0)
   2372 					lc = bc;
   2373 				else
   2374 					lc = hfs_gcft[lc + lbyte(bc)];
   2375 			};
   2376 			bc = lc;
   2377 
   2378 			/* on end of string ac/bc are 0, otherwise > 0 */
   2379 			if (ac != bc || (ac == 0 && bc == 0))
   2380 				return ac - bc;
   2381 		}
   2382 #undef hbyte
   2383 #undef lbyte
   2384 	}
   2385 }
   2386 
   2387 /* binary compare (i.e., not case folding) */
   2388 int
   2389 hfslib_compare_catalog_keys_bc (
   2390 	const void *ap,
   2391 	const void *bp)
   2392 {
   2393 	int c;
   2394 	const hfs_catalog_key_t *a, *b;
   2395 
   2396 	a = (const hfs_catalog_key_t *) ap;
   2397 	b = (const hfs_catalog_key_t *) bp;
   2398 
   2399 	if (a->parent_cnid == b->parent_cnid)
   2400 	{
   2401 		if (a->name.length == 0 && b->name.length == 0)
   2402 			return 0;
   2403 
   2404 		if (a->name.length == 0)
   2405 			return -1;
   2406 		if (b->name.length == 0)
   2407 			return 1;
   2408 
   2409 		/* FIXME: This does a byte-per-byte comparison, whereas the HFS spec
   2410 		 * mandates a uint16_t chunk comparison. */
   2411 		c = memcmp(a->name.unicode, b->name.unicode,
   2412 			sizeof(unichar_t)*min(a->name.length, b->name.length));
   2413 		if (c != 0)
   2414 			return c;
   2415 		else
   2416 			return (a->name.length - b->name.length);
   2417 	} else {
   2418 		return (a->parent_cnid - b->parent_cnid);
   2419 	}
   2420 }
   2421 
   2422 int
   2423 hfslib_compare_extent_keys (
   2424 	const void *ap,
   2425 	const void *bp)
   2426 {
   2427 	/*
   2428 	 *	Comparison order, in descending importance:
   2429 	 *
   2430 	 *		CNID -> fork type -> start block
   2431 	 */
   2432 
   2433 	const hfs_extent_key_t *a, *b;
   2434 	a = (const hfs_extent_key_t *) ap;
   2435 	b = (const hfs_extent_key_t *) bp;
   2436 
   2437 	if (a->file_cnid == b->file_cnid)
   2438 	{
   2439 		if (a->fork_type == b->fork_type)
   2440 		{
   2441 			if (a->start_block == b->start_block)
   2442 			{
   2443 				return 0;
   2444 			} else {
   2445 				return (a->start_block - b->start_block);
   2446 			}
   2447 		} else {
   2448 			return (a->fork_type - b->fork_type);
   2449 		}
   2450 	} else {
   2451 		return (a->file_cnid - b->file_cnid);
   2452 	}
   2453 }
   2454 
   2455 /* 1+10 tables of 16 rows and 16 columns, each 2 bytes wide = 5632 bytes */
   2456 int
   2457 hfslib_create_casefolding_table(void)
   2458 {
   2459 	hfs_callback_args	cbargs;
   2460 	unichar_t*	t; /* convenience */
   2461 	uint16_t	s; /* current subtable * 256 */
   2462 	uint16_t	i; /* current subtable index (0 to 255) */
   2463 
   2464 	if (hfs_gcft != NULL)
   2465 		return 0; /* no sweat, table already exists */
   2466 
   2467 	hfslib_init_cbargs(&cbargs);
   2468 	hfs_gcft = hfslib_malloc(5632, &cbargs);
   2469 	if (hfs_gcft == NULL)
   2470 		HFS_LIBERR("could not allocate case folding table");
   2471 
   2472 	t = hfs_gcft;	 /* easier to type :) */
   2473 
   2474 	/*
   2475 	 * high byte indices
   2476 	 */
   2477 	s = 0 * 256;
   2478 	memset(t, 0x00, 512);
   2479 	t[s+  0] = 0x0100;
   2480 	t[s+  1] = 0x0200;
   2481 	t[s+  3] = 0x0300;
   2482 	t[s+  4] = 0x0400;
   2483 	t[s+  5] = 0x0500;
   2484 	t[s+ 16] = 0x0600;
   2485 	t[s+ 32] = 0x0700;
   2486 	t[s+ 33] = 0x0800;
   2487 	t[s+254] = 0x0900;
   2488 	t[s+255] = 0x0a00;
   2489 
   2490 	/*
   2491 	 * table 1 (high byte 0x00)
   2492 	 */
   2493 	s = 1 * 256;
   2494 	for (i = 0; i < 65; i++)
   2495 		t[s+i] = i;
   2496 	t[s+  0] = 0xffff;
   2497 	for (i = 65; i < 91; i++)
   2498 		t[s+i] = i + 0x20;
   2499 	for (i = 91; i < 256; i++)
   2500 		t[s+i] = i;
   2501 	t[s+198] = 0x00e6;
   2502 	t[s+208] = 0x00f0;
   2503 	t[s+216] = 0x00f8;
   2504 	t[s+222] = 0x00fe;
   2505 
   2506 	/*
   2507 	 * table 2 (high byte 0x01)
   2508 	 */
   2509 	s = 2 * 256;
   2510 	for (i = 0; i < 256; i++)
   2511 		t[s+i] = i + 0x0100;
   2512 	t[s+ 16] = 0x0111;
   2513 	t[s+ 38] = 0x0127;
   2514 	t[s+ 50] = 0x0133;
   2515 	t[s+ 63] = 0x0140;
   2516 	t[s+ 65] = 0x0142;
   2517 	t[s+ 74] = 0x014b;
   2518 	t[s+ 82] = 0x0153;
   2519 	t[s+102] = 0x0167;
   2520 	t[s+129] = 0x0253;
   2521 	t[s+130] = 0x0183;
   2522 	t[s+132] = 0x0185;
   2523 	t[s+134] = 0x0254;
   2524 	t[s+135] = 0x0188;
   2525 	t[s+137] = 0x0256;
   2526 	t[s+138] = 0x0257;
   2527 	t[s+139] = 0x018c;
   2528 	t[s+142] = 0x01dd;
   2529 	t[s+143] = 0x0259;
   2530 	t[s+144] = 0x025b;
   2531 	t[s+145] = 0x0192;
   2532 	t[s+147] = 0x0260;
   2533 	t[s+148] = 0x0263;
   2534 	t[s+150] = 0x0269;
   2535 	t[s+151] = 0x0268;
   2536 	t[s+152] = 0x0199;
   2537 	t[s+156] = 0x026f;
   2538 	t[s+157] = 0x0272;
   2539 	t[s+159] = 0x0275;
   2540 	t[s+162] = 0x01a3;
   2541 	t[s+164] = 0x01a5;
   2542 	t[s+167] = 0x01a8;
   2543 	t[s+169] = 0x0283;
   2544 	t[s+172] = 0x01ad;
   2545 	t[s+174] = 0x0288;
   2546 	t[s+177] = 0x028a;
   2547 	t[s+178] = 0x028b;
   2548 	t[s+179] = 0x01b4;
   2549 	t[s+181] = 0x01b6;
   2550 	t[s+183] = 0x0292;
   2551 	t[s+184] = 0x01b9;
   2552 	t[s+188] = 0x01bd;
   2553 	t[s+196] = 0x01c6;
   2554 	t[s+197] = 0x01c6;
   2555 	t[s+199] = 0x01c9;
   2556 	t[s+200] = 0x01c9;
   2557 	t[s+202] = 0x01cc;
   2558 	t[s+203] = 0x01cc;
   2559 	t[s+228] = 0x01e5;
   2560 	t[s+241] = 0x01f3;
   2561 	t[s+242] = 0x01f3;
   2562 
   2563 	/*
   2564 	 * table 3 (high byte 0x03)
   2565 	 */
   2566 	s = 3 * 256;
   2567 	for (i = 0; i < 145; i++)
   2568 		t[s+i] = i + 0x0300;
   2569 	for (i = 145; i < 170; i++)
   2570 		t[s+i] = i + 0x0320;
   2571 	t[s+162] = 0x03a2;
   2572 	for (i = 170; i < 256; i++)
   2573 		t[s+i] = i + 0x0300;
   2574 
   2575 	for (i = 226; i < 239; i += 2)
   2576 		t[s+i] = i + 0x0301;
   2577 
   2578 	/*
   2579 	 * table 4 (high byte 0x04)
   2580 	 */
   2581 	s = 4 * 256;
   2582 	for (i = 0; i < 16; i++)
   2583 		t[s+i] = i + 0x0400;
   2584 	t[s+  2] = 0x0452;
   2585 	t[s+  4] = 0x0454;
   2586 	t[s+  5] = 0x0455;
   2587 	t[s+  6] = 0x0456;
   2588 	t[s+  8] = 0x0458;
   2589 	t[s+  9] = 0x0459;
   2590 	t[s+ 10] = 0x045a;
   2591 	t[s+ 11] = 0x045b;
   2592 	t[s+ 15] = 0x045f;
   2593 
   2594 	for (i = 16; i < 48; i++)
   2595 		t[s+i] = i + 0x0420;
   2596 	t[s+ 25] = 0x0419;
   2597 	for (i = 48; i < 256; i++)
   2598 		t[s+i] = i + 0x0400;
   2599 	t[s+195] = 0x04c4;
   2600 	t[s+199] = 0x04c8;
   2601 	t[s+203] = 0x04cc;
   2602 
   2603 	for (i = 96; i < 129; i += 2)
   2604 		t[s+i] = i + 0x0401;
   2605 	t[s+118] = 0x0476;
   2606 	for (i = 144; i < 191; i += 2)
   2607 		t[s+i] = i + 0x0401;
   2608 
   2609 	/*
   2610 	 * table 5 (high byte 0x05)
   2611 	 */
   2612 	s = 5 * 256;
   2613 	for (i = 0; i < 49; i++)
   2614 		t[s+i] = i + 0x0500;
   2615 	for (i = 49; i < 87; i++)
   2616 		t[s+i] = i + 0x0530;
   2617 	for (i = 87; i < 256; i++)
   2618 		t[s+i] = i + 0x0500;
   2619 
   2620 	/*
   2621 	 * table 6 (high byte 0x10)
   2622 	 */
   2623 	s = 6 * 256;
   2624 	for (i = 0; i < 160; i++)
   2625 		t[s+i] = i + 0x1000;
   2626 	for (i = 160; i < 198; i++)
   2627 		t[s+i] = i + 0x1030;
   2628 	for (i = 198; i < 256; i++)
   2629 		t[s+i] = i + 0x1000;
   2630 
   2631 	/*
   2632 	 * table 7 (high byte 0x20)
   2633 	 */
   2634 	s = 7 * 256;
   2635 	for (i = 0; i < 256; i++)
   2636 		t[s+i] = i + 0x2000;
   2637 	{
   2638 		uint8_t zi[15] = { 12,  13,  14,  15,
   2639 						   42,  43,  44,  45,  46,
   2640 						  106, 107, 108, 109, 110, 111};
   2641 
   2642 		for (i = 0; i < 15; i++)
   2643 			t[s+zi[i]] = 0x0000;
   2644 	}
   2645 
   2646 	/*
   2647 	 * table 8 (high byte 0x21)
   2648 	 */
   2649 	s = 8 * 256;
   2650 	for (i = 0; i < 96; i++)
   2651 		t[s+i] = i + 0x2100;
   2652 	for (i = 96; i < 112; i++)
   2653 		t[s+i] = i + 0x2110;
   2654 	for (i = 112; i < 256; i++)
   2655 		t[s+i] = i + 0x2100;
   2656 
   2657 	/*
   2658 	 * table 9 (high byte 0xFE)
   2659 	 */
   2660 	s = 9 * 256;
   2661 	for (i = 0; i < 256; i++)
   2662 		t[s+i] = i + 0xFE00;
   2663 	t[s+255] = 0x0000;
   2664 
   2665 	/*
   2666 	 * table 10 (high byte 0xFF)
   2667 	 */
   2668 	s = 10 * 256;
   2669 	for (i = 0; i < 33; i++)
   2670 		t[s+i] = i + 0xFF00;
   2671 	for (i = 33; i < 59; i++)
   2672 		t[s+i] = i + 0xFF20;
   2673 	for (i = 59; i < 256; i++)
   2674 		t[s+i] = i + 0xFF00;
   2675 
   2676 	return 0;
   2677 
   2678 error:
   2679 	return 1;
   2680 }
   2681 
   2682 int
   2683 hfslib_get_hardlink(hfs_volume *vol, uint32_t inode_num,
   2684 		     hfs_catalog_keyed_record_t *rec,
   2685 		     hfs_callback_args *cbargs)
   2686 {
   2687 	hfs_catalog_keyed_record_t metadata;
   2688 	hfs_catalog_key_t key;
   2689 	char name[16];
   2690 	unichar_t name_uni[16];
   2691 	int i, len;
   2692 
   2693 	/* XXX: cache this */
   2694 	if (hfslib_find_catalog_record_with_key(vol,
   2695 						 &hfs_gMetadataDirectoryKey,
   2696 						 &metadata, cbargs) != 0
   2697 		|| metadata.type != HFS_REC_FLDR)
   2698 		return -1;
   2699 
   2700 	len = snprintf(name, sizeof(name), "iNode%d", inode_num);
   2701 	for (i = 0; i < len; i++)
   2702 		name_uni[i] = name[i];
   2703 
   2704 	if (hfslib_make_catalog_key(metadata.folder.cnid, len, name_uni,
   2705 				     &key) == 0)
   2706 		return -1;
   2707 
   2708 	return hfslib_find_catalog_record_with_key(vol, &key, rec, cbargs);
   2709 }
   2710