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