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