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