]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/makefs/cd9660.c
Upgrade to OpenPAM Ximenia.
[FreeBSD/FreeBSD.git] / usr.sbin / makefs / cd9660.c
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/cdefs.h>
101 __FBSDID("$FreeBSD$");
102
103 #include <sys/param.h>
104 #include <sys/queue.h>
105 #include <ctype.h>
106 #include <stdlib.h>
107 #include <string.h>
108 #include <util.h>
109
110 #include "makefs.h"
111 #include "cd9660.h"
112 #include "cd9660/iso9660_rrip.h"
113 #include "cd9660/cd9660_archimedes.h"
114
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,
119     char, char *);
120 static void cd9660_populate_iso_dir_record(
121     struct _iso_directory_record_cd9660 *, u_char, u_char, u_char,
122     const char *);
123 static void cd9660_setup_root_node(iso9660_disk *);
124 static int cd9660_setup_volume_descriptors(iso9660_disk *);
125 #if 0
126 static int cd9660_fill_extended_attribute_record(cd9660node *);
127 #endif
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,
135     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 *);
141
142 static void cd9660_convert_structure(iso9660_disk *, fsnode *, cd9660node *, int,
143     int *, 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 *,
147     int);
148 static int cd9660_level2_convert_filename(iso9660_disk *, const char *, char *,
149     int);
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);
153 #if 0
154 static int cd9660_copy_stat_info(cd9660node *, cd9660node *, int);
155 #endif
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,
163     cd9660node *);
164 static int  cd9660_add_generic_bootimage(iso9660_disk *, const char *);
165
166
167 /*
168  * Allocate and initialize a cd9660node
169  * @returns struct cd9660node * Pointer to new node, or NULL on error
170  */
171 static cd9660node *
172 cd9660_allocate_cd9660node(void)
173 {
174         cd9660node *temp = ecalloc(1, sizeof(*temp));
175
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;
179         temp->node = NULL;
180         temp->isoDirRecord = NULL;
181         temp->isoExtAttributes = NULL;
182         temp->rr_real_parent = temp->rr_relocated = NULL;
183         temp->su_tail_data = NULL;
184         return temp;
185 }
186
187 /**
188 * Set default values for cd9660 extension to makefs
189 */
190 static void
191 cd9660_set_defaults(iso9660_disk *diskStructure)
192 {
193         /*Fix the sector size for now, though the spec allows for other sizes*/
194         diskStructure->sectorSize = 2048;
195
196         /* Set up defaults in our own structure */
197         diskStructure->verbose_level = 0;
198         diskStructure->keep_bad_images = 0;
199         diskStructure->isoLevel = 2;
200
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;
205
206         diskStructure->archimedes_enabled = 0;
207         diskStructure->chrp_boot = 0;
208
209         diskStructure->include_padding_areas = 1;
210
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;
219
220         /* Make sure the PVD is clear */
221         memset(&diskStructure->primaryDescriptor, 0, 2048);
222
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);
229
230         strcpy(diskStructure->primaryDescriptor.system_id, "FreeBSD");
231
232         /* Boot support: Initially disabled */
233         diskStructure->has_generic_bootimage = 0;
234         diskStructure->generic_bootimage = NULL;
235
236         diskStructure->boot_image_directory = 0;
237         /*memset(diskStructure->boot_descriptor, 0, 2048);*/
238
239         diskStructure->is_bootable = 0;
240         TAILQ_INIT(&diskStructure->boot_images);
241         LIST_INIT(&diskStructure->boot_entries);
242 }
243
244 void
245 cd9660_prep_opts(fsinfo_t *fsopts)
246 {
247         iso9660_disk *diskStructure = ecalloc(1, sizeof(*diskStructure));
248
249 #define OPT_STR(letter, name, desc) \
250         { letter, name, NULL, OPT_STRBUF, 0, 0, desc }
251
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)), \
257           min, max, desc }
258
259 #define OPT_BOOL(letter, name, field, desc) \
260         OPT_NUM(letter, name, field, 0, 1, desc)
261
262         const option_t cd9660_options[] = {
263                 OPT_NUM('l', "isolevel", isoLevel,
264                     1, 2, "ISO Level"),
265                 OPT_NUM('v', "verbose", verbose_level,
266                     0, 2, "Turns on verbose output"),
267
268                 OPT_BOOL('R', "rockridge", rock_ridge_enabled,
269                     "Enable Rock-Ridge extensions"),
270                 OPT_BOOL('C', "chrp-boot", chrp_boot,
271                     "Enable CHRP boot"),
272                 OPT_BOOL('K', "keep-bad-images", keep_bad_images,
273                     "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"),
290
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"),
304
305                 { .name = NULL }
306         };
307
308         fsopts->fs_specific = diskStructure;
309         fsopts->fs_options = copy_opts(cd9660_options);
310
311         cd9660_set_defaults(diskStructure);
312 }
313
314 void
315 cd9660_cleanup_opts(fsinfo_t *fsopts)
316 {
317         free(fsopts->fs_specific);
318         free(fsopts->fs_options);
319 }
320
321 static int
322 cd9660_arguments_set_string(const char *val, const char *fieldtitle,
323     size_t length, char testmode, char *dest)
324 {
325         size_t len;
326         int test;
327
328         if (val == NULL)
329                 warnx("error: '%s' requires a string argument", fieldtitle);
330         else if ((len = strlen(val)) <= length) {
331                 if (testmode == 'd')
332                         test = cd9660_valid_d_chars(val);
333                 else
334                         test = cd9660_valid_a_chars(val);
335                 if (test) {
336                         memcpy(dest, val, len);
337                         if (test == 2)
338                                 cd9660_uppercase_characters(dest, len);
339                         return 1;
340                 } else
341                         warnx("error: '%s' must be composed of %c-characters",
342                             fieldtitle, testmode);
343         } else
344                 warnx("error: '%s' must be at most 32 characters long",
345                     fieldtitle);
346         return 0;
347 }
348
349 /*
350  * Command-line parsing function
351  */
352
353 int
354 cd9660_parse_opts(const char *option, fsinfo_t *fsopts)
355 {
356         int     rv, i;
357         iso9660_disk *diskStructure = fsopts->fs_specific;
358         option_t *cd9660_options = fsopts->fs_options;
359         char buf[1024];
360         const char *name, *desc;
361
362         assert(option != NULL);
363
364         if (debug & DEBUG_FS_PARSE_OPTS)
365                 printf("%s: got `%s'\n", __func__, option);
366
367         i = set_option(cd9660_options, option, buf, sizeof(buf));
368         if (i == -1)
369                 return 0;
370
371         if (cd9660_options[i].name == NULL)
372                 abort();
373
374         name = cd9660_options[i].name;
375         desc = cd9660_options[i].desc;
376         switch (cd9660_options[i].letter) {
377         case 'h':
378         case 'S':
379                 rv = 0; /* this is not handled yet */
380                 break;
381         case 'L':
382                 rv = cd9660_arguments_set_string(buf, desc, 32, 'd',
383                     diskStructure->primaryDescriptor.volume_id);
384                 break;
385         case 'A':
386                 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
387                     diskStructure->primaryDescriptor.application_id);
388                 break;
389         case 'P':
390                 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
391                     diskStructure->primaryDescriptor.publisher_id);
392                 break;
393         case 'p':
394                 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
395                     diskStructure->primaryDescriptor.preparer_id);
396                 break;
397         case 'V':
398                 rv = cd9660_arguments_set_string(buf, desc, 128, 'a',
399                     diskStructure->primaryDescriptor.volume_set_id);
400                 break;
401         /* Boot options */
402         case 'B':
403                 if (buf[0] == '\0') {
404                         warnx("The Boot Image parameter requires a valid boot"
405                             "information string");
406                         rv = 0;
407                 } else
408                         rv = cd9660_add_boot_disk(diskStructure, buf);
409                 break;
410         case 'G':
411                 if (buf[0] == '\0') {
412                         warnx("The Generic Boot Image parameter requires a"
413                             " valid boot information string");
414                         rv = 0;
415                 } else
416                         rv = cd9660_add_generic_bootimage(diskStructure, buf);
417                 break;
418         default:
419                 if (strcmp(name, "bootimagedir") == 0) {
420                         /*
421                          * XXXfvdl this is unused.
422                          */
423                         if (buf[0] == '\0') {
424                                 warnx("The Boot Image Directory parameter"
425                                     " requires a directory name");
426                                 rv = 0;
427                         } else {
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);
433                         }
434                 } else if (strcmp(name, "no-emul-boot") == 0 ||
435                     strcmp(name, "no-boot") == 0 ||
436                     strcmp(name, "hard-disk-boot") == 0) {
437                         /* RRIP */
438                         cd9660_eltorito_add_boot_option(diskStructure, name, 0);
439                         rv = 1;
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",
444                                     name);
445                                 rv = 0;
446                         } else {
447                                 cd9660_eltorito_add_boot_option(diskStructure,
448                                     name, buf);
449                                 rv = 1;
450                         }
451                 } else
452                         rv = 1;
453         }
454         return rv;
455 }
456
457 /*
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
464  */
465 void
466 cd9660_makefs(const char *image, const char *dir, fsnode *root,
467     fsinfo_t *fsopts)
468 {
469         int64_t startoffset;
470         int numDirectories;
471         uint64_t pathTableSectors;
472         int64_t firstAvailableSector;
473         int64_t totalSpace;
474         int error;
475         cd9660node *real_root;
476         iso9660_disk *diskStructure = fsopts->fs_specific;
477
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");
484
485         assert(image != NULL);
486         assert(dir != NULL);
487         assert(root != NULL);
488
489         if (diskStructure->verbose_level > 0)
490                 printf("%s: image %s directory %s root %p\n", __func__,
491                     image, dir, root);
492
493         /* Set up some constants. Later, these will be defined with options */
494
495         /* Counter needed for path tables */
496         numDirectories = 0;
497
498         /* Convert tree to our own format */
499         /* Actually, we now need to add the REAL root node, at level 0 */
500
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);
506
507         real_root->level = 0;
508         diskStructure->rootNode = real_root;
509         real_root->type = CD9660_TYPE_DIR;
510         error = 0;
511         real_root->node = root;
512         cd9660_convert_structure(diskStructure, root, real_root, 1,
513             &numDirectories, &error);
514
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__);
520         } else {
521                 if (diskStructure->verbose_level > 0)
522                         printf("%s: tree converted\n", __func__);
523         }
524
525         /* Add the dot and dot dot records */
526         cd9660_add_dot_records(diskStructure, real_root);
527
528         cd9660_setup_root_node(diskStructure);
529
530         if (diskStructure->verbose_level > 0)
531                 printf("%s: done converting tree\n", __func__);
532
533         /* non-SUSP extensions */
534         if (diskStructure->archimedes_enabled)
535                 archimedes_convert_tree(diskStructure->rootNode);
536
537         /* Rock ridge / SUSP init pass */
538         if (diskStructure->rock_ridge_enabled) {
539                 cd9660_susp_initialize(diskStructure, diskStructure->rootNode,
540                     diskStructure->rootNode, NULL);
541         }
542
543         /* Build path table structure */
544         diskStructure->pathTableLength = cd9660_generate_path_table(
545             diskStructure);
546
547         pathTableSectors = CD9660_BLOCKS(diskStructure->sectorSize,
548                 diskStructure->pathTableLength);
549
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");
556         }
557         /* LE first, then BE */
558         diskStructure->primaryLittleEndianTableSector = firstAvailableSector;
559         diskStructure->primaryBigEndianTableSector =
560                 diskStructure->primaryLittleEndianTableSector + pathTableSectors;
561
562         /* Set the secondary ones to -1, not going to use them for now */
563         diskStructure->secondaryBigEndianTableSector = -1;
564         diskStructure->secondaryLittleEndianTableSector = -1;
565
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",
571                     __func__,
572                     diskStructure->pathTableLength, pathTableSectors);
573
574         startoffset = diskStructure->sectorSize*diskStructure->dataFirstSector;
575
576         totalSpace = cd9660_compute_offsets(diskStructure, real_root, startoffset);
577
578         diskStructure->totalSectors = diskStructure->dataFirstSector +
579                 CD9660_BLOCKS(diskStructure->sectorSize, totalSpace);
580
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);
589         }
590
591
592         cd9660_finalize_PVD(diskStructure);
593
594         /* Add padding sectors, just for testing purposes right now */
595         /* diskStructure->totalSectors+=150; */
596
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);
607         }
608
609         /*
610          * Add padding sectors at the end
611          * TODO: Clean this up and separate padding
612          */
613         if (diskStructure->include_padding_areas)
614                 diskStructure->totalSectors += 150;
615
616         cd9660_write_image(diskStructure, image);
617
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);
622         }
623
624         /* Clean up data structures */
625         cd9660_free_structure(real_root);
626
627         if (diskStructure->verbose_level > 0)
628                 printf("%s: done\n", __func__);
629 }
630
631 /* Generic function pointer - implement later */
632 typedef int (*cd9660node_func)(cd9660node *);
633
634 static void
635 cd9660_finalize_PVD(iso9660_disk *diskStructure)
636 {
637         time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL);
638
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);
642
643         /* In RRIP, this might be longer than 34 */
644         diskStructure->primaryDescriptor.root_directory_record[0] = 34;
645
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,
652             (unsigned char *)
653                 diskStructure->primaryDescriptor.volume_sequence_number);
654         cd9660_bothendian_word(diskStructure->sectorSize,
655             (unsigned char *)
656                 diskStructure->primaryDescriptor.logical_block_size);
657         cd9660_bothendian_dword(diskStructure->pathTableLength,
658             (unsigned char *)diskStructure->primaryDescriptor.path_table_size);
659
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);
664
665         diskStructure->primaryDescriptor.file_structure_version[0] = 1;
666
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,
671             128);
672         cd9660_pad_string_spaces(diskStructure->primaryDescriptor.publisher_id,
673             128);
674         cd9660_pad_string_spaces(diskStructure->primaryDescriptor.preparer_id,
675             128);
676         cd9660_pad_string_spaces(diskStructure->primaryDescriptor.application_id,
677             128);
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);
684
685         /* Setup dates */
686         cd9660_time_8426(
687             (unsigned char *)diskStructure->primaryDescriptor.creation_date,
688             tstamp);
689         cd9660_time_8426(
690             (unsigned char *)diskStructure->primaryDescriptor.modification_date,
691             tstamp);
692
693 #if 0
694         cd9660_set_date(diskStructure->primaryDescriptor.expiration_date,
695             tstamp);
696 #endif
697
698         memset(diskStructure->primaryDescriptor.expiration_date, '0', 16);
699         diskStructure->primaryDescriptor.expiration_date[16] = 0;
700
701         cd9660_time_8426(
702             (unsigned char *)diskStructure->primaryDescriptor.effective_date,
703             tstamp);
704         /* make this sane */
705         cd9660_time_915(diskStructure->rootNode->dot_record->isoDirRecord->date,
706             tstamp);
707 }
708
709 static void
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)
713 {
714         time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL);
715
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;
726
727         /* Todo : better rounding */
728         record->length[0] += (record->length[0] & 1) ? 1 : 0;
729 }
730
731 static void
732 cd9660_setup_root_node(iso9660_disk *diskStructure)
733 {
734         cd9660_populate_iso_dir_record(diskStructure->rootNode->isoDirRecord,
735             0, ISO_FLAG_DIRECTORY, 1, "\0");
736
737 }
738
739 /*********** SUPPORT FUNCTIONS ***********/
740 static int
741 cd9660_setup_volume_descriptors(iso9660_disk *diskStructure)
742 {
743         /* Boot volume descriptor should come second */
744         int sector = 16;
745         /* For now, a fixed 2 : PVD and terminator */
746         volume_descriptor *temp, *t;
747
748         /* Set up the PVD */
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;
758
759         sector++;
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);
764                 temp->next = t;
765                 temp = t;
766                 t->sector = 17;
767                 if (diskStructure->verbose_level > 0)
768                         printf("Setting up boot volume descriptor\n");
769                 cd9660_setup_boot_volume_descriptor(diskStructure, t);
770                 sector++;
771         }
772
773         /* Set up the terminator */
774         t = emalloc(sizeof(*t));
775         t->volumeDescriptorData = ecalloc(1, 2048);
776         temp->next = t;
777         t->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_TERMINATOR;
778         t->next = NULL;
779         t->volumeDescriptorData[6] = 1;
780         t->sector = sector;
781         memcpy(t->volumeDescriptorData + 1,
782             ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5);
783
784         sector++;
785         return sector;
786 }
787
788 #if 0
789 /*
790  * Populate EAR at some point. Not required, but is used by NetBSD's
791  * cd9660 support
792  */
793 static int
794 cd9660_fill_extended_attribute_record(cd9660node *node)
795 {
796         node->isoExtAttributes = emalloc(sizeof(*node->isoExtAttributes));
797         return 1;
798 }
799 #endif
800
801 static int
802 cd9660_translate_node_common(iso9660_disk *diskStructure, cd9660node *newnode)
803 {
804         u_char flag;
805         char temp[ISO_FILENAME_MAXLENGTH_WITH_PADDING];
806
807         /* Now populate the isoDirRecord structure */
808         memset(temp, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING);
809
810         (void)cd9660_convert_filename(diskStructure, newnode->node->name,
811             temp, !(S_ISDIR(newnode->node->type)));
812
813         flag = ISO_FLAG_CLEAR;
814         if (S_ISDIR(newnode->node->type))
815                 flag |= ISO_FLAG_DIRECTORY;
816
817         cd9660_populate_iso_dir_record(newnode->isoDirRecord, 0,
818             flag, strlen(temp), temp);
819
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;
825
826         return 1;
827 }
828
829 /*
830  * Translate fsnode to cd9660node
831  * Translate filenames and other metadata, including dates, sizes,
832  * permissions, etc
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
836  */
837 static int
838 cd9660_translate_node(iso9660_disk *diskStructure, fsnode *node,
839     cd9660node *newnode)
840 {
841         if (node == NULL) {
842                 if (diskStructure->verbose_level > 0)
843                         printf("%s: NULL node passed, returning\n", __func__);
844                 return 0;
845         }
846         newnode->isoDirRecord = emalloc(sizeof(*newnode->isoDirRecord));
847         /* Set the node pointer */
848         newnode->node = node;
849
850         /* Set the size */
851         if (!(S_ISDIR(node->type)))
852                 newnode->fileDataLength = node->inode->st.st_size;
853
854         if (cd9660_translate_node_common(diskStructure, newnode) == 0)
855                 return 0;
856
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);
860
861         return 1;
862 }
863
864 /*
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
870  */
871 static int
872 cd9660_compare_filename(const char *first, const char *second)
873 {
874         /*
875          * This can be made more optimal once it has been tested
876          * (the extra character, for example, is for testing)
877          */
878
879         int p1 = 0;
880         int p2 = 0;
881         char c1, c2;
882         /* First, on the filename */
883
884         while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1
885                 && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1) {
886                 c1 = first[p1];
887                 c2 = second[p2];
888                 if (c1 == '.' && c2 =='.')
889                         break;
890                 else if (c1 == '.') {
891                         p2++;
892                         c1 = ' ';
893                 } else if (c2 == '.') {
894                         p1++;
895                         c2 = ' ';
896                 } else {
897                         p1++;
898                         p2++;
899                 }
900
901                 if (c1 < c2)
902                         return -1;
903                 else if (c1 > c2) {
904                         return 1;
905                 }
906         }
907
908         if (first[p1] == '.' && second[p2] == '.') {
909                 p1++;
910                 p2++;
911                 while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1
912                         && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1) {
913                         c1 = first[p1];
914                         c2 = second[p2];
915                         if (c1 == ';' && c2 == ';')
916                                 break;
917                         else if (c1 == ';') {
918                                 p2++;
919                                 c1 = ' ';
920                         } else if (c2 == ';') {
921                                 p1++;
922                                 c2 = ' ';
923                         } else {
924                                 p1++;
925                                 p2++;
926                         }
927
928                         if (c1 < c2)
929                                 return -1;
930                         else if (c1 > c2)
931                                 return 1;
932                 }
933         }
934         return 0;
935 }
936
937 /*
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
941  */
942 static void
943 cd9660_sorted_child_insert(cd9660node *parent, cd9660node *cn_new)
944 {
945         int compare;
946         cd9660node *cn;
947         struct cd9660_children_head *head = &parent->cn_children;
948
949         /* TODO: Optimize? */
950         cn_new->parent = parent;
951
952         /*
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
956          */
957
958         TAILQ_FOREACH(cn, head, cn_next_child) {
959                 /*
960                  * Dont insert a node twice -
961                  * that would cause an infinite loop
962                  */
963                 if (cn_new == cn)
964                         return;
965
966                 compare = cd9660_compare_filename(cn_new->isoDirRecord->name,
967                         cn->isoDirRecord->name);
968
969                 if (compare == 0)
970                         compare = cd9660_compare_filename(cn_new->node->name,
971                                 cn->node->name);
972
973                 if (compare < 0)
974                         break;
975         }
976         if (cn == NULL)
977                 TAILQ_INSERT_TAIL(head, cn_new, cn_next_child);
978         else
979                 TAILQ_INSERT_BEFORE(cn, cn_new, cn_next_child);
980 }
981
982 /*
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
986  */
987 static int
988 cd9660_handle_collisions(iso9660_disk *diskStructure, cd9660node *colliding,
989     int past)
990 {
991         cd9660node *iter, *next, *prev;
992         int skip;
993         int delete_chars = 0;
994         int temp_past = past;
995         int temp_skip;
996         int flag = 0;
997         cd9660node *end_of_range;
998
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);
1004                         continue;
1005                 }
1006                 flag = 1;
1007                 temp_skip = skip = cd9660_count_collisions(iter);
1008                 end_of_range = iter;
1009                 while (temp_skip > 0) {
1010                         temp_skip--;
1011                         end_of_range = TAILQ_NEXT(end_of_range, cn_next_child);
1012                 }
1013                 temp_past = past;
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)
1018                                 iter = prev;
1019                         else
1020                                 delete_chars++;
1021                         temp_past--;
1022                 }
1023                 skip += past;
1024                 iter = cd9660_rename_filename(diskStructure, iter, skip,
1025                     delete_chars);
1026         }
1027         return flag;
1028 }
1029
1030
1031 static cd9660node *
1032 cd9660_rename_filename(iso9660_disk *diskStructure, cd9660node *iter, int num,
1033     int delete_chars)
1034 {
1035         int i = 0;
1036         int numbts, digit, digits, temp, powers, count;
1037         char *naming;
1038         int maxlength;
1039         char *tmp;
1040
1041         if (diskStructure->verbose_level > 0)
1042                 printf("Rename_filename called\n");
1043
1044         assert(1 <= diskStructure->isoLevel && diskStructure->isoLevel <= 2);
1045         /* TODO : A LOT of chanes regarding 8.3 filenames */
1046         if (diskStructure->isoLevel == 1)
1047                 maxlength = 8;
1048         else if (diskStructure->isoLevel == 2)
1049                 maxlength = 31;
1050         else
1051                 maxlength = ISO_FILENAME_MAXLENGTH_BEFORE_VERSION;
1052
1053         tmp = emalloc(ISO_FILENAME_MAXLENGTH_WITH_PADDING);
1054
1055         while (i < num && iter) {
1056                 powers = 1;
1057                 count = 0;
1058                 digits = 1;
1059                 while (((int)(i / powers) ) >= 10) {
1060                         digits++;
1061                         powers = powers * 10;
1062                 }
1063
1064                 naming = iter->o_name;
1065
1066                 /*
1067                 while ((*naming != '.') && (*naming != ';')) {
1068                         naming++;
1069                         count++;
1070                 }
1071                 */
1072
1073                 while (count < maxlength) {
1074                         if (*naming == ';')
1075                                 break;
1076                         naming++;
1077                         count++;
1078                 }
1079
1080                 if ((count + digits) < maxlength)
1081                         numbts = count;
1082                 else
1083                         numbts = maxlength - (digits);
1084                 numbts -= delete_chars;
1085
1086                 /* 8.3 rules - keep the extension, add before the dot */
1087
1088                 /*
1089                  * This code makes a bunch of assumptions.
1090                  * See if you can spot them all :)
1091                  */
1092
1093 #if 0
1094                 if (diskStructure->isoLevel == 1) {
1095                         numbts = 8 - digits - delete_chars;
1096                         if (dot < 0) {
1097
1098                         } else {
1099                                 if (dot < 8) {
1100                                         memmove(&tmp[numbts],&tmp[dot],4);
1101                                 }
1102                         }
1103                 }
1104 #endif
1105
1106                 /* (copying just the filename before the '.' */
1107                 memcpy(tmp, (iter->o_name), numbts);
1108
1109                 /* adding the appropriate number following the name */
1110                 temp = i;
1111                 while (digits > 0) {
1112                         digit = (int)(temp / powers);
1113                         temp = temp - digit * powers;
1114                         sprintf(&tmp[numbts] , "%d", digit);
1115                         digits--;
1116                         numbts++;
1117                         powers = powers / 10;
1118                 }
1119
1120                 while ((*naming != ';')  && (numbts < maxlength)) {
1121                         tmp[numbts] = (*naming);
1122                         naming++;
1123                         numbts++;
1124                 }
1125
1126                 tmp[numbts] = ';';
1127                 tmp[numbts+1] = '1';
1128                 tmp[numbts+2] = '\0';
1129
1130                 /*
1131                  * now tmp has exactly the identifier
1132                  * we want so we'll copy it back to record
1133                  */
1134                 memcpy((iter->isoDirRecord->name), tmp, numbts + 3);
1135
1136                 iter = TAILQ_NEXT(iter, cn_next_child);
1137                 i++;
1138         }
1139
1140         free(tmp);
1141         return iter;
1142 }
1143
1144 /* Todo: Figure out why these functions are nec. */
1145 static void
1146 cd9660_copy_filenames(iso9660_disk *diskStructure, cd9660node *node)
1147 {
1148         cd9660node *cn;
1149
1150         if (TAILQ_EMPTY(&node->cn_children))
1151                 return;
1152
1153         if (TAILQ_FIRST(&node->cn_children)->isoDirRecord == NULL) {
1154                 debug_print_tree(diskStructure, diskStructure->rootNode, 0);
1155                 exit(1);
1156         }
1157
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);
1162         }
1163 }
1164
1165 static void
1166 cd9660_sorting_nodes(cd9660node *node)
1167 {
1168         cd9660node *cn;
1169
1170         TAILQ_FOREACH(cn, &node->cn_children, cn_next_child)
1171                 cd9660_sorting_nodes(cn);
1172         cd9660_sort_nodes(node);
1173 }
1174
1175 /* XXX Bubble sort. */
1176 static void
1177 cd9660_sort_nodes(cd9660node *node)
1178 {
1179         cd9660node *cn, *next;
1180
1181         do {
1182                 TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) {
1183                         if ((next = TAILQ_NEXT(cn, cn_next_child)) == NULL)
1184                                 return;
1185                         else if (strcmp(next->isoDirRecord->name,
1186                                         cn->isoDirRecord->name) >= 0)
1187                                 continue;
1188                         TAILQ_REMOVE(&node->cn_children, next, cn_next_child);
1189                         TAILQ_INSERT_BEFORE(cn, next, cn_next_child);
1190                         break;
1191                 }
1192         } while (cn != NULL);
1193 }
1194
1195 static int
1196 cd9660_count_collisions(cd9660node *copy)
1197 {
1198         int count = 0;
1199         cd9660node *iter, *next;
1200
1201         for (iter = copy;
1202              (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;
1203              iter = next) {
1204                 if (cd9660_compare_filename(iter->isoDirRecord->name,
1205                         next->isoDirRecord->name) == 0)
1206                         count++;
1207                 else
1208                         return count;
1209         }
1210 #if 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);
1215                 if (compare == 0) {
1216                         count++;
1217                         return cd9660_recurse_on_collision(next, count);
1218                 } else
1219                         return count;
1220         }
1221 #endif
1222         return count;
1223 }
1224
1225 static cd9660node *
1226 cd9660_rrip_move_directory(iso9660_disk *diskStructure, cd9660node *dir)
1227 {
1228         char newname[9];
1229         cd9660node *tfile;
1230
1231         /*
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)
1238          */
1239
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)
1246                         return 0;
1247                 cd9660_time_915(diskStructure->rr_moved_dir->isoDirRecord->date,
1248                     stampst.st_ino ? stampst.st_mtime : start_time.tv_sec);
1249         }
1250
1251         /* Create a file with the same ORIGINAL name */
1252         tfile = cd9660_create_file(diskStructure, dir->node->name, dir->parent,
1253             dir);
1254         if (tfile == NULL)
1255                 return NULL;
1256
1257         diskStructure->rock_ridge_move_count++;
1258         snprintf(newname, sizeof(newname), "%08u",
1259             diskStructure->rock_ridge_move_count);
1260
1261         /* Point to old parent */
1262         dir->rr_real_parent = dir->parent;
1263
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,
1267                     cn_next_child);
1268         } else {
1269                 cd9660_sorted_child_insert(dir->rr_real_parent, tfile);
1270         }
1271
1272         /* Point to new parent */
1273         dir->parent = diskStructure->rr_moved_dir;
1274
1275         /* Point the file to the moved directory */
1276         tfile->rr_relocated = dir;
1277
1278         /* Actually move the directory */
1279         cd9660_sorted_child_insert(diskStructure->rr_moved_dir, dir);
1280
1281         /* TODO: Inherit permissions / ownership (basically the entire inode) */
1282
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;
1288
1289         return dir;
1290 }
1291
1292 static int
1293 cd9660_add_dot_records(iso9660_disk *diskStructure, cd9660node *root)
1294 {
1295         struct cd9660_children_head *head = &root->cn_children;
1296         cd9660node *cn;
1297
1298         TAILQ_FOREACH(cn, head, cn_next_child) {
1299                 if ((cn->type & CD9660_TYPE_DIR) == 0)
1300                         continue;
1301                 /* Recursion first */
1302                 cd9660_add_dot_records(diskStructure, cn);
1303         }
1304         cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOT, root);
1305         cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOTDOT,
1306             root);
1307         return 1;
1308 }
1309
1310 /*
1311  * Convert node to cd9660 structure
1312  * This function is designed to be called recursively on the root node of
1313  * the filesystem
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
1319  */
1320 static void
1321 cd9660_convert_structure(iso9660_disk *diskStructure, fsnode *root,
1322     cd9660node *parent_node, int level, int *numDirectories, int *error)
1323 {
1324         fsnode *iterator = root;
1325         cd9660node *this_node;
1326         int working_level;
1327         int add;
1328         int flag = 0;
1329         int counter = 0;
1330
1331         /*
1332          * Newer, more efficient method, reduces recursion depth
1333          */
1334         if (root == NULL) {
1335                 warnx("%s: root is null", __func__);
1336                 return;
1337         }
1338
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')) {
1342                 root = root->next;
1343                 if (root == NULL)
1344                         return;
1345         }
1346         if ((this_node = cd9660_allocate_cd9660node()) == NULL) {
1347                 CD9660_MEM_ALLOC_ERROR(__func__);
1348         }
1349
1350         /*
1351          * To reduce the number of recursive calls, we will iterate over
1352          * the next pointers to the right.
1353          */
1354         while (iterator != NULL) {
1355                 add = 1;
1356                 /*
1357                  * Increment the directory count if this is a directory
1358                  * Ignore "." entries. We will generate them later
1359                  */
1360                 if (!S_ISDIR(iterator->type) ||
1361                     strcmp(iterator->name, ".") != 0) {
1362
1363                         /* Translate the node, including its filename */
1364                         this_node->parent = parent_node;
1365                         cd9660_translate_node(diskStructure, iterator,
1366                             this_node);
1367                         this_node->level = level;
1368
1369                         if (S_ISDIR(iterator->type)) {
1370                                 (*numDirectories)++;
1371                                 this_node->type = CD9660_TYPE_DIR;
1372                                 working_level = level + 1;
1373
1374                                 /*
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
1378                                  */
1379                                 if (level == 8) {
1380                                         if ((!diskStructure->allow_deep_trees) &&
1381                                           (!diskStructure->rock_ridge_enabled)) {
1382                                                 warnx("error: found entry "
1383                                                      "with depth greater "
1384                                                      "than 8.");
1385                                                 (*error) = 1;
1386                                                 return;
1387                                         } else if (diskStructure->
1388                                                    rock_ridge_enabled) {
1389                                                 working_level = 3;
1390                                                 /*
1391                                                  * Moved directory is actually
1392                                                  * at level 2.
1393                                                  */
1394                                                 this_node->level =
1395                                                     working_level - 1;
1396                                                 if (cd9660_rrip_move_directory(
1397                                                         diskStructure,
1398                                                         this_node) == NULL) {
1399                                                         warnx("Failure in "
1400                                                               "cd9660_rrip_"
1401                                                               "move_directory"
1402                                                         );
1403                                                         (*error) = 1;
1404                                                         return;
1405                                                 }
1406                                                 add = 0;
1407                                         }
1408                                 }
1409
1410                                 /* Do the recursive call on the children */
1411                                 if (iterator->child != NULL) {
1412                                         cd9660_convert_structure(diskStructure,
1413                                                 iterator->child, this_node,
1414                                                 working_level,
1415                                                 numDirectories, error);
1416
1417                                         if ((*error) == 1) {
1418                                                 warnx("%s: Error on recursive "
1419                                                     "call", __func__);
1420                                                 return;
1421                                         }
1422                                 }
1423
1424                         } else {
1425                                 /* Only directories should have children */
1426                                 assert(iterator->child == NULL);
1427
1428                                 this_node->type = CD9660_TYPE_FILE;
1429                         }
1430
1431                         /*
1432                          * Finally, do a sorted insert
1433                          */
1434                         if (add) {
1435                                 cd9660_sorted_child_insert(
1436                                     parent_node, this_node);
1437                         }
1438
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__);
1444                         }
1445                 }
1446                 iterator = iterator->next;
1447         }
1448
1449         /* cd9660_handle_collisions(first_node); */
1450
1451         /* TODO: need cleanup */
1452         cd9660_copy_filenames(diskStructure, parent_node);
1453
1454         do {
1455                 flag = cd9660_handle_collisions(diskStructure, parent_node,
1456                     counter);
1457                 counter++;
1458                 cd9660_sorting_nodes(parent_node);
1459         } while ((flag == 1) && (counter < 100));
1460 }
1461
1462 /*
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
1466  * @returns void
1467  */
1468 static void
1469 cd9660_free_structure(cd9660node *root)
1470 {
1471         cd9660node *cn;
1472
1473         while ((cn = TAILQ_FIRST(&root->cn_children)) != NULL) {
1474                 TAILQ_REMOVE(&root->cn_children, cn, cn_next_child);
1475                 cd9660_free_structure(cn);
1476         }
1477         free(root);
1478 }
1479
1480 /*
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
1484  */
1485 static struct ptq_entry
1486 {
1487         TAILQ_ENTRY(ptq_entry) ptq;
1488         cd9660node *node;
1489 } *n;
1490
1491 #define PTQUEUE_NEW(n,s,r,t){\
1492         n = emalloc(sizeof(struct s));  \
1493         n->node = t;\
1494 }
1495
1496 /*
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
1503  */
1504 static int
1505 cd9660_generate_path_table(iso9660_disk *diskStructure)
1506 {
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 */
1511
1512         TAILQ_HEAD(cd9660_pt_head, ptq_entry) pt_head;
1513         TAILQ_INIT(&pt_head);
1514
1515         PTQUEUE_NEW(n, ptq_entry, -1, diskStructure->rootNode);
1516
1517         /* Push the root node */
1518         TAILQ_INSERT_HEAD(&pt_head, n, ptq);
1519
1520         /* Breadth-first traversal of file structure */
1521         while (pt_head.tqh_first != 0) {
1522                 n = pt_head.tqh_first;
1523                 dirNode = n->node;
1524                 TAILQ_REMOVE(&pt_head, pt_head.tqh_first, ptq);
1525                 free(n);
1526
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 */
1532
1533                 dirNode->ptnumber=counter;
1534                 if (dirNode != last) {
1535                         last->ptnext = dirNode;
1536                         dirNode->ptprev = last;
1537                 }
1538                 last = dirNode;
1539
1540                 /* Push children onto queue */
1541                 TAILQ_FOREACH(cn, &dirNode->cn_children, cn_next_child) {
1542                         /*
1543                          * Dont add the DOT and DOTDOT types to the path
1544                          * table.
1545                          */
1546                         if ((cn->type != CD9660_TYPE_DOT)
1547                                 && (cn->type != CD9660_TYPE_DOTDOT)) {
1548
1549                                 if (S_ISDIR(cn->node->type)) {
1550                                         PTQUEUE_NEW(n, ptq_entry, -1, cn);
1551                                         TAILQ_INSERT_TAIL(&pt_head, n, ptq);
1552                                 }
1553                         }
1554                 }
1555                 counter++;
1556         }
1557         return pathTableSize;
1558 }
1559
1560 void
1561 cd9660_compute_full_filename(cd9660node *node, char *buf)
1562 {
1563         int len;
1564
1565         len = PATH_MAX;
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.");
1570 }
1571
1572 /*
1573  * TODO: These two functions are almost identical.
1574  * Some code cleanup is possible here
1575  *
1576  * XXX bounds checking!
1577  */
1578 static int
1579 cd9660_level1_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1580     char *newname, int is_file)
1581 {
1582         /*
1583          * ISO 9660 : 10.1
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
1587          */
1588         int namelen = 0;
1589         int extlen = 0;
1590         int found_ext = 0;
1591
1592         while (*oldname != '\0' && extlen < 3) {
1593                 /* Handle period first, as it is special */
1594                 if (*oldname == '.') {
1595                         if (found_ext) {
1596                                 *newname++ = '_';
1597                                 extlen ++;
1598                         }
1599                         else {
1600                                 *newname++ = '.';
1601                                 found_ext = 1;
1602                         }
1603                 } else {
1604                         /* cut RISC OS file type off ISO name */
1605                         if (diskStructure->archimedes_enabled &&
1606                             *oldname == ',' && strlen(oldname) == 4)
1607                                 break;
1608
1609                         /* Enforce 12.3 / 8 */
1610                         if (namelen == 8 && !found_ext)
1611                                 break;
1612
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;
1618                         else
1619                                 *newname++ = '_';
1620
1621                         if (found_ext)
1622                                 extlen++;
1623                         else
1624                                 namelen++;
1625                 }
1626                 oldname++;
1627         }
1628         if (is_file) {
1629                 if (!found_ext && !diskStructure->omit_trailing_period)
1630                         *newname++ = '.';
1631                 /* Add version */
1632                 sprintf(newname, ";%i", 1);
1633         }
1634         return namelen + extlen + found_ext;
1635 }
1636
1637 /* XXX bounds checking! */
1638 static int
1639 cd9660_level2_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1640     char *newname, int is_file)
1641 {
1642         /*
1643          * ISO 9660 : 7.5.1
1644          * File name : 0+ d or d1 characters
1645          * separator 1 (.)
1646          * File name extension : 0+ d or d1 characters
1647          * separator 2 (;)
1648          * File version number (5 characters, 1-32767)
1649          * 1 <= Sum of File name and File name extension <= 30
1650          */
1651         int namelen = 0;
1652         int extlen = 0;
1653         int found_ext = 0;
1654
1655         while (*oldname != '\0' && namelen + extlen < 30) {
1656                 /* Handle period first, as it is special */
1657                 if (*oldname == '.') {
1658                         if (found_ext) {
1659                                 if (diskStructure->allow_multidot) {
1660                                         *newname++ = '.';
1661                                 } else {
1662                                         *newname++ = '_';
1663                                 }
1664                                 extlen ++;
1665                         }
1666                         else {
1667                                 *newname++ = '.';
1668                                 found_ext = 1;
1669                         }
1670                 } else {
1671                         /* cut RISC OS file type off ISO name */
1672                         if (diskStructure->archimedes_enabled &&
1673                             *oldname == ',' && strlen(oldname) == 4)
1674                                 break;
1675
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 &&
1682                             *oldname == '.') {
1683                                 *newname++ = '.';
1684                         } else {
1685                                 *newname++ = '_';
1686                         }
1687
1688                         if (found_ext)
1689                                 extlen++;
1690                         else
1691                                 namelen++;
1692                 }
1693                 oldname ++;
1694         }
1695         if (is_file) {
1696                 if (!found_ext && !diskStructure->omit_trailing_period)
1697                         *newname++ = '.';
1698                 /* Add version */
1699                 sprintf(newname, ";%i", 1);
1700         }
1701         return namelen + extlen + found_ext;
1702 }
1703
1704 /*
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
1711  */
1712 static int
1713 cd9660_convert_filename(iso9660_disk *diskStructure, const char *oldname,
1714     char *newname, int is_file)
1715 {
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));
1723         abort();
1724 }
1725
1726 int
1727 cd9660_compute_record_size(iso9660_disk *diskStructure, cd9660node *node)
1728 {
1729         int size = node->isoDirRecord->length[0];
1730
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);
1736         return size;
1737 }
1738
1739 static void
1740 cd9660_populate_dot_records(iso9660_disk *diskStructure, cd9660node *node)
1741 {
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);
1750
1751         if (node == diskStructure->rootNode) {
1752                 node->dot_dot_record->fileDataSector = node->fileDataSector;
1753                 memcpy(node->dot_dot_record->isoDirRecord,node->isoDirRecord,
1754                     34);
1755         } else {
1756                 node->dot_dot_record->fileDataSector =
1757                     node->parent->fileDataSector;
1758                 memcpy(node->dot_dot_record->isoDirRecord,
1759                     node->parent->isoDirRecord,34);
1760         }
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);
1767 }
1768
1769 /*
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)
1774 */
1775 static int64_t
1776 cd9660_compute_offsets(iso9660_disk *diskStructure, cd9660node *node,
1777     int64_t startOffset)
1778 {
1779         /*
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
1783          */
1784         int64_t used_bytes = 0;
1785         int64_t current_sector_usage = 0;
1786         cd9660node *child;
1787         fsinode *inode;
1788         int64_t r;
1789
1790         assert(node != NULL);
1791
1792
1793         /*
1794          * NOTE : There needs to be some special case detection for
1795          * the "real root" node, since for it, node->node is undefined
1796          */
1797
1798         node->fileDataSector = -1;
1799
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);
1806
1807                 cd9660_bothendian_dword(node->fileDataSector,
1808                     node->isoDirRecord->extent);
1809
1810                 /*
1811                  * First loop over children, need to know the size of
1812                  * their directory records
1813                  */
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++;
1823                         }
1824
1825                         current_sector_usage +=
1826                             cd9660_compute_record_size(diskStructure, child);
1827                 }
1828
1829                 cd9660_bothendian_dword(node->fileSectorsUsed *
1830                         diskStructure->sectorSize,node->isoDirRecord->size);
1831
1832                 /*
1833                  * This should point to the sector after the directory
1834                  * record (or, the first byte in that sector)
1835                  */
1836                 used_bytes += node->fileSectorsUsed * diskStructure->sectorSize;
1837
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);
1844
1845                                 if (r != -1)
1846                                         used_bytes += r;
1847                                 else
1848                                         return -1;
1849                         }
1850                 }
1851
1852                 /* Explicitly set the . and .. records */
1853                 cd9660_populate_dot_records(diskStructure, node);
1854
1855                 /* Finally, do another iteration to write the file data*/
1856                 for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child);
1857                      child != NULL;
1858                      child = TAILQ_NEXT(child, cn_next_child)) {
1859                         /* Files need extent set */
1860                         if (S_ISDIR(child->node->type))
1861                                 continue;
1862                         child->fileRecordSize =
1863                             cd9660_compute_record_size(diskStructure, child);
1864
1865                         child->fileSectorsUsed =
1866                             CD9660_BLOCKS(diskStructure->sectorSize,
1867                                 child->fileDataLength);
1868
1869                         inode = child->node->inode;
1870                         if ((inode->flags & FI_ALLOCATED) == 0) {
1871                                 inode->ino =
1872                                     CD9660_BLOCKS(diskStructure->sectorSize,
1873                                         used_bytes + startOffset);
1874                                 inode->flags |= FI_ALLOCATED;
1875                                 used_bytes += child->fileSectorsUsed *
1876                                     diskStructure->sectorSize;
1877                         } else {
1878                                 INODE_WARNX(("%s: already allocated inode %d "
1879                                       "data sectors at %" PRIu32, __func__,
1880                                       (int)inode->st.st_ino, inode->ino));
1881                         }
1882                         child->fileDataSector = inode->ino;
1883                         cd9660_bothendian_dword(child->fileDataSector,
1884                                 child->isoDirRecord->extent);
1885                 }
1886         }
1887
1888         return used_bytes;
1889 }
1890
1891 #if 0
1892 /* Might get rid of this func */
1893 static int
1894 cd9660_copy_stat_info(cd9660node *from, cd9660node *to, int file)
1895 {
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);
1908         if (file)
1909                 to->node->inode->st.st_mode |= S_IFREG;
1910         else
1911                 to->node->inode->st.st_mode |= S_IFDIR;
1912         return 1;
1913 }
1914 #endif
1915
1916 static cd9660node *
1917 cd9660_create_virtual_entry(iso9660_disk *diskStructure, const char *name,
1918     cd9660node *parent, int file, int insert)
1919 {
1920         cd9660node *temp;
1921         fsnode * tfsnode;
1922
1923         assert(parent != NULL);
1924
1925         temp = cd9660_allocate_cd9660node();
1926         if (temp == NULL)
1927                 return NULL;
1928
1929         tfsnode = emalloc(sizeof(*tfsnode));
1930         tfsnode->name = estrdup(name);
1931         temp->isoDirRecord = emalloc(sizeof(*temp->isoDirRecord));
1932
1933         cd9660_convert_filename(diskStructure, tfsnode->name,
1934             temp->isoDirRecord->name, file);
1935
1936         temp->node = tfsnode;
1937         temp->parent = parent;
1938
1939         if (insert) {
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);
1944                         else
1945                                 TAILQ_INSERT_HEAD(&temp->parent->cn_children,
1946                                     temp, cn_next_child);
1947                 }
1948         }
1949
1950         if (parent->node != NULL) {
1951                 tfsnode->type = parent->node->type;
1952         }
1953
1954         /* Clear out file type bits */
1955         tfsnode->type &= ~(S_IFMT);
1956         if (file)
1957                 tfsnode->type |= S_IFREG;
1958         else
1959                 tfsnode->type |= S_IFDIR;
1960
1961         /* Indicate that there is no spec entry (inode) */
1962         tfsnode->flags &= ~(FSNODE_F_HASSPEC);
1963 #if 0
1964         cd9660_copy_stat_info(parent, temp, file);
1965 #endif
1966         return temp;
1967 }
1968
1969 static cd9660node *
1970 cd9660_create_file(iso9660_disk *diskStructure, const char *name,
1971     cd9660node *parent, cd9660node *me)
1972 {
1973         cd9660node *temp;
1974
1975         temp = cd9660_create_virtual_entry(diskStructure, name, parent, 1, 1);
1976         if (temp == NULL)
1977                 return NULL;
1978
1979         temp->fileDataLength = 0;
1980
1981         temp->type = CD9660_TYPE_FILE | CD9660_TYPE_VIRTUAL;
1982
1983         temp->node->inode = ecalloc(1, sizeof(*temp->node->inode));
1984         *temp->node->inode = *me->node->inode;
1985
1986         if (cd9660_translate_node_common(diskStructure, temp) == 0)
1987                 return NULL;
1988         return temp;
1989 }
1990
1991 /*
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
1996  */
1997 static cd9660node *
1998 cd9660_create_directory(iso9660_disk *diskStructure, const char *name,
1999     cd9660node *parent, cd9660node *me)
2000 {
2001         cd9660node *temp;
2002
2003         temp = cd9660_create_virtual_entry(diskStructure, name, parent, 0, 1);
2004         if (temp == NULL)
2005                 return NULL;
2006         temp->node->type |= S_IFDIR;
2007
2008         temp->type = CD9660_TYPE_DIR | CD9660_TYPE_VIRTUAL;
2009
2010         temp->node->inode = ecalloc(1, sizeof(*temp->node->inode));
2011         *temp->node->inode = *me->node->inode;
2012
2013         if (cd9660_translate_node_common(diskStructure, temp) == 0)
2014                 return NULL;
2015         return temp;
2016 }
2017
2018 static cd9660node *
2019 cd9660_create_special_directory(iso9660_disk *diskStructure, u_char type,
2020     cd9660node *parent)
2021 {
2022         cd9660node *temp, *first;
2023         char na[2];
2024
2025         assert(parent != NULL);
2026
2027         if (type == CD9660_TYPE_DOT)
2028                 na[0] = 0;
2029         else if (type == CD9660_TYPE_DOTDOT)
2030                 na[0] = 1;
2031         else
2032                 return 0;
2033
2034         na[1] = 0;
2035         if ((temp = cd9660_create_virtual_entry(diskStructure, na, parent,
2036             0, 0)) == NULL)
2037                 return NULL;
2038
2039         temp->parent = parent;
2040         temp->type = type;
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;
2049                 /*
2050                  * If the first child is the dot record, insert
2051                  * this second.  Otherwise, insert it at the head.
2052                  */
2053                 if ((first = TAILQ_FIRST(&parent->cn_children)) == NULL ||
2054                     (first->type & CD9660_TYPE_DOT) == 0) {
2055                         TAILQ_INSERT_HEAD(&parent->cn_children, temp,
2056                             cn_next_child);
2057                 } else {
2058                         TAILQ_INSERT_AFTER(&parent->cn_children, first, temp,
2059                             cn_next_child);
2060                 }
2061         }
2062
2063         return temp;
2064 }
2065
2066 static int
2067 cd9660_add_generic_bootimage(iso9660_disk *diskStructure, const char *bootimage)
2068 {
2069         struct stat stbuf;
2070
2071         assert(bootimage != NULL);
2072
2073         if (*bootimage == '\0') {
2074                 warnx("Error: Boot image must be a filename");
2075                 return 0;
2076         }
2077
2078         diskStructure->generic_bootimage = estrdup(bootimage);
2079
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);
2084
2085         if (stbuf.st_size > 32768) {
2086                 warnx("Error: Boot image must be no greater than 32768 bytes");
2087                 return 0;
2088         }
2089
2090         if (diskStructure->verbose_level > 0) {
2091                 printf("Generic boot image has size %lld\n",
2092                     (long long)stbuf.st_size);
2093         }
2094
2095         diskStructure->has_generic_bootimage = 1;
2096
2097         return 1;
2098 }