1 /* $NetBSD: cd9660.c,v 1.56 2019/10/18 04:09:02 msaitoh Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause AND BSD-4-Clause
6 * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan
7 * Perez-Rathke and Ram Vedam. All rights reserved.
9 * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys,
10 * Alan Perez-Rathke and Ram Vedam.
12 * Redistribution and use in source and binary forms, with or
13 * without modification, are permitted provided that the following
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above
18 * copyright notice, this list of conditions and the following
19 * disclaimer in the documentation and/or other materials provided
20 * with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN
23 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN
27 * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT,
28 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30 * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
37 * Copyright (c) 2001 Wasabi Systems, Inc.
38 * All rights reserved.
40 * Written by Luke Mewburn for Wasabi Systems, Inc.
42 * Redistribution and use in source and binary forms, with or without
43 * modification, are permitted provided that the following conditions
45 * 1. Redistributions of source code must retain the above copyright
46 * notice, this list of conditions and the following disclaimer.
47 * 2. Redistributions in binary form must reproduce the above copyright
48 * notice, this list of conditions and the following disclaimer in the
49 * documentation and/or other materials provided with the distribution.
50 * 3. All advertising materials mentioning features or use of this software
51 * must display the following acknowledgement:
52 * This product includes software developed for the NetBSD Project by
53 * Wasabi Systems, Inc.
54 * 4. The name of Wasabi Systems, Inc. may not be used to endorse
55 * or promote products derived from this software without specific prior
58 * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
59 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
60 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
61 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC
62 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
65 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
66 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
67 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
68 * POSSIBILITY OF SUCH DAMAGE.
71 * Copyright (c) 1982, 1986, 1989, 1993
72 * The Regents of the University of California. All rights reserved.
74 * Redistribution and use in source and binary forms, with or without
75 * modification, are permitted provided that the following conditions
77 * 1. Redistributions of source code must retain the above copyright
78 * notice, this list of conditions and the following disclaimer.
79 * 2. Redistributions in binary form must reproduce the above copyright
80 * notice, this list of conditions and the following disclaimer in the
81 * documentation and/or other materials provided with the distribution.
82 * 3. Neither the name of the University nor the names of its contributors
83 * may be used to endorse or promote products derived from this software
84 * without specific prior written permission.
86 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
87 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
88 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
89 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
90 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
91 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
92 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
93 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
94 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
95 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
100 #include <sys/cdefs.h>
101 __FBSDID("$FreeBSD$");
103 #include <sys/param.h>
104 #include <sys/queue.h>
112 #include "cd9660/iso9660_rrip.h"
113 #include "cd9660/cd9660_archimedes.h"
115 static void cd9660_finalize_PVD(iso9660_disk *);
116 static cd9660node *cd9660_allocate_cd9660node(void);
117 static void cd9660_set_defaults(iso9660_disk *);
118 static int cd9660_arguments_set_string(const char *, const char *, size_t,
120 static void cd9660_populate_iso_dir_record(
121 struct _iso_directory_record_cd9660 *, u_char, u_char, u_char,
123 static void cd9660_setup_root_node(iso9660_disk *);
124 static int cd9660_setup_volume_descriptors(iso9660_disk *);
126 static int cd9660_fill_extended_attribute_record(cd9660node *);
128 static void cd9660_sort_nodes(cd9660node *);
129 static int cd9660_translate_node_common(iso9660_disk *, cd9660node *);
130 static int cd9660_translate_node(iso9660_disk *, fsnode *, cd9660node *);
131 static int cd9660_compare_filename(const char *, const char *);
132 static void cd9660_sorted_child_insert(cd9660node *, cd9660node *);
133 static int cd9660_handle_collisions(iso9660_disk *, cd9660node *, int);
134 static cd9660node *cd9660_rename_filename(iso9660_disk *, cd9660node *, int,
136 static void cd9660_copy_filenames(iso9660_disk *, cd9660node *);
137 static void cd9660_sorting_nodes(cd9660node *);
138 static int cd9660_count_collisions(cd9660node *);
139 static cd9660node *cd9660_rrip_move_directory(iso9660_disk *, cd9660node *);
140 static int cd9660_add_dot_records(iso9660_disk *, cd9660node *);
142 static void cd9660_convert_structure(iso9660_disk *, fsnode *, cd9660node *, int,
144 static void cd9660_free_structure(cd9660node *);
145 static int cd9660_generate_path_table(iso9660_disk *);
146 static int cd9660_level1_convert_filename(iso9660_disk *, const char *, char *,
148 static int cd9660_level2_convert_filename(iso9660_disk *, const char *, char *,
150 static int cd9660_convert_filename(iso9660_disk *, const char *, char *, int);
151 static void cd9660_populate_dot_records(iso9660_disk *, cd9660node *);
152 static int64_t cd9660_compute_offsets(iso9660_disk *, cd9660node *, int64_t);
154 static int cd9660_copy_stat_info(cd9660node *, cd9660node *, int);
156 static cd9660node *cd9660_create_virtual_entry(iso9660_disk *, const char *,
157 cd9660node *, int, int);
158 static cd9660node *cd9660_create_file(iso9660_disk *, const char *,
159 cd9660node *, cd9660node *);
160 static cd9660node *cd9660_create_directory(iso9660_disk *, const char *,
161 cd9660node *, cd9660node *);
162 static cd9660node *cd9660_create_special_directory(iso9660_disk *, u_char,
164 static int cd9660_add_generic_bootimage(iso9660_disk *, const char *);
168 * Allocate and initialize a cd9660node
169 * @returns struct cd9660node * Pointer to new node, or NULL on error
172 cd9660_allocate_cd9660node(void)
174 cd9660node *temp = ecalloc(1, sizeof(*temp));
176 TAILQ_INIT(&temp->cn_children);
177 temp->parent = temp->dot_record = temp->dot_dot_record = NULL;
178 temp->ptnext = temp->ptprev = temp->ptlast = NULL;
180 temp->isoDirRecord = NULL;
181 temp->isoExtAttributes = NULL;
182 temp->rr_real_parent = temp->rr_relocated = NULL;
183 temp->su_tail_data = NULL;
188 * Set default values for cd9660 extension to makefs
191 cd9660_set_defaults(iso9660_disk *diskStructure)
193 /*Fix the sector size for now, though the spec allows for other sizes*/
194 diskStructure->sectorSize = 2048;
196 /* Set up defaults in our own structure */
197 diskStructure->verbose_level = 0;
198 diskStructure->keep_bad_images = 0;
199 diskStructure->isoLevel = 2;
201 diskStructure->rock_ridge_enabled = 0;
202 diskStructure->rock_ridge_renamed_dir_name = 0;
203 diskStructure->rock_ridge_move_count = 0;
204 diskStructure->rr_moved_dir = 0;
206 diskStructure->archimedes_enabled = 0;
207 diskStructure->chrp_boot = 0;
209 diskStructure->include_padding_areas = 1;
211 /* Spec breaking functionality */
212 diskStructure->allow_deep_trees =
213 diskStructure->allow_start_dot =
214 diskStructure->allow_max_name =
215 diskStructure->allow_illegal_chars =
216 diskStructure->allow_lowercase =
217 diskStructure->allow_multidot =
218 diskStructure->omit_trailing_period = 0;
220 /* Make sure the PVD is clear */
221 memset(&diskStructure->primaryDescriptor, 0, 2048);
223 memset(diskStructure->primaryDescriptor.publisher_id, 0x20,128);
224 memset(diskStructure->primaryDescriptor.preparer_id, 0x20,128);
225 memset(diskStructure->primaryDescriptor.application_id, 0x20,128);
226 memset(diskStructure->primaryDescriptor.copyright_file_id, 0x20,37);
227 memset(diskStructure->primaryDescriptor.abstract_file_id, 0x20,37);
228 memset(diskStructure->primaryDescriptor.bibliographic_file_id, 0x20,37);
230 strcpy(diskStructure->primaryDescriptor.system_id, "FreeBSD");
232 /* Boot support: Initially disabled */
233 diskStructure->has_generic_bootimage = 0;
234 diskStructure->generic_bootimage = NULL;
236 diskStructure->boot_image_directory = 0;
237 /*memset(diskStructure->boot_descriptor, 0, 2048);*/
239 diskStructure->is_bootable = 0;
240 TAILQ_INIT(&diskStructure->boot_images);
241 LIST_INIT(&diskStructure->boot_entries);
245 cd9660_prep_opts(fsinfo_t *fsopts)
247 iso9660_disk *diskStructure = ecalloc(1, sizeof(*diskStructure));
249 #define OPT_STR(letter, name, desc) \
250 { letter, name, NULL, OPT_STRBUF, 0, 0, desc }
252 #define OPT_NUM(letter, name, field, min, max, desc) \
253 { letter, name, &diskStructure->field, \
254 sizeof(diskStructure->field) == 8 ? OPT_INT64 : \
255 (sizeof(diskStructure->field) == 4 ? OPT_INT32 : \
256 (sizeof(diskStructure->field) == 2 ? OPT_INT16 : OPT_INT8)), \
259 #define OPT_BOOL(letter, name, field, desc) \
260 OPT_NUM(letter, name, field, 0, 1, desc)
262 const option_t cd9660_options[] = {
263 OPT_NUM('l', "isolevel", isoLevel,
265 OPT_NUM('v', "verbose", verbose_level,
266 0, 2, "Turns on verbose output"),
268 OPT_BOOL('R', "rockridge", rock_ridge_enabled,
269 "Enable Rock-Ridge extensions"),
270 OPT_BOOL('C', "chrp-boot", chrp_boot,
272 OPT_BOOL('K', "keep-bad-images", keep_bad_images,
274 OPT_BOOL('D', "allow-deep-trees", allow_deep_trees,
275 "Allow trees more than 8 levels"),
276 OPT_BOOL('a', "allow-max-name", allow_max_name,
277 "Allow 37 char filenames (unimplemented)"),
278 OPT_BOOL('i', "allow-illegal-chars", allow_illegal_chars,
279 "Allow illegal characters in filenames"),
280 OPT_BOOL('m', "allow-multidot", allow_multidot,
281 "Allow multiple periods in filenames"),
282 OPT_BOOL('o', "omit-trailing-period", omit_trailing_period,
283 "Omit trailing periods in filenames"),
284 OPT_BOOL('\0', "allow-lowercase", allow_lowercase,
285 "Allow lowercase characters in filenames"),
286 OPT_BOOL('\0', "archimedes", archimedes_enabled,
287 "Enable Archimedes structure"),
288 OPT_BOOL('\0', "no-trailing-padding", include_padding_areas,
289 "Include padding areas"),
291 OPT_STR('A', "applicationid", "Application Identifier"),
292 OPT_STR('P', "publisher", "Publisher Identifier"),
293 OPT_STR('p', "preparer", "Preparer Identifier"),
294 OPT_STR('L', "label", "Disk Label"),
295 OPT_STR('V', "volumeid", "Volume Set Identifier"),
296 OPT_STR('B', "bootimage", "Boot image parameter"),
297 OPT_STR('G', "generic-bootimage", "Generic boot image param"),
298 OPT_STR('\0', "bootimagedir", "Boot image directory"),
299 OPT_STR('\0', "no-emul-boot", "No boot emulation"),
300 OPT_STR('\0', "no-boot", "No boot support"),
301 OPT_STR('\0', "hard-disk-boot", "Boot from hard disk"),
302 OPT_STR('\0', "boot-load-segment", "Boot load segment"),
303 OPT_STR('\0', "platformid", "Section Header Platform ID"),
308 fsopts->fs_specific = diskStructure;
309 fsopts->fs_options = copy_opts(cd9660_options);
311 cd9660_set_defaults(diskStructure);
315 cd9660_cleanup_opts(fsinfo_t *fsopts)
317 free(fsopts->fs_specific);
318 free(fsopts->fs_options);
322 cd9660_arguments_set_string(const char *val, const char *fieldtitle,
323 size_t length, char testmode, char *dest)
329 warnx("error: '%s' requires a string argument", fieldtitle);
330 else if ((len = strlen(val)) <= length) {
332 test = cd9660_valid_d_chars(val);
334 test = cd9660_valid_a_chars(val);
336 memcpy(dest, val, len);
338 cd9660_uppercase_characters(dest, len);
341 warnx("error: '%s' must be composed of %c-characters",
342 fieldtitle, testmode);
344 warnx("error: '%s' must be at most 32 characters long",
350 * Command-line parsing function
354 cd9660_parse_opts(const char *option, fsinfo_t *fsopts)
357 iso9660_disk *diskStructure = fsopts->fs_specific;
358 option_t *cd9660_options = fsopts->fs_options;
360 const char *name, *desc;
362 assert(option != NULL);
364 if (debug & DEBUG_FS_PARSE_OPTS)
365 printf("%s: got `%s'\n", __func__, option);
367 i = set_option(cd9660_options, option, buf, sizeof(buf));
371 if (cd9660_options[i].name == NULL)
374 name = cd9660_options[i].name;
375 desc = cd9660_options[i].desc;
376 switch (cd9660_options[i].letter) {
379 rv = 0; /* this is not handled yet */
382 rv = cd9660_arguments_set_string(buf, desc, 32, 'd',
383 diskStructure->primaryDescriptor.volume_id);
386 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
387 diskStructure->primaryDescriptor.application_id);
390 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
391 diskStructure->primaryDescriptor.publisher_id);
394 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
395 diskStructure->primaryDescriptor.preparer_id);
398 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
399 diskStructure->primaryDescriptor.volume_set_id);
403 if (buf[0] == '\0') {
404 warnx("The Boot Image parameter requires a valid boot"
405 "information string");
408 rv = cd9660_add_boot_disk(diskStructure, buf);
411 if (buf[0] == '\0') {
412 warnx("The Generic Boot Image parameter requires a"
413 " valid boot information string");
416 rv = cd9660_add_generic_bootimage(diskStructure, buf);
419 if (strcmp(name, "bootimagedir") == 0) {
421 * XXXfvdl this is unused.
423 if (buf[0] == '\0') {
424 warnx("The Boot Image Directory parameter"
425 " requires a directory name");
428 diskStructure->boot_image_directory =
429 emalloc(strlen(buf) + 1);
430 /* BIG TODO: Add the max length function here */
431 rv = cd9660_arguments_set_string(buf, desc, 12,
432 'd', diskStructure->boot_image_directory);
434 } else if (strcmp(name, "no-emul-boot") == 0 ||
435 strcmp(name, "no-boot") == 0 ||
436 strcmp(name, "hard-disk-boot") == 0) {
438 cd9660_eltorito_add_boot_option(diskStructure, name, 0);
440 } else if (strcmp(name, "boot-load-segment") == 0 ||
441 strcmp(name, "platformid") == 0) {
442 if (buf[0] == '\0') {
443 warnx("Option `%s' doesn't contain a value",
447 cd9660_eltorito_add_boot_option(diskStructure,
458 * Main function for cd9660_makefs
459 * Builds the ISO image file
460 * @param const char *image The image filename to create
461 * @param const char *dir The directory that is being read
462 * @param struct fsnode *root The root node of the filesystem tree
463 * @param struct fsinfo_t *fsopts Any options
466 cd9660_makefs(const char *image, const char *dir, fsnode *root,
471 uint64_t pathTableSectors;
472 int64_t firstAvailableSector;
475 cd9660node *real_root;
476 iso9660_disk *diskStructure = fsopts->fs_specific;
478 if (diskStructure->verbose_level > 0)
479 printf("%s: ISO level is %i\n", __func__,
480 diskStructure->isoLevel);
481 if (diskStructure->isoLevel < 2 &&
482 diskStructure->allow_multidot)
483 errx(EXIT_FAILURE, "allow-multidot requires iso level of 2");
485 assert(image != NULL);
487 assert(root != NULL);
489 if (diskStructure->verbose_level > 0)
490 printf("%s: image %s directory %s root %p\n", __func__,
493 /* Set up some constants. Later, these will be defined with options */
495 /* Counter needed for path tables */
498 /* Convert tree to our own format */
499 /* Actually, we now need to add the REAL root node, at level 0 */
501 real_root = cd9660_allocate_cd9660node();
502 real_root->isoDirRecord = emalloc(sizeof(*real_root->isoDirRecord));
503 /* Leave filename blank for root */
504 memset(real_root->isoDirRecord->name, 0,
505 ISO_FILENAME_MAXLENGTH_WITH_PADDING);
507 real_root->level = 0;
508 diskStructure->rootNode = real_root;
509 real_root->type = CD9660_TYPE_DIR;
511 real_root->node = root;
512 cd9660_convert_structure(diskStructure, root, real_root, 1,
513 &numDirectories, &error);
515 if (TAILQ_EMPTY(&real_root->cn_children)) {
516 errx(EXIT_FAILURE, "%s: converted directory is empty. "
517 "Tree conversion failed", __func__);
518 } else if (error != 0) {
519 errx(EXIT_FAILURE, "%s: tree conversion failed", __func__);
521 if (diskStructure->verbose_level > 0)
522 printf("%s: tree converted\n", __func__);
525 /* Add the dot and dot dot records */
526 cd9660_add_dot_records(diskStructure, real_root);
528 cd9660_setup_root_node(diskStructure);
530 if (diskStructure->verbose_level > 0)
531 printf("%s: done converting tree\n", __func__);
533 /* non-SUSP extensions */
534 if (diskStructure->archimedes_enabled)
535 archimedes_convert_tree(diskStructure->rootNode);
537 /* Rock ridge / SUSP init pass */
538 if (diskStructure->rock_ridge_enabled) {
539 cd9660_susp_initialize(diskStructure, diskStructure->rootNode,
540 diskStructure->rootNode, NULL);
543 /* Build path table structure */
544 diskStructure->pathTableLength = cd9660_generate_path_table(
547 pathTableSectors = CD9660_BLOCKS(diskStructure->sectorSize,
548 diskStructure->pathTableLength);
550 firstAvailableSector = cd9660_setup_volume_descriptors(diskStructure);
551 if (diskStructure->is_bootable) {
552 firstAvailableSector = cd9660_setup_boot(diskStructure,
553 firstAvailableSector);
554 if (firstAvailableSector < 0)
555 errx(EXIT_FAILURE, "setup_boot failed");
557 /* LE first, then BE */
558 diskStructure->primaryLittleEndianTableSector = firstAvailableSector;
559 diskStructure->primaryBigEndianTableSector =
560 diskStructure->primaryLittleEndianTableSector + pathTableSectors;
562 /* Set the secondary ones to -1, not going to use them for now */
563 diskStructure->secondaryBigEndianTableSector = -1;
564 diskStructure->secondaryLittleEndianTableSector = -1;
566 diskStructure->dataFirstSector =
567 diskStructure->primaryBigEndianTableSector + pathTableSectors;
568 if (diskStructure->verbose_level > 0)
569 printf("%s: Path table conversion complete. "
570 "Each table is %i bytes, or %" PRIu64 " sectors.\n",
572 diskStructure->pathTableLength, pathTableSectors);
574 startoffset = diskStructure->sectorSize*diskStructure->dataFirstSector;
576 totalSpace = cd9660_compute_offsets(diskStructure, real_root, startoffset);
578 diskStructure->totalSectors = diskStructure->dataFirstSector +
579 CD9660_BLOCKS(diskStructure->sectorSize, totalSpace);
581 /* Disabled until pass 1 is done */
582 if (diskStructure->rock_ridge_enabled) {
583 diskStructure->susp_continuation_area_start_sector =
584 diskStructure->totalSectors;
585 diskStructure->totalSectors +=
586 CD9660_BLOCKS(diskStructure->sectorSize,
587 diskStructure->susp_continuation_area_size);
588 cd9660_susp_finalize(diskStructure, diskStructure->rootNode);
592 cd9660_finalize_PVD(diskStructure);
594 /* Add padding sectors, just for testing purposes right now */
595 /* diskStructure->totalSectors+=150; */
597 /* Debugging output */
598 if (diskStructure->verbose_level > 0) {
599 printf("%s: Sectors 0-15 reserved\n", __func__);
600 printf("%s: Primary path tables starts in sector %"
601 PRId64 "\n", __func__,
602 diskStructure->primaryLittleEndianTableSector);
603 printf("%s: File data starts in sector %"
604 PRId64 "\n", __func__, diskStructure->dataFirstSector);
605 printf("%s: Total sectors: %"
606 PRId64 "\n", __func__, diskStructure->totalSectors);
610 * Add padding sectors at the end
611 * TODO: Clean this up and separate padding
613 if (diskStructure->include_padding_areas)
614 diskStructure->totalSectors += 150;
616 cd9660_write_image(diskStructure, image);
618 if (diskStructure->verbose_level > 1) {
619 debug_print_volume_descriptor_information(diskStructure);
620 debug_print_tree(diskStructure, real_root, 0);
621 debug_print_path_tree(real_root);
624 /* Clean up data structures */
625 cd9660_free_structure(real_root);
627 if (diskStructure->verbose_level > 0)
628 printf("%s: done\n", __func__);
631 /* Generic function pointer - implement later */
632 typedef int (*cd9660node_func)(cd9660node *);
635 cd9660_finalize_PVD(iso9660_disk *diskStructure)
637 time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL);
639 /* root should be a fixed size of 34 bytes since it has no name */
640 memcpy(diskStructure->primaryDescriptor.root_directory_record,
641 diskStructure->rootNode->dot_record->isoDirRecord, 34);
643 /* In RRIP, this might be longer than 34 */
644 diskStructure->primaryDescriptor.root_directory_record[0] = 34;
646 /* Set up all the important numbers in the PVD */
647 cd9660_bothendian_dword(diskStructure->totalSectors,
648 (unsigned char *)diskStructure->primaryDescriptor.volume_space_size);
649 cd9660_bothendian_word(1,
650 (unsigned char *)diskStructure->primaryDescriptor.volume_set_size);
651 cd9660_bothendian_word(1,
653 diskStructure->primaryDescriptor.volume_sequence_number);
654 cd9660_bothendian_word(diskStructure->sectorSize,
656 diskStructure->primaryDescriptor.logical_block_size);
657 cd9660_bothendian_dword(diskStructure->pathTableLength,
658 (unsigned char *)diskStructure->primaryDescriptor.path_table_size);
660 cd9660_731(diskStructure->primaryLittleEndianTableSector,
661 (u_char *)diskStructure->primaryDescriptor.type_l_path_table);
662 cd9660_732(diskStructure->primaryBigEndianTableSector,
663 (u_char *)diskStructure->primaryDescriptor.type_m_path_table);
665 diskStructure->primaryDescriptor.file_structure_version[0] = 1;
667 /* Pad all strings with spaces instead of nulls */
668 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.volume_id, 32);
669 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.system_id, 32);
670 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.volume_set_id,
672 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.publisher_id,
674 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.preparer_id,
676 cd9660_pad_string_spaces(diskStructure->primaryDescriptor.application_id,
678 cd9660_pad_string_spaces(
679 diskStructure->primaryDescriptor.copyright_file_id, 37);
680 cd9660_pad_string_spaces(
681 diskStructure->primaryDescriptor.abstract_file_id, 37);
682 cd9660_pad_string_spaces(
683 diskStructure->primaryDescriptor.bibliographic_file_id, 37);
687 (unsigned char *)diskStructure->primaryDescriptor.creation_date,
690 (unsigned char *)diskStructure->primaryDescriptor.modification_date,
694 cd9660_set_date(diskStructure->primaryDescriptor.expiration_date,
698 memset(diskStructure->primaryDescriptor.expiration_date, '0', 16);
699 diskStructure->primaryDescriptor.expiration_date[16] = 0;
702 (unsigned char *)diskStructure->primaryDescriptor.effective_date,
705 cd9660_time_915(diskStructure->rootNode->dot_record->isoDirRecord->date,
710 cd9660_populate_iso_dir_record(struct _iso_directory_record_cd9660 *record,
711 u_char ext_attr_length, u_char flags,
712 u_char name_len, const char * name)
714 time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL);
716 record->ext_attr_length[0] = ext_attr_length;
717 cd9660_time_915(record->date, tstamp);
718 record->flags[0] = ISO_FLAG_CLEAR | flags;
719 record->file_unit_size[0] = 0;
720 record->interleave[0] = 0;
721 cd9660_bothendian_word(1, record->volume_sequence_number);
722 record->name_len[0] = name_len;
723 memset(record->name, '\0', sizeof (record->name));
724 memcpy(record->name, name, name_len);
725 record->length[0] = 33 + name_len;
727 /* Todo : better rounding */
728 record->length[0] += (record->length[0] & 1) ? 1 : 0;
732 cd9660_setup_root_node(iso9660_disk *diskStructure)
734 cd9660_populate_iso_dir_record(diskStructure->rootNode->isoDirRecord,
735 0, ISO_FLAG_DIRECTORY, 1, "\0");
739 /*********** SUPPORT FUNCTIONS ***********/
741 cd9660_setup_volume_descriptors(iso9660_disk *diskStructure)
743 /* Boot volume descriptor should come second */
745 /* For now, a fixed 2 : PVD and terminator */
746 volume_descriptor *temp, *t;
749 temp = emalloc(sizeof(*temp));
750 temp->volumeDescriptorData =
751 (unsigned char *)&diskStructure->primaryDescriptor;
752 temp->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_PVD;
753 temp->volumeDescriptorData[6] = 1;
754 temp->sector = sector;
755 memcpy(temp->volumeDescriptorData + 1,
756 ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
757 diskStructure->firstVolumeDescriptor = temp;
760 /* Set up boot support if enabled. BVD must reside in sector 17 */
761 if (diskStructure->is_bootable) {
762 t = emalloc(sizeof(*t));
763 t->volumeDescriptorData = ecalloc(1, 2048);
767 if (diskStructure->verbose_level > 0)
768 printf("Setting up boot volume descriptor\n");
769 cd9660_setup_boot_volume_descriptor(diskStructure, t);
773 /* Set up the terminator */
774 t = emalloc(sizeof(*t));
775 t->volumeDescriptorData = ecalloc(1, 2048);
777 t->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_TERMINATOR;
779 t->volumeDescriptorData[6] = 1;
781 memcpy(t->volumeDescriptorData + 1,
782 ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
790 * Populate EAR at some point. Not required, but is used by NetBSD's
794 cd9660_fill_extended_attribute_record(cd9660node *node)
796 node->isoExtAttributes = emalloc(sizeof(*node->isoExtAttributes));
802 cd9660_translate_node_common(iso9660_disk *diskStructure, cd9660node *newnode)
805 char temp[ISO_FILENAME_MAXLENGTH_WITH_PADDING];
807 /* Now populate the isoDirRecord structure */
808 memset(temp, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING);
810 (void)cd9660_convert_filename(diskStructure, newnode->node->name,
811 temp, !(S_ISDIR(newnode->node->type)));
813 flag = ISO_FLAG_CLEAR;
814 if (S_ISDIR(newnode->node->type))
815 flag |= ISO_FLAG_DIRECTORY;
817 cd9660_populate_iso_dir_record(newnode->isoDirRecord, 0,
818 flag, strlen(temp), temp);
820 cd9660_bothendian_dword(newnode->fileDataLength,
821 newnode->isoDirRecord->size);
822 /* If the file is a link, we want to set the size to 0 */
823 if (S_ISLNK(newnode->node->type))
824 newnode->fileDataLength = 0;
830 * Translate fsnode to cd9660node
831 * Translate filenames and other metadata, including dates, sizes,
833 * @param struct fsnode * The node generated by makefs
834 * @param struct cd9660node * The intermediate node to be written to
835 * @returns int 0 on failure, 1 on success
838 cd9660_translate_node(iso9660_disk *diskStructure, fsnode *node,
842 if (diskStructure->verbose_level > 0)
843 printf("%s: NULL node passed, returning\n", __func__);
846 newnode->isoDirRecord = emalloc(sizeof(*newnode->isoDirRecord));
847 /* Set the node pointer */
848 newnode->node = node;
851 if (!(S_ISDIR(node->type)))
852 newnode->fileDataLength = node->inode->st.st_size;
854 if (cd9660_translate_node_common(diskStructure, newnode) == 0)
857 /* Finally, overwrite some of the values that are set by default */
858 cd9660_time_915(newnode->isoDirRecord->date,
859 stampst.st_ino ? stampst.st_mtime : node->inode->st.st_mtime);
865 * Compares two ISO filenames
866 * @param const char * The first file name
867 * @param const char * The second file name
868 * @returns : -1 if first is less than second, 0 if they are the same, 1 if
869 * the second is greater than the first
872 cd9660_compare_filename(const char *first, const char *second)
875 * This can be made more optimal once it has been tested
876 * (the extra character, for example, is for testing)
882 /* First, on the filename */
884 while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1
885 && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1) {
888 if (c1 == '.' && c2 =='.')
890 else if (c1 == '.') {
893 } else if (c2 == '.') {
908 if (first[p1] == '.' && second[p2] == '.') {
911 while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1
912 && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1) {
915 if (c1 == ';' && c2 == ';')
917 else if (c1 == ';') {
920 } else if (c2 == ';') {
938 * Insert a node into list with ISO sorting rules
939 * @param cd9660node * The head node of the list
940 * @param cd9660node * The node to be inserted
943 cd9660_sorted_child_insert(cd9660node *parent, cd9660node *cn_new)
947 struct cd9660_children_head *head = &parent->cn_children;
949 /* TODO: Optimize? */
950 cn_new->parent = parent;
953 * first will either be 0, the . or the ..
954 * if . or .., this means no other entry may be written before first
955 * if 0, the new node may be inserted at the head
958 TAILQ_FOREACH(cn, head, cn_next_child) {
960 * Dont insert a node twice -
961 * that would cause an infinite loop
966 compare = cd9660_compare_filename(cn_new->isoDirRecord->name,
967 cn->isoDirRecord->name);
970 compare = cd9660_compare_filename(cn_new->node->name,
977 TAILQ_INSERT_TAIL(head, cn_new, cn_next_child);
979 TAILQ_INSERT_BEFORE(cn, cn_new, cn_next_child);
983 * Called After cd9660_sorted_child_insert
984 * handles file collisions by suffixing each filename with ~n
985 * where n represents the files respective place in the ordering
988 cd9660_handle_collisions(iso9660_disk *diskStructure, cd9660node *colliding,
991 cd9660node *iter, *next, *prev;
993 int delete_chars = 0;
994 int temp_past = past;
997 cd9660node *end_of_range;
999 for (iter = TAILQ_FIRST(&colliding->cn_children);
1000 iter != NULL && (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;) {
1001 if (strcmp(iter->isoDirRecord->name,
1002 next->isoDirRecord->name) != 0) {
1003 iter = TAILQ_NEXT(iter, cn_next_child);
1007 temp_skip = skip = cd9660_count_collisions(iter);
1008 end_of_range = iter;
1009 while (temp_skip > 0) {
1011 end_of_range = TAILQ_NEXT(end_of_range, cn_next_child);
1014 while (temp_past > 0) {
1015 if ((next = TAILQ_NEXT(end_of_range, cn_next_child)) != NULL)
1016 end_of_range = next;
1017 else if ((prev = TAILQ_PREV(iter, cd9660_children_head, cn_next_child)) != NULL)
1024 iter = cd9660_rename_filename(diskStructure, iter, skip,
1032 cd9660_rename_filename(iso9660_disk *diskStructure, cd9660node *iter, int num,
1036 int numbts, digit, digits, temp, powers, count;
1041 if (diskStructure->verbose_level > 0)
1042 printf("Rename_filename called\n");
1044 assert(1 <= diskStructure->isoLevel && diskStructure->isoLevel <= 2);
1045 /* TODO : A LOT of chanes regarding 8.3 filenames */
1046 if (diskStructure->isoLevel == 1)
1048 else if (diskStructure->isoLevel == 2)
1051 maxlength = ISO_FILENAME_MAXLENGTH_BEFORE_VERSION;
1053 tmp = emalloc(ISO_FILENAME_MAXLENGTH_WITH_PADDING);
1055 while (i < num && iter) {
1059 while (((int)(i / powers) ) >= 10) {
1061 powers = powers * 10;
1064 naming = iter->o_name;
1067 while ((*naming != '.') && (*naming != ';')) {
1073 while (count < maxlength) {
1080 if ((count + digits) < maxlength)
1083 numbts = maxlength - (digits);
1084 numbts -= delete_chars;
1086 /* 8.3 rules - keep the extension, add before the dot */
1089 * This code makes a bunch of assumptions.
1090 * See if you can spot them all :)
1094 if (diskStructure->isoLevel == 1) {
1095 numbts = 8 - digits - delete_chars;
1100 memmove(&tmp[numbts],&tmp[dot],4);
1106 /* (copying just the filename before the '.' */
1107 memcpy(tmp, (iter->o_name), numbts);
1109 /* adding the appropriate number following the name */
1111 while (digits > 0) {
1112 digit = (int)(temp / powers);
1113 temp = temp - digit * powers;
1114 sprintf(&tmp[numbts] , "%d", digit);
1117 powers = powers / 10;
1120 while ((*naming != ';') && (numbts < maxlength)) {
1121 tmp[numbts] = (*naming);
1127 tmp[numbts+1] = '1';
1128 tmp[numbts+2] = '\0';
1131 * now tmp has exactly the identifier
1132 * we want so we'll copy it back to record
1134 memcpy((iter->isoDirRecord->name), tmp, numbts + 3);
1136 iter = TAILQ_NEXT(iter, cn_next_child);
1144 /* Todo: Figure out why these functions are nec. */
1146 cd9660_copy_filenames(iso9660_disk *diskStructure, cd9660node *node)
1150 if (TAILQ_EMPTY(&node->cn_children))
1153 if (TAILQ_FIRST(&node->cn_children)->isoDirRecord == NULL) {
1154 debug_print_tree(diskStructure, diskStructure->rootNode, 0);
1158 TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) {
1159 cd9660_copy_filenames(diskStructure, cn);
1160 memcpy(cn->o_name, cn->isoDirRecord->name,
1161 ISO_FILENAME_MAXLENGTH_WITH_PADDING);
1166 cd9660_sorting_nodes(cd9660node *node)
1170 TAILQ_FOREACH(cn, &node->cn_children, cn_next_child)
1171 cd9660_sorting_nodes(cn);
1172 cd9660_sort_nodes(node);
1175 /* XXX Bubble sort. */
1177 cd9660_sort_nodes(cd9660node *node)
1179 cd9660node *cn, *next;
1182 TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) {
1183 if ((next = TAILQ_NEXT(cn, cn_next_child)) == NULL)
1185 else if (strcmp(next->isoDirRecord->name,
1186 cn->isoDirRecord->name) >= 0)
1188 TAILQ_REMOVE(&node->cn_children, next, cn_next_child);
1189 TAILQ_INSERT_BEFORE(cn, next, cn_next_child);
1192 } while (cn != NULL);
1196 cd9660_count_collisions(cd9660node *copy)
1199 cd9660node *iter, *next;
1202 (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;
1204 if (cd9660_compare_filename(iter->isoDirRecord->name,
1205 next->isoDirRecord->name) == 0)
1211 if ((next = TAILQ_NEXT(iter, cn_next_child)) != NULL) {
1212 printf("%s: count is %i\n", __func__, count);
1213 compare = cd9660_compare_filename(iter->isoDirRecord->name,
1214 next->isoDirRecord->name);
1217 return cd9660_recurse_on_collision(next, count);
1226 cd9660_rrip_move_directory(iso9660_disk *diskStructure, cd9660node *dir)
1232 * This function needs to:
1233 * 1) Create an empty virtual file in place of the old directory
1234 * 2) Point the virtual file to the new directory
1235 * 3) Point the relocated directory to its old parent
1236 * 4) Move the directory specified by dir into rr_moved_dir,
1237 * and rename it to "diskStructure->rock_ridge_move_count" (as a string)
1240 /* First see if the moved directory even exists */
1241 if (diskStructure->rr_moved_dir == NULL) {
1242 diskStructure->rr_moved_dir = cd9660_create_directory(
1243 diskStructure, ISO_RRIP_DEFAULT_MOVE_DIR_NAME,
1244 diskStructure->rootNode, dir);
1245 if (diskStructure->rr_moved_dir == NULL)
1247 cd9660_time_915(diskStructure->rr_moved_dir->isoDirRecord->date,
1248 stampst.st_ino ? stampst.st_mtime : start_time.tv_sec);
1251 /* Create a file with the same ORIGINAL name */
1252 tfile = cd9660_create_file(diskStructure, dir->node->name, dir->parent,
1257 diskStructure->rock_ridge_move_count++;
1258 snprintf(newname, sizeof(newname), "%08u",
1259 diskStructure->rock_ridge_move_count);
1261 /* Point to old parent */
1262 dir->rr_real_parent = dir->parent;
1264 /* Place the placeholder file */
1265 if (TAILQ_EMPTY(&dir->rr_real_parent->cn_children)) {
1266 TAILQ_INSERT_HEAD(&dir->rr_real_parent->cn_children, tfile,
1269 cd9660_sorted_child_insert(dir->rr_real_parent, tfile);
1272 /* Point to new parent */
1273 dir->parent = diskStructure->rr_moved_dir;
1275 /* Point the file to the moved directory */
1276 tfile->rr_relocated = dir;
1278 /* Actually move the directory */
1279 cd9660_sorted_child_insert(diskStructure->rr_moved_dir, dir);
1281 /* TODO: Inherit permissions / ownership (basically the entire inode) */
1283 /* Set the new name */
1284 memset(dir->isoDirRecord->name, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING);
1285 strncpy(dir->isoDirRecord->name, newname, 8);
1286 dir->isoDirRecord->length[0] = 34 + 8;
1287 dir->isoDirRecord->name_len[0] = 8;
1293 cd9660_add_dot_records(iso9660_disk *diskStructure, cd9660node *root)
1295 struct cd9660_children_head *head = &root->cn_children;
1298 TAILQ_FOREACH(cn, head, cn_next_child) {
1299 if ((cn->type & CD9660_TYPE_DIR) == 0)
1301 /* Recursion first */
1302 cd9660_add_dot_records(diskStructure, cn);
1304 cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOT, root);
1305 cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOTDOT,
1311 * Convert node to cd9660 structure
1312 * This function is designed to be called recursively on the root node of
1314 * Lots of recursion going on here, want to make sure it is efficient
1315 * @param struct fsnode * The root node to be converted
1316 * @param struct cd9660* The parent node (should not be NULL)
1317 * @param int Current directory depth
1318 * @param int* Running count of the number of directories that are being created
1321 cd9660_convert_structure(iso9660_disk *diskStructure, fsnode *root,
1322 cd9660node *parent_node, int level, int *numDirectories, int *error)
1324 fsnode *iterator = root;
1325 cd9660node *this_node;
1332 * Newer, more efficient method, reduces recursion depth
1335 warnx("%s: root is null", __func__);
1339 /* Test for an empty directory - makefs still gives us the . record */
1340 if ((S_ISDIR(root->type)) && (root->name[0] == '.')
1341 && (root->name[1] == '\0')) {
1346 if ((this_node = cd9660_allocate_cd9660node()) == NULL) {
1347 CD9660_MEM_ALLOC_ERROR(__func__);
1351 * To reduce the number of recursive calls, we will iterate over
1352 * the next pointers to the right.
1354 while (iterator != NULL) {
1357 * Increment the directory count if this is a directory
1358 * Ignore "." entries. We will generate them later
1360 if (!S_ISDIR(iterator->type) ||
1361 strcmp(iterator->name, ".") != 0) {
1363 /* Translate the node, including its filename */
1364 this_node->parent = parent_node;
1365 cd9660_translate_node(diskStructure, iterator,
1367 this_node->level = level;
1369 if (S_ISDIR(iterator->type)) {
1370 (*numDirectories)++;
1371 this_node->type = CD9660_TYPE_DIR;
1372 working_level = level + 1;
1375 * If at level 8, directory would be at 8
1376 * and have children at 9 which is not
1377 * allowed as per ISO spec
1380 if ((!diskStructure->allow_deep_trees) &&
1381 (!diskStructure->rock_ridge_enabled)) {
1382 warnx("error: found entry "
1383 "with depth greater "
1387 } else if (diskStructure->
1388 rock_ridge_enabled) {
1391 * Moved directory is actually
1396 if (cd9660_rrip_move_directory(
1398 this_node) == NULL) {
1410 /* Do the recursive call on the children */
1411 if (iterator->child != NULL) {
1412 cd9660_convert_structure(diskStructure,
1413 iterator->child, this_node,
1415 numDirectories, error);
1417 if ((*error) == 1) {
1418 warnx("%s: Error on recursive "
1425 /* Only directories should have children */
1426 assert(iterator->child == NULL);
1428 this_node->type = CD9660_TYPE_FILE;
1432 * Finally, do a sorted insert
1435 cd9660_sorted_child_insert(
1436 parent_node, this_node);
1439 /*Allocate new temp_node */
1440 if (iterator->next != NULL) {
1441 this_node = cd9660_allocate_cd9660node();
1442 if (this_node == NULL)
1443 CD9660_MEM_ALLOC_ERROR(__func__);
1446 iterator = iterator->next;
1449 /* cd9660_handle_collisions(first_node); */
1451 /* TODO: need cleanup */
1452 cd9660_copy_filenames(diskStructure, parent_node);
1455 flag = cd9660_handle_collisions(diskStructure, parent_node,
1458 cd9660_sorting_nodes(parent_node);
1459 } while ((flag == 1) && (counter < 100));
1463 * Clean up the cd9660node tree
1464 * This is designed to be called recursively on the root node
1465 * @param struct cd9660node *root The node to free
1469 cd9660_free_structure(cd9660node *root)
1473 while ((cn = TAILQ_FIRST(&root->cn_children)) != NULL) {
1474 TAILQ_REMOVE(&root->cn_children, cn, cn_next_child);
1475 cd9660_free_structure(cn);
1481 * Be a little more memory conservative:
1482 * instead of having the TAILQ_ENTRY as part of the cd9660node,
1483 * just create a temporary structure
1485 static struct ptq_entry
1487 TAILQ_ENTRY(ptq_entry) ptq;
1491 #define PTQUEUE_NEW(n,s,r,t){\
1492 n = emalloc(sizeof(struct s)); \
1497 * Generate the path tables
1498 * The specific implementation of this function is left as an exercise to the
1499 * programmer. It could be done recursively. Make sure you read how the path
1500 * table has to be laid out, it has levels.
1501 * @param struct iso9660_disk *disk The disk image
1502 * @returns int The number of built path tables (between 1 and 4), 0 on failure
1505 cd9660_generate_path_table(iso9660_disk *diskStructure)
1507 cd9660node *cn, *dirNode = diskStructure->rootNode;
1508 cd9660node *last = dirNode;
1509 int pathTableSize = 0; /* computed as we go */
1510 int counter = 1; /* root gets a count of 0 */
1512 TAILQ_HEAD(cd9660_pt_head, ptq_entry) pt_head;
1513 TAILQ_INIT(&pt_head);
1515 PTQUEUE_NEW(n, ptq_entry, -1, diskStructure->rootNode);
1517 /* Push the root node */
1518 TAILQ_INSERT_HEAD(&pt_head, n, ptq);
1520 /* Breadth-first traversal of file structure */
1521 while (pt_head.tqh_first != 0) {
1522 n = pt_head.tqh_first;
1524 TAILQ_REMOVE(&pt_head, pt_head.tqh_first, ptq);
1527 /* Update the size */
1528 pathTableSize += ISO_PATHTABLE_ENTRY_BASESIZE
1529 + dirNode->isoDirRecord->name_len[0]+
1530 (dirNode->isoDirRecord->name_len[0] % 2 == 0 ? 0 : 1);
1531 /* includes the padding bit */
1533 dirNode->ptnumber=counter;
1534 if (dirNode != last) {
1535 last->ptnext = dirNode;
1536 dirNode->ptprev = last;
1540 /* Push children onto queue */
1541 TAILQ_FOREACH(cn, &dirNode->cn_children, cn_next_child) {
1543 * Dont add the DOT and DOTDOT types to the path
1546 if ((cn->type != CD9660_TYPE_DOT)
1547 && (cn->type != CD9660_TYPE_DOTDOT)) {
1549 if (S_ISDIR(cn->node->type)) {
1550 PTQUEUE_NEW(n, ptq_entry, -1, cn);
1551 TAILQ_INSERT_TAIL(&pt_head, n, ptq);
1557 return pathTableSize;
1561 cd9660_compute_full_filename(cd9660node *node, char *buf)
1566 len = snprintf(buf, len, "%s/%s/%s", node->node->root,
1567 node->node->path, node->node->name);
1568 if (len >= PATH_MAX)
1569 errx(EXIT_FAILURE, "Pathname too long.");
1573 * TODO: These two functions are almost identical.
1574 * Some code cleanup is possible here
1576 * XXX bounds checking!
1579 cd9660_level1_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1580 char *newname, int is_file)
1584 * File Name shall not contain more than 8 d or d1 characters
1585 * File Name Extension shall not contain more than 3 d or d1 characters
1586 * Directory Identifier shall not contain more than 8 d or d1 characters
1592 while (*oldname != '\0' && extlen < 3) {
1593 /* Handle period first, as it is special */
1594 if (*oldname == '.') {
1604 /* cut RISC OS file type off ISO name */
1605 if (diskStructure->archimedes_enabled &&
1606 *oldname == ',' && strlen(oldname) == 4)
1609 /* Enforce 12.3 / 8 */
1610 if (namelen == 8 && !found_ext)
1613 if (islower((unsigned char)*oldname))
1614 *newname++ = toupper((unsigned char)*oldname);
1615 else if (isupper((unsigned char)*oldname)
1616 || isdigit((unsigned char)*oldname))
1617 *newname++ = *oldname;
1629 if (!found_ext && !diskStructure->omit_trailing_period)
1632 sprintf(newname, ";%i", 1);
1634 return namelen + extlen + found_ext;
1637 /* XXX bounds checking! */
1639 cd9660_level2_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1640 char *newname, int is_file)
1644 * File name : 0+ d or d1 characters
1646 * File name extension : 0+ d or d1 characters
1648 * File version number (5 characters, 1-32767)
1649 * 1 <= Sum of File name and File name extension <= 30
1655 while (*oldname != '\0' && namelen + extlen < 30) {
1656 /* Handle period first, as it is special */
1657 if (*oldname == '.') {
1659 if (diskStructure->allow_multidot) {
1671 /* cut RISC OS file type off ISO name */
1672 if (diskStructure->archimedes_enabled &&
1673 *oldname == ',' && strlen(oldname) == 4)
1676 if (islower((unsigned char)*oldname))
1677 *newname++ = toupper((unsigned char)*oldname);
1678 else if (isupper((unsigned char)*oldname) ||
1679 isdigit((unsigned char)*oldname))
1680 *newname++ = *oldname;
1681 else if (diskStructure->allow_multidot &&
1696 if (!found_ext && !diskStructure->omit_trailing_period)
1699 sprintf(newname, ";%i", 1);
1701 return namelen + extlen + found_ext;
1705 * Convert a file name to ISO compliant file name
1706 * @param char * oldname The original filename
1707 * @param char ** newname The new file name, in the appropriate character
1708 * set and of appropriate length
1709 * @param int 1 if file, 0 if directory
1710 * @returns int The length of the new string
1713 cd9660_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1714 char *newname, int is_file)
1716 assert(1 <= diskStructure->isoLevel && diskStructure->isoLevel <= 2);
1717 if (diskStructure->isoLevel == 1)
1718 return(cd9660_level1_convert_filename(diskStructure,
1719 oldname, newname, is_file));
1720 else if (diskStructure->isoLevel == 2)
1721 return (cd9660_level2_convert_filename(diskStructure,
1722 oldname, newname, is_file));
1727 cd9660_compute_record_size(iso9660_disk *diskStructure, cd9660node *node)
1729 int size = node->isoDirRecord->length[0];
1731 if (diskStructure->rock_ridge_enabled)
1732 size += node->susp_entry_size;
1733 size += node->su_tail_size;
1734 size += size & 1; /* Ensure length of record is even. */
1735 assert(size <= 254);
1740 cd9660_populate_dot_records(iso9660_disk *diskStructure, cd9660node *node)
1742 node->dot_record->fileDataSector = node->fileDataSector;
1743 memcpy(node->dot_record->isoDirRecord,node->isoDirRecord, 34);
1744 node->dot_record->isoDirRecord->name_len[0] = 1;
1745 node->dot_record->isoDirRecord->name[0] = 0;
1746 node->dot_record->isoDirRecord->name[1] = 0;
1747 node->dot_record->isoDirRecord->length[0] = 34;
1748 node->dot_record->fileRecordSize =
1749 cd9660_compute_record_size(diskStructure, node->dot_record);
1751 if (node == diskStructure->rootNode) {
1752 node->dot_dot_record->fileDataSector = node->fileDataSector;
1753 memcpy(node->dot_dot_record->isoDirRecord,node->isoDirRecord,
1756 node->dot_dot_record->fileDataSector =
1757 node->parent->fileDataSector;
1758 memcpy(node->dot_dot_record->isoDirRecord,
1759 node->parent->isoDirRecord,34);
1761 node->dot_dot_record->isoDirRecord->name_len[0] = 1;
1762 node->dot_dot_record->isoDirRecord->name[0] = 1;
1763 node->dot_dot_record->isoDirRecord->name[1] = 0;
1764 node->dot_dot_record->isoDirRecord->length[0] = 34;
1765 node->dot_dot_record->fileRecordSize =
1766 cd9660_compute_record_size(diskStructure, node->dot_dot_record);
1770 * @param struct cd9660node *node The node
1771 * @param int The offset (in bytes) - SHOULD align to the beginning of a sector
1772 * @returns int The total size of files and directory entries (should be
1773 * a multiple of sector size)
1776 cd9660_compute_offsets(iso9660_disk *diskStructure, cd9660node *node,
1777 int64_t startOffset)
1780 * This function needs to compute the size of directory records and
1781 * runs, file lengths, and set the appropriate variables both in
1782 * cd9660node and isoDirEntry
1784 int64_t used_bytes = 0;
1785 int64_t current_sector_usage = 0;
1790 assert(node != NULL);
1794 * NOTE : There needs to be some special case detection for
1795 * the "real root" node, since for it, node->node is undefined
1798 node->fileDataSector = -1;
1800 if (node->type & CD9660_TYPE_DIR) {
1801 node->fileRecordSize = cd9660_compute_record_size(
1802 diskStructure, node);
1803 /*Set what sector this directory starts in*/
1804 node->fileDataSector =
1805 CD9660_BLOCKS(diskStructure->sectorSize,startOffset);
1807 cd9660_bothendian_dword(node->fileDataSector,
1808 node->isoDirRecord->extent);
1811 * First loop over children, need to know the size of
1812 * their directory records
1814 node->fileSectorsUsed = 1;
1815 TAILQ_FOREACH(child, &node->cn_children, cn_next_child) {
1816 node->fileDataLength +=
1817 cd9660_compute_record_size(diskStructure, child);
1818 if ((cd9660_compute_record_size(diskStructure, child) +
1819 current_sector_usage) >=
1820 diskStructure->sectorSize) {
1821 current_sector_usage = 0;
1822 node->fileSectorsUsed++;
1825 current_sector_usage +=
1826 cd9660_compute_record_size(diskStructure, child);
1829 cd9660_bothendian_dword(node->fileSectorsUsed *
1830 diskStructure->sectorSize,node->isoDirRecord->size);
1833 * This should point to the sector after the directory
1834 * record (or, the first byte in that sector)
1836 used_bytes += node->fileSectorsUsed * diskStructure->sectorSize;
1838 for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child);
1839 child != NULL; child = TAILQ_NEXT(child, cn_next_child)) {
1840 /* Directories need recursive call */
1841 if (S_ISDIR(child->node->type)) {
1842 r = cd9660_compute_offsets(diskStructure, child,
1843 used_bytes + startOffset);
1852 /* Explicitly set the . and .. records */
1853 cd9660_populate_dot_records(diskStructure, node);
1855 /* Finally, do another iteration to write the file data*/
1856 for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child);
1858 child = TAILQ_NEXT(child, cn_next_child)) {
1859 /* Files need extent set */
1860 if (S_ISDIR(child->node->type))
1862 child->fileRecordSize =
1863 cd9660_compute_record_size(diskStructure, child);
1865 child->fileSectorsUsed =
1866 CD9660_BLOCKS(diskStructure->sectorSize,
1867 child->fileDataLength);
1869 inode = child->node->inode;
1870 if ((inode->flags & FI_ALLOCATED) == 0) {
1872 CD9660_BLOCKS(diskStructure->sectorSize,
1873 used_bytes + startOffset);
1874 inode->flags |= FI_ALLOCATED;
1875 used_bytes += child->fileSectorsUsed *
1876 diskStructure->sectorSize;
1878 INODE_WARNX(("%s: already allocated inode %d "
1879 "data sectors at %" PRIu32, __func__,
1880 (int)inode->st.st_ino, inode->ino));
1882 child->fileDataSector = inode->ino;
1883 cd9660_bothendian_dword(child->fileDataSector,
1884 child->isoDirRecord->extent);
1892 /* Might get rid of this func */
1894 cd9660_copy_stat_info(cd9660node *from, cd9660node *to, int file)
1896 to->node->inode->st.st_dev = 0;
1897 to->node->inode->st.st_ino = 0;
1898 to->node->inode->st.st_size = 0;
1899 to->node->inode->st.st_blksize = from->node->inode->st.st_blksize;
1900 to->node->inode->st.st_atime = from->node->inode->st.st_atime;
1901 to->node->inode->st.st_mtime = from->node->inode->st.st_mtime;
1902 to->node->inode->st.st_ctime = from->node->inode->st.st_ctime;
1903 to->node->inode->st.st_uid = from->node->inode->st.st_uid;
1904 to->node->inode->st.st_gid = from->node->inode->st.st_gid;
1905 to->node->inode->st.st_mode = from->node->inode->st.st_mode;
1906 /* Clear out type */
1907 to->node->inode->st.st_mode = to->node->inode->st.st_mode & ~(S_IFMT);
1909 to->node->inode->st.st_mode |= S_IFREG;
1911 to->node->inode->st.st_mode |= S_IFDIR;
1917 cd9660_create_virtual_entry(iso9660_disk *diskStructure, const char *name,
1918 cd9660node *parent, int file, int insert)
1923 assert(parent != NULL);
1925 temp = cd9660_allocate_cd9660node();
1929 tfsnode = emalloc(sizeof(*tfsnode));
1930 tfsnode->name = estrdup(name);
1931 temp->isoDirRecord = emalloc(sizeof(*temp->isoDirRecord));
1933 cd9660_convert_filename(diskStructure, tfsnode->name,
1934 temp->isoDirRecord->name, file);
1936 temp->node = tfsnode;
1937 temp->parent = parent;
1940 if (temp->parent != NULL) {
1941 temp->level = temp->parent->level + 1;
1942 if (!TAILQ_EMPTY(&temp->parent->cn_children))
1943 cd9660_sorted_child_insert(temp->parent, temp);
1945 TAILQ_INSERT_HEAD(&temp->parent->cn_children,
1946 temp, cn_next_child);
1950 if (parent->node != NULL) {
1951 tfsnode->type = parent->node->type;
1954 /* Clear out file type bits */
1955 tfsnode->type &= ~(S_IFMT);
1957 tfsnode->type |= S_IFREG;
1959 tfsnode->type |= S_IFDIR;
1961 /* Indicate that there is no spec entry (inode) */
1962 tfsnode->flags &= ~(FSNODE_F_HASSPEC);
1964 cd9660_copy_stat_info(parent, temp, file);
1970 cd9660_create_file(iso9660_disk *diskStructure, const char *name,
1971 cd9660node *parent, cd9660node *me)
1975 temp = cd9660_create_virtual_entry(diskStructure, name, parent, 1, 1);
1979 temp->fileDataLength = 0;
1981 temp->type = CD9660_TYPE_FILE | CD9660_TYPE_VIRTUAL;
1983 temp->node->inode = ecalloc(1, sizeof(*temp->node->inode));
1984 *temp->node->inode = *me->node->inode;
1986 if (cd9660_translate_node_common(diskStructure, temp) == 0)
1992 * Create a new directory which does not exist on disk
1993 * @param const char * name The name to assign to the directory
1994 * @param const char * parent Pointer to the parent directory
1995 * @returns cd9660node * Pointer to the new directory
1998 cd9660_create_directory(iso9660_disk *diskStructure, const char *name,
1999 cd9660node *parent, cd9660node *me)
2003 temp = cd9660_create_virtual_entry(diskStructure, name, parent, 0, 1);
2006 temp->node->type |= S_IFDIR;
2008 temp->type = CD9660_TYPE_DIR | CD9660_TYPE_VIRTUAL;
2010 temp->node->inode = ecalloc(1, sizeof(*temp->node->inode));
2011 *temp->node->inode = *me->node->inode;
2013 if (cd9660_translate_node_common(diskStructure, temp) == 0)
2019 cd9660_create_special_directory(iso9660_disk *diskStructure, u_char type,
2022 cd9660node *temp, *first;
2025 assert(parent != NULL);
2027 if (type == CD9660_TYPE_DOT)
2029 else if (type == CD9660_TYPE_DOTDOT)
2035 if ((temp = cd9660_create_virtual_entry(diskStructure, na, parent,
2039 temp->parent = parent;
2041 temp->isoDirRecord->length[0] = 34;
2042 /* Dot record is always first */
2043 if (type == CD9660_TYPE_DOT) {
2044 parent->dot_record = temp;
2045 TAILQ_INSERT_HEAD(&parent->cn_children, temp, cn_next_child);
2046 /* DotDot should be second */
2047 } else if (type == CD9660_TYPE_DOTDOT) {
2048 parent->dot_dot_record = temp;
2050 * If the first child is the dot record, insert
2051 * this second. Otherwise, insert it at the head.
2053 if ((first = TAILQ_FIRST(&parent->cn_children)) == NULL ||
2054 (first->type & CD9660_TYPE_DOT) == 0) {
2055 TAILQ_INSERT_HEAD(&parent->cn_children, temp,
2058 TAILQ_INSERT_AFTER(&parent->cn_children, first, temp,
2067 cd9660_add_generic_bootimage(iso9660_disk *diskStructure, const char *bootimage)
2071 assert(bootimage != NULL);
2073 if (*bootimage == '\0') {
2074 warnx("Error: Boot image must be a filename");
2078 diskStructure->generic_bootimage = estrdup(bootimage);
2080 /* Get information about the file */
2081 if (lstat(diskStructure->generic_bootimage, &stbuf) == -1)
2082 err(EXIT_FAILURE, "%s: lstat(\"%s\")", __func__,
2083 diskStructure->generic_bootimage);
2085 if (stbuf.st_size > 32768) {
2086 warnx("Error: Boot image must be no greater than 32768 bytes");
2090 if (diskStructure->verbose_level > 0) {
2091 printf("Generic boot image has size %lld\n",
2092 (long long)stbuf.st_size);
2095 diskStructure->has_generic_bootimage = 1;