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