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