Home | History | Annotate | Line # | Download | only in makefs
cd9660.c revision 1.8
      1 /*	$NetBSD: cd9660.c,v 1.8 2005/10/30 09:27:49 dyoung Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
      5  * Perez-Rathke and Ram Vedam.  All rights reserved.
      6  *
      7  * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
      8  * Alan Perez-Rathke and Ram Vedam.
      9  *
     10  * Redistribution and use in source and binary forms, with or
     11  * without modification, are permitted provided that the following
     12  * conditions 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
     16  *    copyright notice, this list of conditions and the following
     17  *    disclaimer in the documentation and/or other materials provided
     18  *    with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN
     21  * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR
     22  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     23  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     24  * DISCLAIMED.  IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN
     25  * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT,
     26  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     27  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
     28  * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     29  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     30  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
     32  * OF SUCH DAMAGE.
     33  */
     34 /*
     35  * Copyright (c) 2001 Wasabi Systems, Inc.
     36  * All rights reserved.
     37  *
     38  * Written by Luke Mewburn for Wasabi Systems, Inc.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *      This product includes software developed for the NetBSD Project by
     51  *      Wasabi Systems, Inc.
     52  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
     53  *    or promote products derived from this software without specific prior
     54  *    written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
     57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 /*
     69  * Copyright (c) 1982, 1986, 1989, 1993
     70  *	The Regents of the University of California.  All rights reserved.
     71  *
     72  * Redistribution and use in source and binary forms, with or without
     73  * modification, are permitted provided that the following conditions
     74  * are met:
     75  * 1. Redistributions of source code must retain the above copyright
     76  *    notice, this list of conditions and the following disclaimer.
     77  * 2. Redistributions in binary form must reproduce the above copyright
     78  *    notice, this list of conditions and the following disclaimer in the
     79  *    documentation and/or other materials provided with the distribution.
     80  * 3. Neither the name of the University nor the names of its contributors
     81  *    may be used to endorse or promote products derived from this software
     82  *    without specific prior written permission.
     83  *
     84  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     85  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     86  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     87  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     88  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     89  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     90  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     91  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     92  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     93  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     94  * SUCH DAMAGE.
     95  *
     96   */
     97 
     98 #if HAVE_NBTOOL_CONFIG_H
     99 #include "nbtool_config.h"
    100 #endif
    101 
    102 #include <sys/cdefs.h>
    103 #if defined(__RCSID) && !defined(__lint)
    104 __RCSID("$NetBSD: cd9660.c,v 1.8 2005/10/30 09:27:49 dyoung Exp $");
    105 #endif  /* !__lint */
    106 
    107 #include <string.h>
    108 #include <ctype.h>
    109 #include <sys/cdefs.h>
    110 #include <sys/param.h>
    111 #include <sys/queue.h>
    112 
    113 #if !HAVE_NBTOOL_CONFIG_H
    114 #include <sys/mount.h>
    115 #endif
    116 
    117 #include "makefs.h"
    118 #include "cd9660.h"
    119 #include "cd9660/iso9660_rrip.h"
    120 
    121 /*
    122  * Global variables
    123  */
    124 iso9660_disk diskStructure;
    125 
    126 static void cd9660_finalize_PVD(void);
    127 static cd9660node *cd9660_allocate_cd9660node(void);
    128 static void cd9660_set_defaults(void);
    129 static int cd9660_arguments_set_string(const char *, const char *, int,
    130     char, char *);
    131 static void cd9660_populate_iso_dir_record(
    132     struct _iso_directory_record_cd9660 *, u_char, u_char, u_char,
    133     const char *);
    134 static void cd9660_setup_root_node(void);
    135 static int cd9660_setup_volume_descriptors(void);
    136 #if 0
    137 static int cd9660_fill_extended_attribute_record(cd9660node *);
    138 #endif
    139 static void cd9660_sort_nodes(cd9660node *);
    140 static int cd9960_translate_node_common(cd9660node *);
    141 static int cd9660_translate_node(fsnode *, cd9660node *);
    142 static int cd9660_compare_filename(const char *, const char *);
    143 static void cd9660_sorted_child_insert(cd9660node *, cd9660node *);
    144 static int cd9660_handle_collisions(cd9660node *, int);
    145 static cd9660node *cd9660_rename_filename(cd9660node *, int, int);
    146 static void cd9660_copy_filenames(cd9660node *);
    147 static void cd9660_sorting_nodes(cd9660node *);
    148 static int cd9660_count_collisions(cd9660node *);
    149 static cd9660node *cd9660_rrip_move_directory(cd9660node *);
    150 static int cd9660_add_dot_records(cd9660node *);
    151 
    152 static void cd9660_convert_structure(fsnode *, cd9660node *, int,
    153     int *, int *);
    154 static void cd9660_free_structure(cd9660node *);
    155 static int cd9660_generate_path_table(void);
    156 static int cd9660_level1_convert_filename(const char *, char *, int);
    157 static int cd9660_level2_convert_filename(const char *, char *, int);
    158 #if 0
    159 static int cd9660_joliet_convert_filename(const char *, char *, int);
    160 #endif
    161 static int cd9660_convert_filename(const char *, char *, int);
    162 static void cd9660_populate_dot_records(cd9660node *);
    163 static int cd9660_compute_offsets(cd9660node *, int);
    164 #if 0
    165 static int cd9660_copy_stat_info(cd9660node *, cd9660node *, int);
    166 #endif
    167 static cd9660node *cd9660_create_virtual_entry(const char *, cd9660node *, int,
    168     int);
    169 static cd9660node *cd9660_create_file(const char *, cd9660node *);
    170 static cd9660node *cd9660_create_directory(const char *, cd9660node *);
    171 static cd9660node *cd9660_create_special_directory(u_char, cd9660node *);
    172 
    173 
    174 /*
    175  * Allocate and initalize a cd9660node
    176  * @returns struct cd9660node * Pointer to new node, or NULL on error
    177  */
    178 static cd9660node *
    179 cd9660_allocate_cd9660node(void)
    180 {
    181 	cd9660node *temp;
    182 
    183 	if ((temp = calloc(1, sizeof(cd9660node))) == NULL)
    184 		err(EXIT_FAILURE, "%s: calloc", __func__);
    185 	TAILQ_INIT(&temp->cn_children);
    186 	temp->parent = temp->dot_record = temp->dot_dot_record = NULL;
    187 	temp->ptnext = temp->ptprev = temp->ptlast = NULL;
    188 	temp->node = NULL;
    189 	temp->isoDirRecord = NULL;
    190 	temp->isoExtAttributes = NULL;
    191 	temp->rr_real_parent = temp->rr_relocated = NULL;
    192 	return temp;
    193 }
    194 
    195 int cd9660_defaults_set = 0;
    196 
    197 /**
    198 * Set default values for cd9660 extension to makefs
    199 */
    200 static void
    201 cd9660_set_defaults(void)
    202 {
    203 	int i;
    204 
    205 	/*Fix the sector size for now, though the spec allows for other sizes*/
    206 	diskStructure.sectorSize = 2048;
    207 
    208 	/* Set up defaults in our own structure */
    209 	diskStructure.verbose_level = 2;
    210 	diskStructure.keep_bad_images = 0;
    211 	diskStructure.follow_sym_links = 0;
    212 	diskStructure.isoLevel = 2;
    213 
    214 	diskStructure.rock_ridge_enabled = 0;
    215 	diskStructure.rock_ridge_renamed_dir_name = 0;
    216 	diskStructure.rock_ridge_move_count = 0;
    217 	diskStructure.rr_moved_dir = 0;
    218 
    219 	diskStructure.include_padding_areas = 1;
    220 
    221 	/* Spec breaking functionality */
    222 	diskStructure.allow_deep_trees =
    223 	    diskStructure.allow_start_dot =
    224 	    diskStructure.allow_max_name =
    225 	    diskStructure.allow_illegal_chars =
    226 	    diskStructure.allow_lowercase =
    227 	    diskStructure.allow_multidot =
    228 	    diskStructure.omit_trailing_period = 0;
    229 
    230 	/* Make sure the PVD is clear */
    231 	memset(&diskStructure.primaryDescriptor, 0, 2048);
    232 
    233 	memset(diskStructure.primaryDescriptor.volume_set_id,	0x20,32);
    234 	memset(diskStructure.primaryDescriptor.publisher_id,	0x20,128);
    235 	memset(diskStructure.primaryDescriptor.preparer_id,	0x20,128);
    236 	memset(diskStructure.primaryDescriptor.application_id,	0x20,128);
    237 	memset(diskStructure.primaryDescriptor.copyright_file_id, 0x20,128);
    238 	memset(diskStructure.primaryDescriptor.abstract_file_id, 0x20,128);
    239 	memset(diskStructure.primaryDescriptor.bibliographic_file_id, 0x20,128);
    240 
    241 	strcpy(diskStructure.primaryDescriptor.system_id,"NetBSD");
    242 
    243 	cd9660_defaults_set = 1;
    244 
    245 	/* Boot support: Initially disabled */
    246 	diskStructure.boot_image_directory = 0;
    247 	/*memset(diskStructure.boot_descriptor, 0, 2048);*/
    248 
    249 	diskStructure.is_bootable = 0;
    250 	TAILQ_INIT(&diskStructure.boot_images);
    251 	LIST_INIT(&diskStructure.boot_entries);
    252 	for (i = 0; i < CD9660_INODE_HASH_SIZE; i++)
    253 		SLIST_INIT(&diskStructure.inode_hash[i]);
    254 }
    255 
    256 void
    257 cd9660_prep_opts(fsinfo_t *fsopts)
    258 {
    259 	cd9660_set_defaults();
    260 }
    261 
    262 void
    263 cd9660_cleanup_opts(fsinfo_t *fsopts)
    264 {
    265 
    266 }
    267 
    268 static int
    269 cd9660_arguments_set_string(const char *val, const char *fieldtitle, int length,
    270 			    char testmode, char * dest)
    271 {
    272 	int len, test;
    273 
    274 	if (val == NULL)
    275 		warnx("error: The %s requires a string argument", fieldtitle);
    276 	else if ((len = strlen(val)) <= length) {
    277 		if (testmode == 'd')
    278 			test = cd9660_valid_d_chars(val);
    279 		else
    280 			test = cd9660_valid_a_chars(val);
    281 		if (test) {
    282 			memcpy(dest, val, len);
    283 			if (test == 2)
    284 				cd9660_uppercase_characters(dest, len);
    285 			return 1;
    286 		} else
    287 			warnx("error: The %s must be composed of "
    288 			      "%c-characters", fieldtitle, testmode);
    289 	} else
    290 		warnx("error: The %s must be at most 32 characters long",
    291 		    fieldtitle);
    292 	return 0;
    293 }
    294 
    295 /*
    296  * Command-line parsing function
    297  */
    298 
    299 int
    300 cd9660_parse_opts(const char *option, fsinfo_t *fsopts)
    301 {
    302 	char *var, *val;
    303 	int	rv;
    304 	/* Set up allowed options - integer options ONLY */
    305 	option_t cd9660_options[] = {
    306 		{ "l", &diskStructure.isoLevel, 1, 3, "ISO Level" },
    307 		{ "isolevel", &diskStructure.isoLevel, 1, 3, "ISO Level" },
    308 		{ "verbose",  &diskStructure.verbose_level, 0, 2,
    309 		  "Turns on verbose output" },
    310 		{ "v", &diskStructure.verbose_level, 0 , 2,
    311 		  "Turns on verbose output"},
    312 		{ NULL }
    313 	};
    314 
    315 	if (cd9660_defaults_set == 0)
    316 		cd9660_set_defaults();
    317 
    318 	/*
    319 	 * Todo : finish implementing this, and make a function that
    320 	 * parses them
    321 	 */
    322 	/*
    323 	string_option_t cd9660_string_options[] = {
    324 		{ "L", "Label", &diskStructure.primaryDescriptor.volume_id, 1, 32, "Disk Label", ISO_STRING_FILTER_DCHARS },
    325 		{ NULL }
    326 	}
    327 	*/
    328 
    329 	assert(option != NULL);
    330 	assert(fsopts != NULL);
    331 
    332 	if (debug & DEBUG_FS_PARSE_OPTS)
    333 		printf("cd9660_parse_opts: got `%s'\n", option);
    334 
    335 	if ((var = strdup(option)) == NULL)
    336 		err(1, "allocating memory for copy of option string");
    337 	rv = 1;
    338 
    339 	val = strchr(var, '=');
    340 	if (val != NULL)
    341 		*val++ = '\0';
    342 
    343 	/* First handle options with no parameters */
    344 	if (strcmp(var, "h") == 0) {
    345 		diskStructure.displayHelp = 1;
    346 		rv = 1;
    347 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "S", "follow-symlinks")) {
    348 		/* this is not handled yet */
    349 		diskStructure.follow_sym_links = 1;
    350 		rv = 1;
    351 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "L", "label")) {
    352 		rv = cd9660_arguments_set_string(val, "Disk Label", 32, 'd',
    353 			diskStructure.primaryDescriptor.volume_id);
    354 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "A", "applicationid")) {
    355 		rv = cd9660_arguments_set_string(val, "Application Identifier", 128, 'a',
    356 			diskStructure.primaryDescriptor.application_id);
    357 	} else if(CD9660_IS_COMMAND_ARG_DUAL(var, "P", "publisher")) {
    358 		rv = cd9660_arguments_set_string(val, "Publisher Identifier",
    359 			128, 'a', diskStructure.primaryDescriptor.publisher_id);
    360 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "p", "preparer")) {
    361 		rv = cd9660_arguments_set_string(val, "Preparer Identifier",
    362 		    128, 'a', diskStructure.primaryDescriptor.preparer_id);
    363 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "V", "volumeid")) {
    364 		rv = cd9660_arguments_set_string(val, "Volume Set Identifier",
    365 		    128, 'a', diskStructure.primaryDescriptor.volume_set_id);
    366 	/* Boot options */
    367 	} else if (CD9660_IS_COMMAND_ARG_DUAL(var, "B", "bootimage")) {
    368 		if (val == NULL)
    369 			warnx("error: The Boot Image parameter requires a valid boot information string");
    370 		else
    371 			rv = cd9660_add_boot_disk(val);
    372 	} else if (CD9660_IS_COMMAND_ARG(var, "bootimagedir")) {
    373 		/*
    374 		 * XXXfvdl this is unused.
    375 		 */
    376 		if (val == NULL)
    377 			errx(1, "error: The Boot Image Directory parameter"
    378 			     " requires a directory name\n");
    379 		else {
    380 			if ((diskStructure.boot_image_directory =
    381 			     malloc(strlen(val) + 1)) == NULL) {
    382 				CD9660_MEM_ALLOC_ERROR("cd9660_parse_opts");
    383 				exit(1);
    384 			}
    385 
    386 			/* BIG TODO: Add the max length function here */
    387 			cd9660_arguments_set_string(val, "Boot Image Directory",
    388 			    12 , 'd', diskStructure.boot_image_directory);
    389 		}
    390 	} else if (CD9660_IS_COMMAND_ARG(var, "no-trailing-padding"))
    391 		diskStructure.include_padding_areas = 0;
    392 	/* RRIP */
    393 	else if (CD9660_IS_COMMAND_ARG_DUAL(var, "R", "rockridge"))
    394 		diskStructure.rock_ridge_enabled = 1;
    395 	else if (CD9660_IS_COMMAND_ARG_DUAL(var, "K", "keep-bad-images"))
    396 		diskStructure.keep_bad_images = 1;
    397 	else if (CD9660_IS_COMMAND_ARG(var, "allow-deep-trees"))
    398 		diskStructure.allow_deep_trees = 1;
    399 	else if (CD9660_IS_COMMAND_ARG(var, "allow-max-name"))
    400 		diskStructure.allow_max_name = 1;
    401 	else if (CD9660_IS_COMMAND_ARG(var, "allow-illegal-chars"))
    402 		diskStructure.allow_illegal_chars = 1;
    403 	else if (CD9660_IS_COMMAND_ARG(var, "allow-lowercase"))
    404 		diskStructure.allow_lowercase = 1;
    405 	else if (CD9660_IS_COMMAND_ARG(var,"allow-multidot"))
    406 		diskStructure.allow_multidot = 1;
    407 	else if (CD9660_IS_COMMAND_ARG(var, "omit-trailing-period"))
    408 		diskStructure.omit_trailing_period = 1;
    409 	else if (CD9660_IS_COMMAND_ARG(var, "no-emul-boot") ||
    410 		    CD9660_IS_COMMAND_ARG(var, "no-boot") ||
    411 		    CD9660_IS_COMMAND_ARG(var, "hard-disk-boot") ||
    412 		    CD9660_IS_COMMAND_ARG(var, "boot-load-segment")) {
    413 		/* XXX check error! */
    414 		cd9660_eltorito_add_boot_option(var, val);
    415 	}
    416 		/* End of flag variables */
    417 	else if (val == NULL) {
    418 		warnx("Option `%s' doesn't contain a value", var);
    419 		rv = 0;
    420 	} else
    421 		rv = set_option(cd9660_options, var, val);
    422 
    423 	if (var)
    424 		free(var);
    425 	return (rv);
    426 }
    427 
    428 /*
    429  * Main function for cd9660_makefs
    430  * Builds the ISO image file
    431  * @param const char *image The image filename to create
    432  * @param const char *dir The directory that is being read
    433  * @param struct fsnode *root The root node of the filesystem tree
    434  * @param struct fsinfo_t *fsopts Any options
    435  */
    436 void
    437 cd9660_makefs(const char *image, const char *dir, fsnode *root,
    438 	      fsinfo_t *fsopts)
    439 {
    440 	int startoffset;
    441 	int numDirectories;
    442 	int pathTableSectors;
    443 	int firstAvailableSector;
    444 	int totalSpace;
    445 	int error;
    446 	cd9660node *real_root;
    447 
    448 	if (diskStructure.verbose_level > 0)
    449 		printf("cd9660_makefs: ISO level is %i\n",
    450 		    diskStructure.isoLevel);
    451 
    452 	assert(image != NULL);
    453 	assert(dir != NULL);
    454 	assert(root != NULL);
    455 	assert(fsopts != NULL);
    456 
    457 	if (diskStructure.displayHelp) {
    458 		/*
    459 		 * Display help here - probably want to put it in
    460 		 * a separate function
    461 		 */
    462 		return;
    463 	}
    464 
    465 	diskStructure.rootFilesystemPath = dir;
    466 
    467 	if (diskStructure.verbose_level > 0)
    468 		printf("cd9660_makefs: image %s directory %s root %p\n",
    469 		    image, dir, root);
    470 
    471 	/* Set up some constants. Later, these will be defined with options */
    472 
    473 	/* Counter needed for path tables */
    474 	numDirectories = 0;
    475 
    476 	/* Convert tree to our own format */
    477 	/* Actually, we now need to add the REAL root node, at level 0 */
    478 
    479 	real_root = cd9660_allocate_cd9660node();
    480 	if ((real_root->isoDirRecord =
    481 		malloc( sizeof(iso_directory_record_cd9660) )) == NULL) {
    482 		CD9660_MEM_ALLOC_ERROR("cd9660_makefs");
    483 		exit(1);
    484 	}
    485 
    486 	/* Leave filename blank for root */
    487 	memset(real_root->isoDirRecord->name, 0,
    488 	    ISO_FILENAME_MAXLENGTH_WITH_PADDING);
    489 
    490 	real_root->level = 0;
    491 	diskStructure.rootNode = real_root;
    492 	real_root->type = CD9660_TYPE_DIR;
    493 	error = 0;
    494 	real_root->node = root;
    495 	cd9660_convert_structure(root, real_root, 1, &numDirectories, &error);
    496 
    497 	if (TAILQ_EMPTY(&real_root->cn_children)) {
    498 		errx(1, "cd9660_makefs: converted directory is empty. "
    499 			"Tree conversion failed\n");
    500 	} else if (error != 0) {
    501 		errx(1, "cd9660_makefs: tree conversion failed\n");
    502 	} else {
    503 		if (diskStructure.verbose_level > 0)
    504 			printf("cd9660_makefs: tree converted\n");
    505 	}
    506 
    507 	/* Add the dot and dot dot records */
    508 	cd9660_add_dot_records(real_root);
    509 
    510 	cd9660_setup_root_node();
    511 
    512 	if (diskStructure.verbose_level > 0)
    513 		printf("cd9660_makefs: done converting tree\n");
    514 
    515 	/* Rock ridge / SUSP init pass */
    516 	if (diskStructure.rock_ridge_enabled) {
    517 		cd9660_susp_initialize(diskStructure.rootNode,
    518 		    diskStructure.rootNode, NULL);
    519 	}
    520 
    521 	/* Build path table structure */
    522 	diskStructure.pathTableLength = cd9660_generate_path_table();
    523 
    524 	pathTableSectors = CD9660_BLOCKS(diskStructure.sectorSize,
    525 		diskStructure.pathTableLength);
    526 
    527 	firstAvailableSector = cd9660_setup_volume_descriptors();
    528 	if (diskStructure.is_bootable) {
    529 		firstAvailableSector = cd9660_setup_boot(firstAvailableSector);
    530 		if (firstAvailableSector < 0)
    531 			errx(1, "setup_boot failed");
    532 	}
    533 	/* LE first, then BE */
    534 	diskStructure.primaryLittleEndianTableSector = firstAvailableSector;
    535 	diskStructure.primaryBigEndianTableSector =
    536 		diskStructure.primaryLittleEndianTableSector + pathTableSectors;
    537 
    538 	/* Set the secondary ones to -1, not going to use them for now */
    539 	diskStructure.secondaryBigEndianTableSector = -1;
    540 	diskStructure.secondaryLittleEndianTableSector = -1;
    541 
    542 	diskStructure.dataFirstSector =
    543 	    diskStructure.primaryBigEndianTableSector + pathTableSectors;
    544 	if (diskStructure.verbose_level > 0)
    545 		printf("cd9660_makefs: Path table conversion complete. "
    546 		       "Each table is %i bytes, or %i sectors.\n",
    547 		    diskStructure.pathTableLength, pathTableSectors);
    548 
    549 	startoffset = diskStructure.sectorSize*diskStructure.dataFirstSector;
    550 
    551 	totalSpace = cd9660_compute_offsets(real_root, startoffset);
    552 
    553 	diskStructure.totalSectors = diskStructure.dataFirstSector +
    554 		CD9660_BLOCKS(diskStructure.sectorSize, totalSpace);
    555 
    556 	/* Disabled until pass 1 is done */
    557 	if (diskStructure.rock_ridge_enabled) {
    558 		diskStructure.susp_continuation_area_start_sector =
    559 		    diskStructure.totalSectors;
    560 		diskStructure.totalSectors +=
    561 		    CD9660_BLOCKS(diskStructure.sectorSize,
    562 			diskStructure.susp_continuation_area_size);
    563 		cd9660_susp_finalize(diskStructure.rootNode);
    564 	}
    565 
    566 
    567 	cd9660_finalize_PVD();
    568 
    569 	/* Add padding sectors, just for testing purposes right now */
    570 	/* diskStructure.totalSectors+=150; */
    571 
    572 	/* Debugging output */
    573 	if (diskStructure.verbose_level > 0) {
    574 		printf("cd9660_makefs: Sectors 0-15 reserved\n");
    575 		printf("cd9660_makefs: Primary path tables starts in sector %i\n",
    576 			diskStructure.primaryLittleEndianTableSector);
    577 		printf("cd9660_makefs: File data starts in sector %i\n",
    578 			diskStructure.dataFirstSector);
    579 		printf("cd9660_makefs: Total sectors: %i\n",diskStructure.totalSectors);
    580 	}
    581 
    582 	/*
    583 	 * Add padding sectors at the end
    584 	 * TODO: Clean this up and separate padding
    585 	 */
    586 	if (diskStructure.include_padding_areas)
    587 		diskStructure.totalSectors += 150;
    588 
    589 	cd9660_write_image(image);
    590 
    591 	if (diskStructure.verbose_level > 1) {
    592 		debug_print_volume_descriptor_information();
    593 		debug_print_tree(real_root,0);
    594 		debug_print_path_tree(real_root);
    595 	}
    596 
    597 	/* Clean up data structures */
    598 	cd9660_free_structure(real_root);
    599 
    600 	if (diskStructure.verbose_level > 0)
    601 		printf("cd9660_makefs: done\n");
    602 }
    603 
    604 /* Generic function pointer - implement later */
    605 typedef int (*cd9660node_func)(cd9660node *);
    606 
    607 static void
    608 cd9660_finalize_PVD(void)
    609 {
    610 	time_t tim;
    611 	unsigned char *temp;
    612 
    613 	/* Copy the root directory record */
    614 	temp = (unsigned char *) &diskStructure.primaryDescriptor;
    615 
    616 	/* root should be a fixed size of 34 bytes since it has no name */
    617 	memcpy(diskStructure.primaryDescriptor.root_directory_record,
    618 		diskStructure.rootNode->dot_record->isoDirRecord, 34);
    619 
    620 	/* In RRIP, this might be longer than 34 */
    621 	diskStructure.primaryDescriptor.root_directory_record[0] = 34;
    622 
    623 	/* Set up all the important numbers in the PVD */
    624 	cd9660_bothendian_dword(diskStructure.totalSectors,
    625 	    (unsigned char *)diskStructure.primaryDescriptor.volume_space_size);
    626 	cd9660_bothendian_word(1,
    627 	    (unsigned char *)diskStructure.primaryDescriptor.volume_set_size);
    628 	cd9660_bothendian_word(1,
    629 	    (unsigned char *)
    630 		diskStructure.primaryDescriptor.volume_sequence_number);
    631 	cd9660_bothendian_word(diskStructure.sectorSize,
    632 	    (unsigned char *)
    633 		diskStructure.primaryDescriptor.logical_block_size);
    634 	cd9660_bothendian_dword(diskStructure.pathTableLength,
    635 	    (unsigned char *)diskStructure.primaryDescriptor.path_table_size);
    636 
    637 	cd9660_731(diskStructure.primaryLittleEndianTableSector,
    638 		(u_char *)diskStructure.primaryDescriptor.type_l_path_table);
    639 	cd9660_732(diskStructure.primaryBigEndianTableSector,
    640 		(u_char *)diskStructure.primaryDescriptor.type_m_path_table);
    641 
    642 	diskStructure.primaryDescriptor.file_structure_version[0] = 1;
    643 
    644 	/* Pad all strings with spaces instead of nulls */
    645 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.volume_id, 32);
    646 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.system_id, 32);
    647 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.volume_set_id,
    648 	    128);
    649 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.publisher_id,
    650 	    128);
    651 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.preparer_id,
    652 	    128);
    653 	cd9660_pad_string_spaces(diskStructure.primaryDescriptor.application_id,
    654 	    128);
    655 	cd9660_pad_string_spaces(
    656 	    diskStructure.primaryDescriptor.copyright_file_id, 128);
    657 	cd9660_pad_string_spaces(
    658 		diskStructure.primaryDescriptor.abstract_file_id, 128);
    659 	cd9660_pad_string_spaces(
    660 		diskStructure.primaryDescriptor.bibliographic_file_id, 128);
    661 
    662 	/* Setup dates */
    663 	time(&tim);
    664 	cd9660_time_8426(
    665 	    (unsigned char *)diskStructure.primaryDescriptor.creation_date,
    666 	    tim);
    667 	cd9660_time_8426(
    668 	    (unsigned char *)diskStructure.primaryDescriptor.modification_date,
    669 	    tim);
    670 
    671 	/*
    672 	cd9660_set_date(diskStructure.primaryDescriptor.expiration_date, now);
    673 	*/
    674 
    675 	memset(diskStructure.primaryDescriptor.expiration_date, '0' ,17);
    676 	cd9660_time_8426(
    677 	    (unsigned char *)diskStructure.primaryDescriptor.effective_date,
    678 	    tim);
    679 }
    680 
    681 static void
    682 cd9660_populate_iso_dir_record(struct _iso_directory_record_cd9660 *record,
    683 			       u_char ext_attr_length, u_char flags,
    684 			       u_char name_len, const char * name)
    685 {
    686 	record->ext_attr_length[0] = ext_attr_length;
    687 	record->flags[0] = ISO_FLAG_CLEAR | flags;
    688 	record->file_unit_size[0] = 0;
    689 	record->interleave[0] = 0;
    690 	cd9660_bothendian_word(1, record->volume_sequence_number);
    691 	record->name_len[0] = name_len;
    692 	memcpy(record->name, name, name_len);
    693 	record->length[0] = 33 + name_len;
    694 
    695 	/* Todo : better rounding */
    696 	record->length[0] += (record->length[0] & 1) ? 1 : 0;
    697 }
    698 
    699 static void
    700 cd9660_setup_root_node(void)
    701 {
    702 	cd9660_populate_iso_dir_record(diskStructure.rootNode->isoDirRecord,
    703 	    0, ISO_FLAG_DIRECTORY, 1, "\0");
    704 
    705 }
    706 
    707 /*********** SUPPORT FUNCTIONS ***********/
    708 static int
    709 cd9660_setup_volume_descriptors(void)
    710 {
    711 	/* Boot volume descriptor should come second */
    712 	int sector = 16;
    713 	/* For now, a fixed 2 : PVD and terminator */
    714 	volume_descriptor *temp, *t;
    715 
    716 	/* Set up the PVD */
    717 	if ((temp = malloc(sizeof(volume_descriptor))) == NULL) {
    718 		CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors");
    719 		exit(1);
    720 	}
    721 
    722 	temp->volumeDescriptorData =
    723 	   (unsigned char *)&diskStructure.primaryDescriptor;
    724 	temp->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_PVD;
    725 	temp->volumeDescriptorData[6] = 1;
    726 	temp->sector = sector;
    727 	memcpy(temp->volumeDescriptorData + 1,
    728 	    ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
    729 	diskStructure.firstVolumeDescriptor = temp;
    730 
    731 	sector++;
    732 	/* Set up boot support if enabled. BVD must reside in sector 17 */
    733 	if (diskStructure.is_bootable) {
    734 		if ((t = malloc(sizeof(volume_descriptor))) == NULL) {
    735 			CD9660_MEM_ALLOC_ERROR(
    736 			    "cd9660_setup_volume_descriptors");
    737 			exit(1);
    738 		}
    739 		if ((t->volumeDescriptorData = malloc(2048)) == NULL) {
    740 			CD9660_MEM_ALLOC_ERROR(
    741 			    "cd9660_setup_volume_descriptors");
    742 			exit(1);
    743 		}
    744 		temp->next = t;
    745 		temp = t;
    746 		memset(t->volumeDescriptorData, 0, 2048);
    747 		t->sector = 17;
    748 		if (diskStructure.verbose_level > 0)
    749 			printf("Setting up boot volume descriptor\n");
    750 		cd9660_setup_boot_volume_descritpor(t);
    751 		sector++;
    752 	}
    753 
    754 	/* Set up the terminator */
    755 	if ((t = malloc(sizeof(volume_descriptor))) == NULL) {
    756 		CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors");
    757 		exit(1);
    758 	}
    759 	if ((t->volumeDescriptorData = malloc(2048)) == NULL) {
    760 		CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors");
    761 		exit(1);
    762 	}
    763 
    764 	temp->next = t;
    765 	memset(t->volumeDescriptorData, 0, 2048);
    766 	t->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_TERMINATOR;
    767 	t->next = 0;
    768 	t->volumeDescriptorData[6] = 1;
    769 	t->sector = sector;
    770 	memcpy(t->volumeDescriptorData + 1,
    771 	    ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
    772 
    773 	sector++;
    774 	return sector;
    775 }
    776 
    777 #if 0
    778 /*
    779  * Populate EAR at some point. Not required, but is used by NetBSD's
    780  * cd9660 support
    781  */
    782 static int
    783 cd9660_fill_extended_attribute_record(cd9660node *node)
    784 {
    785 	if ((node->isoExtAttributes =
    786 	    malloc(sizeof(struct iso_extended_attributes))) == NULL) {
    787 		CD9660_MEM_ALLOC_ERROR("cd9660_fill_extended_attribute_record");
    788 		exit(1);
    789 	};
    790 
    791 	return 1;
    792 }
    793 #endif
    794 
    795 static int
    796 cd9960_translate_node_common(cd9660node *newnode)
    797 {
    798 	time_t tim;
    799 	int test;
    800 	u_char flag;
    801 	char temp[ISO_FILENAME_MAXLENGTH_WITH_PADDING];
    802 
    803 	/* Now populate the isoDirRecord structure */
    804 	memset(temp, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING);
    805 
    806 	test = cd9660_convert_filename(newnode->node->name,
    807 		temp, !(S_ISDIR(newnode->node->type)));
    808 
    809 	flag = ISO_FLAG_CLEAR;
    810 	if (S_ISDIR(newnode->node->type))
    811 		flag |= ISO_FLAG_DIRECTORY;
    812 
    813 	cd9660_populate_iso_dir_record(newnode->isoDirRecord, 0,
    814 	    flag, strlen(temp), temp);
    815 
    816 	/* Set the various dates */
    817 
    818 	/* If we want to use the current date and time */
    819 	time(&tim);
    820 
    821 	cd9660_time_915(newnode->isoDirRecord->date, tim);
    822 
    823 	cd9660_bothendian_dword(newnode->fileDataLength,
    824 	    newnode->isoDirRecord->size);
    825 	/* If the file is a link, we want to set the size to 0 */
    826 	if (S_ISLNK(newnode->node->type))
    827 		newnode->fileDataLength = 0;
    828 
    829 	return 1;
    830 }
    831 
    832 /*
    833  * Translate fsnode to cd9960node
    834  * Translate filenames and other metadata, including dates, sizes,
    835  * permissions, etc
    836  * @param struct fsnode * The node generated by makefs
    837  * @param struct cd9660node * The intermediate node to be written to
    838  * @returns int 0 on failure, 1 on success
    839  */
    840 static int
    841 cd9660_translate_node(fsnode *node, cd9660node *newnode)
    842 {
    843 	if (node == NULL) {
    844 		if (diskStructure.verbose_level > 0)
    845 			printf("cd9660_translate_node: NULL node passed, "
    846 			       "returning\n");
    847 		return 0;
    848 	}
    849 	if ((newnode->isoDirRecord =
    850 		malloc(sizeof(iso_directory_record_cd9660))) == NULL) {
    851 		CD9660_MEM_ALLOC_ERROR("cd9660_translate_node");
    852 		return 0;
    853 	}
    854 
    855 	/* Set the node pointer */
    856 	newnode->node = node;
    857 
    858 	/* Set the size */
    859 	if (!(S_ISDIR(node->type)))
    860 		newnode->fileDataLength = node->inode->st.st_size;
    861 
    862 	if (cd9960_translate_node_common(newnode) == 0)
    863 		return 0;
    864 
    865 	/* Finally, overwrite some of the values that are set by default */
    866 	cd9660_time_915(newnode->isoDirRecord->date, node->inode->st.st_mtime);
    867 
    868 	return 1;
    869 }
    870 
    871 /*
    872  * Compares two ISO filenames
    873  * @param const char * The first file name
    874  * @param const char * The second file name
    875  * @returns : -1 if first is less than second, 0 if they are the same, 1 if
    876  * 	the second is greater than the first
    877  */
    878 static int
    879 cd9660_compare_filename(const char *first, const char *second)
    880 {
    881 	/*
    882 	 * This can be made more optimal once it has been tested
    883 	 * (the extra character, for example, is for testing)
    884 	 */
    885 
    886 	int p1 = 0;
    887 	int p2 = 0;
    888 	char c1, c2;
    889 	/* First, on the filename */
    890 
    891 	while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1
    892 		&& p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1) {
    893 		c1 = first[p1];
    894 		c2 = second[p2];
    895 		if (c1 == '.' && c2 =='.')
    896 			break;
    897 		else if (c1 == '.') {
    898 			p2++;
    899 			c1 = ' ';
    900 		} else if (c2 == '.') {
    901 			p1++;
    902 			c2 = ' ';
    903 		} else {
    904 			p1++;
    905 			p2++;
    906 		}
    907 
    908 		if (c1 < c2)
    909 			return -1;
    910 		else if (c1 > c2) {
    911 			return 1;
    912 		}
    913 	}
    914 
    915 	if (first[p1] == '.' && second[p2] == '.') {
    916 		p1++;
    917 		p2++;
    918 		while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1
    919 			&& p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1) {
    920 			c1 = first[p1];
    921 			c2 = second[p2];
    922 			if (c1 == ';' && c2 == ';')
    923 				break;
    924 			else if (c1 == ';') {
    925 				p2++;
    926 				c1 = ' ';
    927 			} else if (c2 == ';') {
    928 				p1++;
    929 				c2 = ' ';
    930 			} else {
    931 				p1++;
    932 				p2++;
    933 			}
    934 
    935 			if (c1 < c2)
    936 				return -1;
    937 			else if (c1 > c2)
    938 				return 1;
    939 		}
    940 	}
    941 	return 0;
    942 }
    943 
    944 /*
    945  * Insert a node into list with ISO sorting rules
    946  * @param cd9660node * The head node of the list
    947  * @param cd9660node * The node to be inserted
    948  */
    949 static void
    950 cd9660_sorted_child_insert(cd9660node *parent, cd9660node *cn_new)
    951 {
    952 	int compare;
    953 	cd9660node *cn;
    954 	struct cd9660_children_head *head = &parent->cn_children;
    955 
    956 	/* TODO: Optimize? */
    957 	cn_new->parent = parent;
    958 
    959 #if 0	/* XXXDCY did this serve any purpose when head was a cd9660node? */
    960 	if (head == cn_new) {
    961 		head->parent->child = head;
    962 		return;
    963 	}
    964 #endif
    965 
    966 	/*
    967 	 * first will either be 0, the . or the ..
    968 	 * if . or .., this means no other entry may be written before first
    969 	 * if 0, the new node may be inserted at the head
    970 	 */
    971 
    972 	TAILQ_FOREACH(cn, head, cn_next_child) {
    973 		/*
    974 		 * Dont insert a node twice -
    975 		 * that would cause an infinite loop
    976 		 */
    977 		assert(cn_new != cn);
    978 
    979 		compare = cd9660_compare_filename(cn_new->isoDirRecord->name,
    980 			cn->isoDirRecord->name);
    981 
    982 		if (compare == 0)
    983 			compare = cd9660_compare_filename(cn_new->node->name,
    984 				cn->node->name);
    985 
    986 		if (compare < 0)
    987 			break;
    988 	}
    989 	if (cn == NULL)
    990 		TAILQ_INSERT_TAIL(head, cn_new, cn_next_child);
    991 	else
    992 		TAILQ_INSERT_BEFORE(cn, cn_new, cn_next_child);
    993 }
    994 
    995 /*
    996  * Called After cd9660_sorted_child_insert
    997  * handles file collisions by suffixing each filname with ~n
    998  * where n represents the files respective place in the ordering
    999  */
   1000 static int
   1001 cd9660_handle_collisions(cd9660node *colliding, int past)
   1002 {
   1003 	cd9660node *iter, *next, *prev;
   1004 	int skip;
   1005 	int delete_chars = 0;
   1006 	int temp_past = past;
   1007 	int temp_skip;
   1008 	int flag = 0;
   1009 	cd9660node *end_of_range;
   1010 
   1011 	for (iter = TAILQ_FIRST(&colliding->cn_children);
   1012 	     iter != NULL && (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;) {
   1013 		if (strcmp(iter->isoDirRecord->name,
   1014 		           next->isoDirRecord->name) != 0) {
   1015 			iter = TAILQ_NEXT(iter, cn_next_child);
   1016 			continue;
   1017 		}
   1018 		flag = 1;
   1019 		temp_skip = skip = cd9660_count_collisions(iter);
   1020 		end_of_range = iter;
   1021 		while (temp_skip > 0) {
   1022 			temp_skip--;
   1023 			end_of_range = TAILQ_NEXT(end_of_range, cn_next_child);
   1024 		}
   1025 		temp_past = past;
   1026 		while (temp_past > 0) {
   1027 			if ((next = TAILQ_NEXT(end_of_range, cn_next_child)) != NULL)
   1028 				end_of_range = next;
   1029 			else if ((prev = TAILQ_PREV(iter, cd9660_children_head, cn_next_child)) != NULL)
   1030 				iter = prev;
   1031 			else
   1032 				delete_chars++;
   1033 			temp_past--;
   1034 		}
   1035 		skip += past;
   1036 		iter = cd9660_rename_filename(iter, skip, delete_chars);
   1037 	}
   1038 	return flag;
   1039 }
   1040 
   1041 
   1042 static cd9660node *
   1043 cd9660_rename_filename(cd9660node *iter, int num, int delete_chars)
   1044 {
   1045 	int i = 0;
   1046 	int numbts, dot, semi, digit, digits, temp, powers, multiplier, count;
   1047 	char *naming;
   1048 	int maxlength;
   1049         char *tmp;
   1050 
   1051 	if (diskStructure.verbose_level > 0)
   1052 		printf("Rename_filename called\n");
   1053 
   1054 	/* TODO : A LOT of chanes regarding 8.3 filenames */
   1055 	if (diskStructure.isoLevel == 1)
   1056 		maxlength = 8;
   1057 	else if (diskStructure.isoLevel == 2)
   1058 		maxlength = 31;
   1059 	else
   1060 		maxlength = ISO_FILENAME_MAXLENGTH_BEFORE_VERSION;
   1061 
   1062 	tmp = malloc(maxlength + 1);
   1063 
   1064 	while (i < num) {
   1065 		powers = 1;
   1066 		count = 0;
   1067 		digits = 1;
   1068 		multiplier = 1;
   1069 		while (((int)(i / powers) ) >= 10) {
   1070 			digits++;
   1071 			powers = powers * 10;
   1072 		}
   1073 
   1074 		naming = iter->o_name;
   1075 
   1076 		/*
   1077 		while ((*naming != '.') && (*naming != ';')) {
   1078 			naming++;
   1079 			count++;
   1080 		}
   1081 		*/
   1082 
   1083 		dot = -1;
   1084 		semi = -1;
   1085 		while (count < maxlength) {
   1086 			if (*naming == '.')
   1087 				dot = count;
   1088 			else if (*naming == ';') {
   1089 				semi = count;
   1090 				break;
   1091 			}
   1092 			naming++;
   1093 			count++;
   1094 		}
   1095 
   1096 		if ((count + digits) < maxlength)
   1097 			numbts = count;
   1098 		else
   1099 			numbts = maxlength - (digits);
   1100 		numbts -= delete_chars;
   1101 
   1102 		/* 8.3 rules - keep the extension, add before the dot */
   1103 
   1104 		/*
   1105 		 * This code makes a bunch of assumptions.
   1106 		 * See if you can spot them all :)
   1107 		 */
   1108 
   1109 		/*
   1110 		if (diskStructure.isoLevel == 1) {
   1111 			numbts = 8 - digits - delete_chars;
   1112 			if (dot < 0) {
   1113 
   1114 			} else {
   1115 				if (dot < 8) {
   1116 					memmove(&tmp[numbts],&tmp[dot],4);
   1117 				}
   1118 			}
   1119 		}
   1120 		*/
   1121 
   1122 		/* (copying just the filename before the '.' */
   1123 		memcpy(tmp, (iter->o_name), numbts);
   1124 
   1125 		/* adding the appropriate number following the name */
   1126 		temp = i;
   1127 		while (digits > 0) {
   1128 			digit = (int)(temp / powers);
   1129 			temp = temp - digit * powers;
   1130 			sprintf(&tmp[numbts] , "%d", digit);
   1131 			digits--;
   1132 			numbts++;
   1133 			powers = powers / 10;
   1134 		}
   1135 
   1136 		while ((*naming != ';')  && (numbts < maxlength)) {
   1137 			tmp[numbts] = (*naming);
   1138 			naming++;
   1139 			numbts++;
   1140 		}
   1141 
   1142 		tmp[numbts] = ';';
   1143 		tmp[numbts+1] = '1';
   1144 
   1145 		/*
   1146 		 * now tmp has exactly the identifier
   1147 		 * we want so we'll copy it back to record
   1148 		 */
   1149 		memcpy((iter->isoDirRecord->name), tmp, numbts + 2);
   1150 
   1151 		iter = TAILQ_NEXT(iter, cn_next_child);
   1152 		i++;
   1153 	}
   1154 
   1155 	free(tmp);
   1156 	return iter;
   1157 }
   1158 
   1159 /* Todo: Figure out why these functions are nec. */
   1160 static void
   1161 cd9660_copy_filenames(cd9660node *node)
   1162 {
   1163 	cd9660node *cn;
   1164 
   1165 	if (TAILQ_EMPTY(&node->cn_children))
   1166 		return;
   1167 
   1168 	if (TAILQ_FIRST(&node->cn_children)->isoDirRecord == NULL) {
   1169 		debug_print_tree(diskStructure.rootNode, 0);
   1170 		exit(1);
   1171 	}
   1172 
   1173 	TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) {
   1174 		cd9660_copy_filenames(cn);
   1175 		memcpy(cn->o_name, cn->isoDirRecord->name,
   1176 		    ISO_FILENAME_MAXLENGTH_WITH_PADDING);
   1177 	}
   1178 }
   1179 
   1180 static void
   1181 cd9660_sorting_nodes(cd9660node *node)
   1182 {
   1183 	cd9660node *cn;
   1184 
   1185 	TAILQ_FOREACH(cn, &node->cn_children, cn_next_child)
   1186 		cd9660_sorting_nodes(cn);
   1187 	cd9660_sort_nodes(node);
   1188 }
   1189 
   1190 /* XXX Bubble sort. */
   1191 static void
   1192 cd9660_sort_nodes(cd9660node *node)
   1193 {
   1194 	cd9660node *cn, *next;
   1195 
   1196 	do {
   1197 		TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) {
   1198 			if ((next = TAILQ_NEXT(cn, cn_next_child)) == NULL)
   1199 				return;
   1200 			else if (strcmp(next->isoDirRecord->name,
   1201 				        cn->isoDirRecord->name) >= 0)
   1202 				continue;
   1203 			TAILQ_REMOVE(&node->cn_children, next, cn_next_child);
   1204 			TAILQ_INSERT_BEFORE(node, next, cn_next_child);
   1205 			break;
   1206 		}
   1207 	} while (cn != NULL);
   1208 }
   1209 
   1210 static int
   1211 cd9660_count_collisions(cd9660node *copy)
   1212 {
   1213 	int count = 0;
   1214 	cd9660node *iter, *next;
   1215 
   1216 	for (iter = copy;
   1217 	     (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;
   1218 	     iter = next) {
   1219 		if (cd9660_compare_filename(iter->isoDirRecord->name,
   1220 			next->isoDirRecord->name) == 0)
   1221 			count++;
   1222 		else
   1223 			return count;
   1224 	}
   1225 #if 0
   1226 	if ((next = TAILQ_NEXT(iter, cn_next_child)) != NULL) {
   1227 		printf("cd9660_recurse_on_collision: count is %i \n", count);
   1228 		compare = cd9660_compare_filename(iter->isoDirRecord->name,
   1229 			next->isoDirRecord->name);
   1230 		if (compare == 0) {
   1231 			count++;
   1232 			return cd9660_recurse_on_collision(next, count);
   1233 		} else
   1234 			return count;
   1235 	}
   1236 #endif
   1237 	return count;
   1238 }
   1239 
   1240 static cd9660node *
   1241 cd9660_rrip_move_directory(cd9660node *dir)
   1242 {
   1243 	char newname[9];
   1244 	cd9660node *tfile;
   1245 
   1246 	/*
   1247 	 * This function needs to:
   1248 	 * 1) Create an empty virtual file in place of the old directory
   1249 	 * 2) Point the virtual file to the new directory
   1250 	 * 3) Point the relocated directory to its old parent
   1251 	 * 4) Move the directory specified by dir into rr_moved_dir,
   1252 	 * and rename it to "diskStructure.rock_ridge_move_count" (as a string)
   1253 	 */
   1254 
   1255 	/* First see if the moved directory even exists */
   1256 	if (diskStructure.rr_moved_dir == NULL) {
   1257 		diskStructure.rr_moved_dir =
   1258 			cd9660_create_directory(ISO_RRIP_DEFAULT_MOVE_DIR_NAME,
   1259 				diskStructure.rootNode);
   1260 		if (diskStructure.rr_moved_dir == NULL)
   1261 			return 0;
   1262 	}
   1263 
   1264 	/* Create a file with the same ORIGINAL name */
   1265 	tfile = cd9660_create_file(dir->node->name, dir->parent);
   1266 	if (tfile == NULL)
   1267 		return NULL;
   1268 
   1269 	diskStructure.rock_ridge_move_count++;
   1270 	sprintf(newname,"%08i", diskStructure.rock_ridge_move_count);
   1271 
   1272 	/* Point to old parent */
   1273 	dir->rr_real_parent = dir->parent;
   1274 
   1275 	/* Place the placeholder file */
   1276 	if (TAILQ_EMPTY(&dir->rr_real_parent->cn_children)) {
   1277 		TAILQ_INSERT_HEAD(&dir->rr_real_parent->cn_children, tfile,
   1278 		    cn_next_child);
   1279 	} else {
   1280 		cd9660_sorted_child_insert(dir->rr_real_parent, tfile);
   1281 	}
   1282 
   1283 	/* Point to new parent */
   1284 	dir->parent = diskStructure.rr_moved_dir;
   1285 
   1286 	/* Point the file to the moved directory */
   1287 	tfile->rr_relocated = dir;
   1288 
   1289 	/* Actually move the directory */
   1290 	cd9660_sorted_child_insert(diskStructure.rr_moved_dir, dir);
   1291 
   1292 	/* TODO: Inherit permissions / ownership (basically the entire inode) */
   1293 
   1294 	/* Set the new name */
   1295 	memset(dir->isoDirRecord->name, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING);
   1296 	strncpy(dir->isoDirRecord->name, newname, 8);
   1297 
   1298 	return dir;
   1299 }
   1300 
   1301 static int
   1302 cd9660_add_dot_records(cd9660node *root)
   1303 {
   1304 	struct cd9660_children_head *head = &root->cn_children;
   1305 	cd9660node *cn;
   1306 
   1307 	TAILQ_FOREACH(cn, head, cn_next_child) {
   1308 		if ((cn->type & CD9660_TYPE_DIR) == 0)
   1309 			continue;
   1310 		/* Recursion first */
   1311 		cd9660_add_dot_records(cn);
   1312 	}
   1313 	cd9660_create_special_directory(CD9660_TYPE_DOT, root);
   1314 	cd9660_create_special_directory(CD9660_TYPE_DOTDOT, root);
   1315 	return 1;
   1316 }
   1317 
   1318 /*
   1319  * Convert node to cd9660 structure
   1320  * This function is designed to be called recursively on the root node of
   1321  * the filesystem
   1322  * Lots of recursion going on here, want to make sure it is efficient
   1323  * @param struct fsnode * The root node to be converted
   1324  * @param struct cd9660* The parent node (should not be NULL)
   1325  * @param int Current directory depth
   1326  * @param int* Running count of the number of directories that are being created
   1327  */
   1328 static void
   1329 cd9660_convert_structure(fsnode *root, cd9660node *parent_node, int level,
   1330 			 int *numDirectories, int *error)
   1331 {
   1332 	fsnode *iterator = root;
   1333 	cd9660node *this_node;
   1334 	int working_level;
   1335 	int add;
   1336 	int flag = 0;
   1337 	int counter = 0;
   1338 
   1339 	/*
   1340 	 * Newer, more efficient method, reduces recursion depth
   1341 	 */
   1342 	if (root == NULL) {
   1343 		warnx("%s: root is null\n", __func__);
   1344 		return;
   1345 	}
   1346 
   1347 	/* Test for an empty directory - makefs still gives us the . record */
   1348 	if ((S_ISDIR(root->type)) && (root->name[0] == '.')
   1349 		&& (root->name[1] == '\0')) {
   1350 		root = root->next;
   1351 		if (root == NULL)
   1352 			return;
   1353 	}
   1354 	if ((this_node = cd9660_allocate_cd9660node()) == NULL) {
   1355 		CD9660_MEM_ALLOC_ERROR(__func__);
   1356 	}
   1357 
   1358 	/*
   1359 	 * To reduce the number of recursive calls, we will iterate over
   1360 	 * the next pointers to the right.
   1361 	 */
   1362 	while (iterator != NULL) {
   1363 		add = 1;
   1364 		/*
   1365 		 * Increment the directory count if this is a directory
   1366 		 * Ignore "." entries. We will generate them later
   1367 		 */
   1368 		if (!S_ISDIR(iterator->type) ||
   1369 		    strcmp(iterator->name, ".") != 0) {
   1370 
   1371 			/* Translate the node, including its filename */
   1372 			this_node->parent = parent_node;
   1373 			cd9660_translate_node(iterator, this_node);
   1374 			this_node->level = level;
   1375 
   1376 			if (S_ISDIR(iterator->type)) {
   1377 				(*numDirectories)++;
   1378 				this_node->type = CD9660_TYPE_DIR;
   1379 				working_level = level + 1;
   1380 
   1381 				/*
   1382 				 * If at level 8, directory would be at 8
   1383 				 * and have children at 9 which is not
   1384 				 * allowed as per ISO spec
   1385 				 */
   1386 				if (level == 8) {
   1387 					if ((!diskStructure.allow_deep_trees) &&
   1388 					  (!diskStructure.rock_ridge_enabled)) {
   1389 						warnx("error: found entry "
   1390 						     "with depth greater "
   1391 						     "than 8.");
   1392 						(*error) = 1;
   1393 						return;
   1394 					} else if (diskStructure.
   1395 						   rock_ridge_enabled) {
   1396 						working_level = 3;
   1397 						/*
   1398 						 * Moved directory is actually
   1399 						 * at level 2.
   1400 						 */
   1401 						this_node->level =
   1402 						    working_level - 1;
   1403 						if (cd9660_rrip_move_directory(
   1404 							this_node) == 0) {
   1405 							warnx("Failure in "
   1406 							      "cd9660_rrip_"
   1407 							      "move_directory"
   1408 							);
   1409 							(*error) = 1;
   1410 							return;
   1411 						}
   1412 						add = 0;
   1413 					}
   1414 				}
   1415 
   1416 				/* Do the recursive call on the children */
   1417 				if (iterator->child != 0) {
   1418 					cd9660_convert_structure(
   1419 					    iterator->child, this_node,
   1420 						working_level,
   1421 						numDirectories, error);
   1422 
   1423 					if ((*error) == 1) {
   1424 						warnx("%s: Error on recursive "
   1425 						    "call", __func__);
   1426 						return;
   1427 					}
   1428 				}
   1429 
   1430 			} else {
   1431 				/* Only directories should have children */
   1432 				assert(iterator->child == NULL);
   1433 
   1434 				this_node->type = CD9660_TYPE_FILE;
   1435 			}
   1436 
   1437 			/*
   1438 			 * Finally, do a sorted insert
   1439 			 */
   1440 			if (add) {
   1441 				cd9660_sorted_child_insert(
   1442 				    parent_node, this_node);
   1443 			}
   1444 
   1445 			/*Allocate new temp_node */
   1446 			if (iterator->next != 0) {
   1447 				this_node = cd9660_allocate_cd9660node();
   1448 				if (this_node == NULL)
   1449 					CD9660_MEM_ALLOC_ERROR(__func__);
   1450 			}
   1451 		}
   1452 		iterator = iterator->next;
   1453 	}
   1454 
   1455 	/* cd9660_handle_collisions(first_node); */
   1456 
   1457 	/* TODO: need cleanup */
   1458 	cd9660_copy_filenames(parent_node);
   1459 
   1460 	do {
   1461 		flag = cd9660_handle_collisions(parent_node, counter);
   1462 		counter++;
   1463 		cd9660_sorting_nodes(parent_node);
   1464 	} while ((flag == 1) && (counter < 100));
   1465 }
   1466 
   1467 /*
   1468  * Clean up the cd9660node tree
   1469  * This is designed to be called recursively on the root node
   1470  * @param struct cd9660node *root The node to free
   1471  * @returns void
   1472  */
   1473 static void
   1474 cd9660_free_structure(cd9660node *root)
   1475 {
   1476 	cd9660node *cn;
   1477 
   1478 	while ((cn = TAILQ_FIRST(&root->cn_children)) != NULL) {
   1479 		TAILQ_REMOVE(&root->cn_children, cn, cn_next_child);
   1480 		cd9660_free_structure(cn);
   1481 	}
   1482 	free(root);
   1483 }
   1484 
   1485 /*
   1486  * Be a little more memory conservative:
   1487  * instead of having the TAILQ_ENTRY as part of the cd9660node,
   1488  * just create a temporary structure
   1489  */
   1490 struct ptq_entry
   1491 {
   1492 	TAILQ_ENTRY(ptq_entry) ptq;
   1493 	cd9660node *node;
   1494 } *n;
   1495 
   1496 #define PTQUEUE_NEW(n,s,r,t){\
   1497 	n = malloc(sizeof(struct s));	\
   1498 	if (n == NULL)	\
   1499 		return r; \
   1500 	n->node = t;\
   1501 }
   1502 
   1503 /*
   1504  * Generate the path tables
   1505  * The specific implementation of this function is left as an exercise to the
   1506  * programmer. It could be done recursively. Make sure you read how the path
   1507  * table has to be laid out, it has levels.
   1508  * @param struct iso9660_disk *disk The disk image
   1509  * @returns int The number of built path tables (between 1 and 4), 0 on failure
   1510  */
   1511 static int
   1512 cd9660_generate_path_table(void)
   1513 {
   1514 	cd9660node *cn, *dirNode = diskStructure.rootNode;
   1515 	cd9660node *last = dirNode;
   1516 	int pathTableSize = 0;	/* computed as we go */
   1517 	int counter = 1;	/* root gets a count of 0 */
   1518 	int parentRecNum = 0;	/* root's parent is '0' */
   1519 
   1520 	TAILQ_HEAD(cd9660_pt_head, ptq_entry) pt_head;
   1521 	TAILQ_INIT(&pt_head);
   1522 
   1523 	PTQUEUE_NEW(n, ptq_entry, -1, diskStructure.rootNode);
   1524 
   1525 	/* Push the root node */
   1526 	TAILQ_INSERT_HEAD(&pt_head, n, ptq);
   1527 
   1528 	/* Breadth-first traversal of file structure */
   1529 	while (pt_head.tqh_first != 0) {
   1530 		n = pt_head.tqh_first;
   1531 		dirNode = n->node;
   1532 		TAILQ_REMOVE(&pt_head, pt_head.tqh_first, ptq);
   1533 		free(n);
   1534 
   1535 		/* Update the size */
   1536 		pathTableSize += ISO_PATHTABLE_ENTRY_BASESIZE
   1537 		    + dirNode->isoDirRecord->name_len[0]+
   1538 			(dirNode->isoDirRecord->name_len[0] % 2 == 0 ? 0 : 1);
   1539 			/* includes the padding bit */
   1540 
   1541 		dirNode->ptnumber=counter;
   1542 		if (dirNode != last) {
   1543 			last->ptnext = dirNode;
   1544 			dirNode->ptprev = last;
   1545 		}
   1546 		last = dirNode;
   1547 
   1548 		parentRecNum = 1;
   1549 		if (dirNode->parent != 0)
   1550 			parentRecNum = dirNode->parent->ptnumber;
   1551 
   1552 		/* Push children onto queue */
   1553 		TAILQ_FOREACH(cn, &dirNode->cn_children, cn_next_child) {
   1554 			/*
   1555 			 * Dont add the DOT and DOTDOT types to the path
   1556 			 * table.
   1557 			 */
   1558 			if ((cn->type != CD9660_TYPE_DOT)
   1559 				&& (cn->type != CD9660_TYPE_DOTDOT)) {
   1560 
   1561 				if (S_ISDIR(cn->node->type)) {
   1562 					PTQUEUE_NEW(n, ptq_entry, -1, cn);
   1563 					TAILQ_INSERT_TAIL(&pt_head, n, ptq);
   1564 				}
   1565 			}
   1566 		}
   1567 		counter++;
   1568 	}
   1569 	return pathTableSize;
   1570 }
   1571 
   1572 void
   1573 cd9660_compute_full_filename(cd9660node *node, char *buf, int level)
   1574 {
   1575 	cd9660node *parent;
   1576 
   1577 	parent = (node->rr_real_parent == NULL ?
   1578 		  node->parent : node->rr_real_parent);
   1579 	if (parent != NULL) {
   1580 		cd9660_compute_full_filename(parent, buf, level + 1);
   1581 		strcat(buf, node->node->name);
   1582 	} else {
   1583 		/* We are at the root */
   1584 		strcat(buf, diskStructure.rootFilesystemPath);
   1585 		if (buf[strlen(buf) - 1] == '/')
   1586 			buf[strlen(buf) - 1] = '\0';
   1587 	}
   1588 
   1589 	if (level != 0)
   1590 		strcat(buf, "/");
   1591 }
   1592 
   1593 /* NEW filename conversion method */
   1594 typedef int(*cd9660_filename_conversion_functor)(const char *, char *, int);
   1595 
   1596 
   1597 /*
   1598  * TODO: These two functions are almost identical.
   1599  * Some code cleanup is possible here
   1600  *
   1601  * XXX bounds checking!
   1602  */
   1603 static int
   1604 cd9660_level1_convert_filename(const char *oldname, char *newname, int is_file)
   1605 {
   1606 	/*
   1607 	 * ISO 9660 : 10.1
   1608 	 * File Name shall not contain more than 8 d or d1 characters
   1609 	 * File Name Extension shall not contain more than 3 d or d1 characters
   1610 	 * Directory Identifier shall not contain more than 8 d or d1 characters
   1611 	 */
   1612 	int namelen = 0;
   1613 	int extlen = 0;
   1614 	int found_ext = 0;
   1615 
   1616 	while (*oldname != '\0') {
   1617 		/* Handle period first, as it is special */
   1618 		if (*oldname == '.') {
   1619 			if (found_ext) {
   1620 				*newname++ = '_';
   1621 				extlen ++;
   1622 			}
   1623 			else {
   1624 				*newname++ = '.';
   1625 				found_ext = 1;
   1626 			}
   1627 		} else {
   1628 			/* Enforce 12.3 / 8 */
   1629 			if (((namelen == 8) && !found_ext) ||
   1630 			    (found_ext && extlen == 3)) {
   1631 				break;
   1632 			}
   1633 
   1634 			if (islower((unsigned char)*oldname))
   1635 				*newname++ = toupper((unsigned char)*oldname);
   1636 			else if (isupper((unsigned char)*oldname)
   1637 				    || isdigit((unsigned char)*oldname))
   1638 				*newname++ = *oldname;
   1639 			else
   1640 				*newname++ = '_';
   1641 
   1642 			if (found_ext)
   1643 				extlen++;
   1644 			else
   1645 				namelen++;
   1646 		}
   1647 		oldname ++;
   1648 	}
   1649 	if (is_file) {
   1650 		if (!found_ext && !diskStructure.omit_trailing_period)
   1651 			*newname++ = '.';
   1652 		/* Add version */
   1653 		sprintf(newname, ";%i", 1);
   1654 	}
   1655 	return namelen + extlen + found_ext;
   1656 }
   1657 
   1658 /* XXX bounds checking! */
   1659 static int
   1660 cd9660_level2_convert_filename(const char *oldname, char *newname, int is_file)
   1661 {
   1662 	/*
   1663 	 * ISO 9660 : 7.5.1
   1664 	 * File name : 0+ d or d1 characters
   1665 	 * separator 1 (.)
   1666 	 * File name extension : 0+ d or d1 characters
   1667 	 * separator 2 (;)
   1668 	 * File version number (5 characters, 1-32767)
   1669 	 * 1 <= Sum of File name and File name extension <= 30
   1670 	 */
   1671 	int namelen = 0;
   1672 	int extlen = 0;
   1673 	int found_ext = 0;
   1674 
   1675 	while (*oldname != '\0') {
   1676 		/* Handle period first, as it is special */
   1677 		if (*oldname == '.') {
   1678 			if (found_ext) {
   1679 				*newname++ = '_';
   1680 				extlen ++;
   1681 			}
   1682 			else {
   1683 				*newname++ = '.';
   1684 				found_ext = 1;
   1685 			}
   1686 		} else {
   1687 			if ((namelen + extlen) == 30)
   1688 				break;
   1689 
   1690 			 if (islower((unsigned char)*oldname))
   1691 				*newname++ = toupper((unsigned char)*oldname);
   1692 			else if (isupper((unsigned char)*oldname) ||
   1693 			    isdigit((unsigned char)*oldname))
   1694 				*newname++ = *oldname;
   1695 			else
   1696 				*newname++ = '_';
   1697 
   1698 			if (found_ext)
   1699 				extlen++;
   1700 			else
   1701 				namelen++;
   1702 		}
   1703 		oldname ++;
   1704 	}
   1705 	if (is_file) {
   1706 		if (!found_ext && !diskStructure.omit_trailing_period)
   1707 			*newname++ = '.';
   1708 		/* Add version */
   1709 		sprintf(newname, ";%i", 1);
   1710 	}
   1711 	return namelen + extlen + found_ext;
   1712 }
   1713 
   1714 #if 0
   1715 static int
   1716 cd9660_joliet_convert_filename(const char *oldname, char *newname, int is_file)
   1717 {
   1718 	/* TODO: implement later, move to cd9660_joliet.c ?? */
   1719 }
   1720 #endif
   1721 
   1722 
   1723 /*
   1724  * Convert a file name to ISO compliant file name
   1725  * @param char * oldname The original filename
   1726  * @param char ** newname The new file name, in the appropriate character
   1727  *                        set and of appropriate length
   1728  * @param int 1 if file, 0 if directory
   1729  * @returns int The length of the new string
   1730  */
   1731 static int
   1732 cd9660_convert_filename(const char *oldname, char *newname, int is_file)
   1733 {
   1734 	/* NEW */
   1735 	cd9660_filename_conversion_functor conversion_function = 0;
   1736 	if (diskStructure.isoLevel == 1)
   1737 		conversion_function = &cd9660_level1_convert_filename;
   1738 	else if (diskStructure.isoLevel == 2)
   1739 		conversion_function = &cd9660_level2_convert_filename;
   1740 	return (*conversion_function)(oldname, newname, is_file);
   1741 }
   1742 
   1743 int
   1744 cd9660_compute_record_size(cd9660node *node)
   1745 {
   1746 	int size = node->isoDirRecord->length[0];
   1747 
   1748 	if (diskStructure.rock_ridge_enabled)
   1749 		size += node->susp_entry_size;
   1750 	return size;
   1751 }
   1752 
   1753 static void
   1754 cd9660_populate_dot_records(cd9660node *node)
   1755 {
   1756 	node->dot_record->fileDataSector = node->fileDataSector;
   1757 	memcpy(node->dot_record->isoDirRecord,node->isoDirRecord, 34);
   1758 	node->dot_record->isoDirRecord->name_len[0] = 1;
   1759 	node->dot_record->isoDirRecord->name[0] = 0;
   1760 	node->dot_record->isoDirRecord->name[1] = 0;
   1761 	node->dot_record->isoDirRecord->length[0] = 34;
   1762 	node->dot_record->fileRecordSize =
   1763 	    cd9660_compute_record_size(node->dot_record);
   1764 
   1765 	if (node == diskStructure.rootNode) {
   1766 		node->dot_dot_record->fileDataSector = node->fileDataSector;
   1767 		memcpy(node->dot_dot_record->isoDirRecord,node->isoDirRecord,
   1768 		    34);
   1769 	} else {
   1770 		node->dot_dot_record->fileDataSector =
   1771 		    node->parent->fileDataSector;
   1772 		memcpy(node->dot_dot_record->isoDirRecord,
   1773 		    node->parent->isoDirRecord,34);
   1774 	}
   1775 	node->dot_dot_record->isoDirRecord->name_len[0] = 1;
   1776 	node->dot_dot_record->isoDirRecord->name[0] = 1;
   1777 	node->dot_dot_record->isoDirRecord->name[1] = 0;
   1778 	node->dot_dot_record->isoDirRecord->length[0] = 34;
   1779 	node->dot_dot_record->fileRecordSize =
   1780 	    cd9660_compute_record_size(node->dot_dot_record);
   1781 }
   1782 
   1783 static struct cd9660_inode *
   1784 cd9660_inode_lookup(iso9660_disk *disk, uint32_t ino)
   1785 {
   1786 	struct cd9660_inode *in;
   1787 	struct cd9660_inode_head *head;
   1788 
   1789 	head = &disk->inode_hash[CD9660_INODE_HASH(ino)];
   1790 
   1791 	SLIST_FOREACH(in, head, in_link) {
   1792 		if (in->in_ino == ino)
   1793 			break;
   1794 		else if (in->in_ino > ino)
   1795 			return NULL;
   1796 	}
   1797 	return in;
   1798 }
   1799 
   1800 static void
   1801 cd9660_inode_insert(iso9660_disk *disk, struct cd9660_inode *in)
   1802 {
   1803 	struct cd9660_inode *iter_in, *last_in = NULL;
   1804 	struct cd9660_inode_head *head;
   1805 	head = &disk->inode_hash[CD9660_INODE_HASH(in->in_ino)];
   1806 
   1807 	SLIST_FOREACH(iter_in, head, in_link) {
   1808 		assert(iter_in->in_ino != in->in_ino);
   1809 		if (iter_in->in_ino > in->in_ino)
   1810 			break;
   1811 		last_in = iter_in;
   1812 	}
   1813 	if (last_in == NULL)
   1814 		SLIST_INSERT_HEAD(head, in, in_link);
   1815 	else
   1816 		SLIST_INSERT_AFTER(last_in, in, in_link);
   1817 }
   1818 
   1819 /*
   1820  * @param struct cd9660node *node The node
   1821  * @param int The offset (in bytes) - SHOULD align to the beginning of a sector
   1822  * @returns int The total size of files and directory entries (should be
   1823  *              a multiple of sector size)
   1824 */
   1825 static int
   1826 cd9660_compute_offsets(cd9660node *node, int startOffset)
   1827 {
   1828 	/*
   1829 	 * This function needs to compute the size of directory records and
   1830 	 * runs, file lengths, and set the appropriate variables both in
   1831 	 * cd9660node and isoDirEntry
   1832 	 */
   1833 	int used_bytes = 0;
   1834 	int current_sector_usage = 0;
   1835 	cd9660node *child;
   1836 	struct cd9660_inode *in;
   1837 	int r;
   1838 
   1839 	assert(node != NULL);
   1840 
   1841 
   1842 	/*
   1843 	 * NOTE : There needs to be some special case detection for
   1844 	 * the "real root" node, since for it, node->node is undefined
   1845 	 */
   1846 
   1847 	node->fileDataSector = -1;
   1848 
   1849 	if (node->type & CD9660_TYPE_DIR) {
   1850 		node->fileRecordSize = cd9660_compute_record_size(node);
   1851 		/*Set what sector this directory starts in*/
   1852 		node->fileDataSector =
   1853 		    CD9660_BLOCKS(diskStructure.sectorSize,startOffset);
   1854 
   1855 		cd9660_bothendian_dword(node->fileDataSector,
   1856 		    node->isoDirRecord->extent);
   1857 
   1858 		/*
   1859 		 * First loop over children, need to know the size of
   1860 		 * their directory records
   1861 		 */
   1862 		node->fileSectorsUsed = 1;
   1863 		TAILQ_FOREACH(child, &node->cn_children, cn_next_child) {
   1864 			node->fileDataLength +=
   1865 			    cd9660_compute_record_size(child);
   1866 			if ((cd9660_compute_record_size(child) +
   1867 			    current_sector_usage) >=
   1868 		 	    diskStructure.sectorSize) {
   1869 				current_sector_usage = 0;
   1870 				node->fileSectorsUsed++;
   1871 			}
   1872 
   1873 			current_sector_usage +=
   1874 			    cd9660_compute_record_size(child);
   1875 		}
   1876 
   1877 		cd9660_bothendian_dword(node->fileSectorsUsed *
   1878 			diskStructure.sectorSize,node->isoDirRecord->size);
   1879 
   1880 		/*
   1881 		 * This should point to the sector after the directory
   1882 		 * record (or, the first byte in that sector)
   1883 		 */
   1884 		used_bytes += node->fileSectorsUsed * diskStructure.sectorSize;
   1885 
   1886 		for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child);
   1887 		     child != NULL; child = TAILQ_NEXT(child, cn_next_child)) {
   1888 			/* Directories need recursive call */
   1889 			if (S_ISDIR(child->node->type)) {
   1890 				r = cd9660_compute_offsets(child,
   1891 				    used_bytes + startOffset);
   1892 
   1893 				if (r != -1)
   1894 					used_bytes += r;
   1895 				else
   1896 					return -1;
   1897 			}
   1898 		}
   1899 
   1900 		/* Explicitly set the . and .. records */
   1901 		cd9660_populate_dot_records(node);
   1902 
   1903 		/* Finally, do another iteration to write the file data*/
   1904 		for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child);
   1905 		     child != NULL;
   1906 		     child = TAILQ_NEXT(child, cn_next_child)) {
   1907 			/* Files need extent set */
   1908 			if (S_ISDIR(child->node->type))
   1909 				continue;
   1910 			child->fileRecordSize =
   1911 			    cd9660_compute_record_size(child);
   1912 
   1913 			child->fileSectorsUsed =
   1914 			    CD9660_BLOCKS(diskStructure.sectorSize,
   1915 				child->fileDataLength);
   1916 
   1917 			in = cd9660_inode_lookup(&diskStructure,
   1918 			    child->node->inode->st.st_ino);
   1919 			if (in != NULL) {
   1920 				INODE_WARNX(("%s: already allocated inode %d"
   1921 				      " (%" PRIu32 ") data sectors", __func__,
   1922 				      (int)child->node->inode->st.st_ino,
   1923 				      in->in_ino));
   1924 			} else if ((in = calloc(1, sizeof(*in))) == NULL)
   1925 				err(EXIT_FAILURE, "%s: calloc", __func__);
   1926 			else {
   1927 				in->in_ino = child->node->inode->st.st_ino;
   1928 				in->in_data_sector =
   1929 				    CD9660_BLOCKS(diskStructure.sectorSize,
   1930 				        used_bytes + startOffset);
   1931 				cd9660_inode_insert(&diskStructure, in);
   1932 				used_bytes += child->fileSectorsUsed *
   1933 				    diskStructure.sectorSize;
   1934 			}
   1935 			child->fileDataSector = in->in_data_sector;
   1936 			cd9660_bothendian_dword(child->fileDataSector,
   1937 				child->isoDirRecord->extent);
   1938 		}
   1939 	}
   1940 
   1941 	return used_bytes;
   1942 }
   1943 
   1944 #if 0
   1945 /* Might get rid of this func */
   1946 static int
   1947 cd9660_copy_stat_info(cd9660node *from, cd9660node *to, int file)
   1948 {
   1949 	to->node->inode->st.st_dev = 0;
   1950 	to->node->inode->st.st_ino = 0;
   1951 	to->node->inode->st.st_size = 0;
   1952 	to->node->inode->st.st_blksize = from->node->inode->st.st_blksize;
   1953 	to->node->inode->st.st_atime = from->node->inode->st.st_atime;
   1954 	to->node->inode->st.st_mtime = from->node->inode->st.st_mtime;
   1955 	to->node->inode->st.st_ctime = from->node->inode->st.st_ctime;
   1956 	to->node->inode->st.st_uid = from->node->inode->st.st_uid;
   1957 	to->node->inode->st.st_gid = from->node->inode->st.st_gid;
   1958 	to->node->inode->st.st_mode = from->node->inode->st.st_mode;
   1959 	/* Clear out type */
   1960 	to->node->inode->st.st_mode = to->node->inode->st.st_mode & ~(S_IFMT);
   1961 	if (file)
   1962 		to->node->inode->st.st_mode |= S_IFREG;
   1963 	else
   1964 		to->node->inode->st.st_mode |= S_IFDIR;
   1965 	return 1;
   1966 }
   1967 #endif
   1968 
   1969 static cd9660node *
   1970 cd9660_create_virtual_entry(const char *name, cd9660node *parent, int file,
   1971 			    int insert)
   1972 {
   1973 	cd9660node *temp;
   1974 	fsnode * tfsnode;
   1975 
   1976 	assert(parent != NULL);
   1977 
   1978 	temp = cd9660_allocate_cd9660node();
   1979 	if (temp == NULL)
   1980 		return NULL;
   1981 
   1982 	if ((tfsnode = malloc(sizeof(fsnode))) == NULL) {
   1983 		CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry");
   1984 		return NULL;
   1985 	}
   1986 
   1987 	/* Assume for now name is a valid length */
   1988 	if ((tfsnode->name = malloc(strlen(name) + 1)) == NULL) {
   1989 		CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry");
   1990 		return NULL;
   1991 	}
   1992 
   1993 	if ((temp->isoDirRecord =
   1994 	    malloc(sizeof(iso_directory_record_cd9660))) == NULL) {
   1995 		CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry");
   1996 		return NULL;
   1997 	}
   1998 
   1999 	strcpy(tfsnode->name, name);
   2000 
   2001 	cd9660_convert_filename(tfsnode->name, temp->isoDirRecord->name, file);
   2002 
   2003 	temp->node = tfsnode;
   2004 	temp->parent = parent;
   2005 
   2006 	if (insert) {
   2007 		if (temp->parent != NULL) {
   2008 			temp->level = temp->parent->level + 1;
   2009 			if (!TAILQ_EMPTY(&temp->parent->cn_children))
   2010 				cd9660_sorted_child_insert(temp->parent, temp);
   2011 			else
   2012 				TAILQ_INSERT_HEAD(&temp->parent->cn_children,
   2013 				    temp, cn_next_child);
   2014 		}
   2015 	}
   2016 
   2017 	if (parent->node != NULL) {
   2018 		tfsnode->type = parent->node->type;
   2019 	}
   2020 
   2021 	/* Clear out file type bits */
   2022 	tfsnode->type &= ~(S_IFMT);
   2023 	if (file)
   2024 		tfsnode->type |= S_IFREG;
   2025 	else
   2026 		tfsnode->type |= S_IFDIR;
   2027 
   2028 	/* Indicate that there is no spec entry (inode) */
   2029 	tfsnode->flags &= ~(FSNODE_F_HASSPEC);
   2030 #if 0
   2031 	cd9660_copy_stat_info(parent, temp, file);
   2032 #endif
   2033 	return temp;
   2034 }
   2035 
   2036 static cd9660node *
   2037 cd9660_create_file(const char * name, cd9660node *parent)
   2038 {
   2039 	cd9660node *temp;
   2040 
   2041 	temp = cd9660_create_virtual_entry(name,parent,1,1);
   2042 	if (temp == NULL)
   2043 		return NULL;
   2044 
   2045 	temp->fileDataLength = 0;
   2046 
   2047 	temp->type = CD9660_TYPE_FILE | CD9660_TYPE_VIRTUAL;
   2048 
   2049 	if (cd9960_translate_node_common(temp) == 0)
   2050 		return NULL;
   2051 	return temp;
   2052 }
   2053 
   2054 /*
   2055  * Create a new directory which does not exist on disk
   2056  * @param const char * name The name to assign to the directory
   2057  * @param const char * parent Pointer to the parent directory
   2058  * @returns cd9660node * Pointer to the new directory
   2059  */
   2060 static cd9660node *
   2061 cd9660_create_directory(const char *name, cd9660node *parent)
   2062 {
   2063 	cd9660node *temp;
   2064 
   2065 	temp = cd9660_create_virtual_entry(name,parent,0,1);
   2066 	if (temp == NULL)
   2067 		return NULL;
   2068 	temp->node->type |= S_IFDIR;
   2069 
   2070 	temp->type = CD9660_TYPE_DIR | CD9660_TYPE_VIRTUAL;
   2071 
   2072 	if (cd9960_translate_node_common(temp) == 0)
   2073 		return NULL;
   2074 	return temp;
   2075 }
   2076 
   2077 static cd9660node *
   2078 cd9660_create_special_directory(u_char type, cd9660node *parent)
   2079 {
   2080 	cd9660node *temp, *first;
   2081 	char na[2];
   2082 
   2083 	assert(parent != NULL);
   2084 
   2085 	if (type == CD9660_TYPE_DOT)
   2086 		na[0] = 0;
   2087 	else if (type == CD9660_TYPE_DOTDOT)
   2088 		na[0] = 1;
   2089 	else
   2090 		return 0;
   2091 
   2092 	na[1] = 0;
   2093 	if ((temp = cd9660_create_virtual_entry(na, parent, 0, 0)) == NULL)
   2094 		return NULL;
   2095 
   2096 	temp->parent = parent;
   2097 	temp->type = type;
   2098 	temp->isoDirRecord->length[0] = 34;
   2099 	/* Dot record is always first */
   2100 	if (type == CD9660_TYPE_DOT) {
   2101 		parent->dot_record = temp;
   2102 		TAILQ_INSERT_HEAD(&parent->cn_children, temp, cn_next_child);
   2103 	/* DotDot should be second */
   2104 	} else if (type == CD9660_TYPE_DOTDOT) {
   2105 		parent->dot_dot_record = temp;
   2106 		/*
   2107                  * If the first child is the dot record, insert
   2108                  * this second.  Otherwise, insert it at the head.
   2109 		 */
   2110 		if ((first = TAILQ_FIRST(&parent->cn_children)) == NULL ||
   2111 		    (first->type & CD9660_TYPE_DOT) == 0) {
   2112 			TAILQ_INSERT_HEAD(&parent->cn_children, temp,
   2113 			    cn_next_child);
   2114 		} else {
   2115 			TAILQ_INSERT_AFTER(&parent->cn_children, first, temp,
   2116 			    cn_next_child);
   2117 		}
   2118 	}
   2119 
   2120 	return temp;
   2121 }
   2122 
   2123