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