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