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