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