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