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