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