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