Index: stable/11/usr.sbin/makefs/cd9660/cd9660_archimedes.c =================================================================== --- stable/11/usr.sbin/makefs/cd9660/cd9660_archimedes.c (revision 332979) +++ stable/11/usr.sbin/makefs/cd9660/cd9660_archimedes.c (revision 332980) @@ -1,128 +1,130 @@ /* $NetBSD: cd9660_archimedes.c,v 1.1 2009/01/10 22:06:29 bjh21 Exp $ */ /*- * SPDX-License-Identifier: BSD-3-Clause * * Copyright (c) 1998, 2009 Ben Harris * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * cd9660_archimedes.c - support for RISC OS "ARCHIMEDES" extension * * RISC OS CDFS looks for a special block at the end of the System Use * Field for each file. If present, this contains the RISC OS load * and exec address (used to hold the file timestamp and type), the * file attributes, and a flag indicating whether the first character * of the filename should be replaced with '!' (since many special * RISC OS filenames do). */ #include __FBSDID("$FreeBSD$"); +#include #include #include #include +#include #include #include "makefs.h" #include "cd9660.h" #include "cd9660_archimedes.h" /* * Convert a Unix time_t (non-leap seconds since 1970-01-01) to a RISC * OS time (non-leap(?) centiseconds since 1900-01-01(?)). */ static u_int64_t riscos_date(time_t unixtime) { u_int64_t base; base = 31536000ULL * 70 + 86400 * 17; return (((u_int64_t)unixtime) + base)*100; } /* * Add "ARCHIMEDES" metadata to a node if that seems appropriate. * * We touch regular files with names matching /,[0-9a-f]{3}$/ and * directories matching /^!/. */ static void archimedes_convert_node(cd9660node *node) { struct ISO_ARCHIMEDES *arc; size_t len; int type = -1; uint64_t stamp; if (node->su_tail_data != NULL) /* Something else already has the tail. */ return; len = strlen(node->node->name); if (len < 1) return; if (len >= 4 && node->node->name[len-4] == ',') /* XXX should support ,xxx and ,lxa */ type = strtoul(node->node->name + len - 3, NULL, 16); if (type == -1 && node->node->name[0] != '!') return; if (type == -1) type = 0; assert(sizeof(struct ISO_ARCHIMEDES) == 32); if ((arc = calloc(1, sizeof(struct ISO_ARCHIMEDES))) == NULL) { CD9660_MEM_ALLOC_ERROR("archimedes_convert_node"); exit(1); } stamp = riscos_date(node->node->inode->st.st_mtime); memcpy(arc->magic, "ARCHIMEDES", 10); cd9660_731(0xfff00000 | (type << 8) | (stamp >> 32), arc->loadaddr); cd9660_731(stamp & 0x00ffffffffULL, arc->execaddr); arc->ro_attr = RO_ACCESS_UR | RO_ACCESS_OR; arc->cdfs_attr = node->node->name[0] == '!' ? CDFS_PLING : 0; node->su_tail_data = (void *)arc; node->su_tail_size = sizeof(*arc); } /* * Add "ARCHIMEDES" metadata to an entire tree recursively. */ void archimedes_convert_tree(cd9660node *node) { cd9660node *cn; assert(node != NULL); archimedes_convert_node(node); /* Recurse on children. */ TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) archimedes_convert_tree(cn); } Index: stable/11/usr.sbin/makefs/cd9660/iso9660_rrip.c =================================================================== --- stable/11/usr.sbin/makefs/cd9660/iso9660_rrip.c (revision 332979) +++ stable/11/usr.sbin/makefs/cd9660/iso9660_rrip.c (revision 332980) @@ -1,842 +1,844 @@ /* $NetBSD: iso9660_rrip.c,v 1.14 2014/05/30 13:14:47 martin Exp $ */ /*- * SPDX-License-Identifier: BSD-2-Clause-NetBSD * * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan * Perez-Rathke and Ram Vedam. All rights reserved. * * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys, * Alan Perez-Rathke and Ram Vedam. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* This will hold all the function definitions * defined in iso9660_rrip.h */ -#include "makefs.h" -#include "cd9660.h" -#include "iso9660_rrip.h" +#include +__FBSDID("$FreeBSD$"); + #include +#include #include -#include -__FBSDID("$FreeBSD$"); +#include "makefs.h" +#include "cd9660.h" +#include "iso9660_rrip.h" static void cd9660_rrip_initialize_inode(cd9660node *); static int cd9660_susp_handle_continuation(iso9660_disk *, cd9660node *); static int cd9660_susp_handle_continuation_common(iso9660_disk *, cd9660node *, int); int cd9660_susp_initialize(iso9660_disk *diskStructure, cd9660node *node, cd9660node *parent, cd9660node *grandparent) { cd9660node *cn; int r; /* Make sure the node is not NULL. If it is, there are major problems */ assert(node != NULL); if (!(node->type & CD9660_TYPE_DOT) && !(node->type & CD9660_TYPE_DOTDOT)) TAILQ_INIT(&(node->head)); if (node->dot_record != 0) TAILQ_INIT(&(node->dot_record->head)); if (node->dot_dot_record != 0) TAILQ_INIT(&(node->dot_dot_record->head)); /* SUSP specific entries here */ if ((r = cd9660_susp_initialize_node(diskStructure, node)) < 0) return r; /* currently called cd9660node_rrip_init_links */ r = cd9660_rrip_initialize_node(diskStructure, node, parent, grandparent); if (r < 0) return r; /* * See if we need a CE record, and set all of the * associated counters. * * This should be called after all extensions. After * this is called, no new records should be added. */ if ((r = cd9660_susp_handle_continuation(diskStructure, node)) < 0) return r; /* Recurse on children. */ TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) { if ((r = cd9660_susp_initialize(diskStructure, cn, node, parent)) < 0) return 0; } return 1; } int cd9660_susp_finalize(iso9660_disk *diskStructure, cd9660node *node) { cd9660node *temp; int r; assert(node != NULL); if (node == diskStructure->rootNode) diskStructure->susp_continuation_area_current_free = 0; if ((r = cd9660_susp_finalize_node(diskStructure, node)) < 0) return r; if ((r = cd9660_rrip_finalize_node(node)) < 0) return r; TAILQ_FOREACH(temp, &node->cn_children, cn_next_child) { if ((r = cd9660_susp_finalize(diskStructure, temp)) < 0) return r; } return 1; } /* * If we really wanted to speed things up, we could have some sort of * lookup table on the SUSP entry type that calls a functor. Or, we could * combine the functions. These functions are kept separate to allow * easier addition of other extensions. * For the sake of simplicity and clarity, we won't be doing that for now. */ /* * SUSP needs to update the following types: * CE (continuation area) */ int cd9660_susp_finalize_node(iso9660_disk *diskStructure, cd9660node *node) { struct ISO_SUSP_ATTRIBUTES *t; /* Handle CE counters */ if (node->susp_entry_ce_length > 0) { node->susp_entry_ce_start = diskStructure->susp_continuation_area_current_free; diskStructure->susp_continuation_area_current_free += node->susp_entry_ce_length; } TAILQ_FOREACH(t, &node->head, rr_ll) { if (t->susp_type != SUSP_TYPE_SUSP || t->entry_type != SUSP_ENTRY_SUSP_CE) continue; cd9660_bothendian_dword( diskStructure-> susp_continuation_area_start_sector, t->attr.su_entry.CE.ca_sector); cd9660_bothendian_dword( diskStructure-> susp_continuation_area_start_sector, t->attr.su_entry.CE.ca_sector); cd9660_bothendian_dword(node->susp_entry_ce_start, t->attr.su_entry.CE.offset); cd9660_bothendian_dword(node->susp_entry_ce_length, t->attr.su_entry.CE.length); } return 0; } int cd9660_rrip_finalize_node(cd9660node *node) { struct ISO_SUSP_ATTRIBUTES *t; TAILQ_FOREACH(t, &node->head, rr_ll) { if (t->susp_type != SUSP_TYPE_RRIP) continue; switch (t->entry_type) { case SUSP_ENTRY_RRIP_CL: /* Look at rr_relocated*/ if (node->rr_relocated == NULL) return -1; cd9660_bothendian_dword( node->rr_relocated->fileDataSector, (unsigned char *) t->attr.rr_entry.CL.dir_loc); break; case SUSP_ENTRY_RRIP_PL: /* Look at rr_real_parent */ if (node->parent == NULL || node->parent->rr_real_parent == NULL) return -1; cd9660_bothendian_dword( node->parent->rr_real_parent->fileDataSector, (unsigned char *) t->attr.rr_entry.PL.dir_loc); break; } } return 0; } static int cd9660_susp_handle_continuation_common(iso9660_disk *diskStructure, cd9660node *node, int space) { int ca_used, susp_used, susp_used_pre_ce, working; struct ISO_SUSP_ATTRIBUTES *temp, *pre_ce, *last, *CE, *ST; pre_ce = last = NULL; working = 254 - space; if (node->su_tail_size > 0) /* Allow 4 bytes for "ST" record. */ working -= node->su_tail_size + 4; /* printf("There are %i bytes to work with\n",working); */ susp_used_pre_ce = susp_used = 0; ca_used = 0; TAILQ_FOREACH(temp, &node->head, rr_ll) { if (working < 0) break; /* * printf("SUSP Entry found, length is %i\n", * CD9660_SUSP_ENTRY_SIZE(temp)); */ working -= CD9660_SUSP_ENTRY_SIZE(temp); if (working >= 0) { last = temp; susp_used += CD9660_SUSP_ENTRY_SIZE(temp); } if (working >= 28) { /* * Remember the last entry after which we * could insert a "CE" entry. */ pre_ce = last; susp_used_pre_ce = susp_used; } } /* A CE entry is needed */ if (working <= 0) { CE = cd9660node_susp_create_node(SUSP_TYPE_SUSP, SUSP_ENTRY_SUSP_CE, "CE", SUSP_LOC_ENTRY); cd9660_susp_ce(CE, node); /* This will automatically insert at the appropriate location */ if (pre_ce != NULL) TAILQ_INSERT_AFTER(&node->head, pre_ce, CE, rr_ll); else TAILQ_INSERT_HEAD(&node->head, CE, rr_ll); last = CE; susp_used = susp_used_pre_ce + 28; /* Count how much CA data is necessary */ for (temp = TAILQ_NEXT(last, rr_ll); temp != NULL; temp = TAILQ_NEXT(temp, rr_ll)) { ca_used += CD9660_SUSP_ENTRY_SIZE(temp); } } /* An ST entry is needed */ if (node->su_tail_size > 0) { ST = cd9660node_susp_create_node(SUSP_TYPE_SUSP, SUSP_ENTRY_SUSP_ST, "ST", SUSP_LOC_ENTRY); cd9660_susp_st(ST, node); if (last != NULL) TAILQ_INSERT_AFTER(&node->head, last, ST, rr_ll); else TAILQ_INSERT_HEAD(&node->head, ST, rr_ll); last = ST; susp_used += 4; } if (last != NULL) last->last_in_suf = 1; node->susp_entry_size = susp_used; node->susp_entry_ce_length = ca_used; diskStructure->susp_continuation_area_size += ca_used; return 1; } /* See if a continuation entry is needed for each of the different types */ static int cd9660_susp_handle_continuation(iso9660_disk *diskStructure, cd9660node *node) { assert (node != NULL); /* Entry */ if (cd9660_susp_handle_continuation_common(diskStructure, node,(int)(node->isoDirRecord->length[0])) < 0) return 0; return 1; } int cd9660_susp_initialize_node(iso9660_disk *diskStructure, cd9660node *node) { struct ISO_SUSP_ATTRIBUTES *temp; /* * Requirements/notes: * CE: is added for us where needed * ST: not sure if it is even required, but if so, should be * handled by the CE code * PD: isn't needed (though might be added for testing) * SP: is stored ONLY on the . record of the root directory * ES: not sure */ /* Check for root directory, add SP and ER if needed. */ if (node->type & CD9660_TYPE_DOT) { if (node->parent == diskStructure->rootNode) { temp = cd9660node_susp_create_node(SUSP_TYPE_SUSP, SUSP_ENTRY_SUSP_SP, "SP", SUSP_LOC_DOT); cd9660_susp_sp(temp, node); /* Should be first entry. */ TAILQ_INSERT_HEAD(&node->head, temp, rr_ll); } } return 1; } static void cd9660_rrip_initialize_inode(cd9660node *node) { struct ISO_SUSP_ATTRIBUTES *attr; /* * Inode dependent values - this may change, * but for now virtual files and directories do * not have an inode structure */ if ((node->node != NULL) && (node->node->inode != NULL)) { /* PX - POSIX attributes */ attr = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_PX, "PX", SUSP_LOC_ENTRY); cd9660node_rrip_px(attr, node->node); TAILQ_INSERT_TAIL(&node->head, attr, rr_ll); /* TF - timestamp */ attr = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_TF, "TF", SUSP_LOC_ENTRY); cd9660node_rrip_tf(attr, node->node); TAILQ_INSERT_TAIL(&node->head, attr, rr_ll); /* SL - Symbolic link */ /* ?????????? Dan - why is this here? */ if (TAILQ_EMPTY(&node->cn_children) && node->node->inode != NULL && S_ISLNK(node->node->inode->st.st_mode)) cd9660_createSL(node); /* PN - device number */ if (node->node->inode != NULL && ((S_ISCHR(node->node->inode->st.st_mode) || S_ISBLK(node->node->inode->st.st_mode)))) { attr = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_PN, "PN", SUSP_LOC_ENTRY); cd9660node_rrip_pn(attr, node->node); TAILQ_INSERT_TAIL(&node->head, attr, rr_ll); } } } int cd9660_rrip_initialize_node(iso9660_disk *diskStructure, cd9660node *node, cd9660node *parent, cd9660node *grandparent) { struct ISO_SUSP_ATTRIBUTES *current = NULL; assert(node != NULL); if (node->type & CD9660_TYPE_DOT) { /* * Handle ER - should be the only entry to appear on * a "." record */ if (node->parent == diskStructure->rootNode) { cd9660_susp_ER(node, 1, SUSP_RRIP_ER_EXT_ID, SUSP_RRIP_ER_EXT_DES, SUSP_RRIP_ER_EXT_SRC); } if (parent != NULL && parent->node != NULL && parent->node->inode != NULL) { /* PX - POSIX attributes */ current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_PX, "PX", SUSP_LOC_ENTRY); cd9660node_rrip_px(current, parent->node); TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } } else if (node->type & CD9660_TYPE_DOTDOT) { if (grandparent != NULL && grandparent->node != NULL && grandparent->node->inode != NULL) { /* PX - POSIX attributes */ current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_PX, "PX", SUSP_LOC_ENTRY); cd9660node_rrip_px(current, grandparent->node); TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } /* Handle PL */ if (parent != NULL && parent->rr_real_parent != NULL) { current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_PL, "PL", SUSP_LOC_DOTDOT); cd9660_rrip_PL(current,node); TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } } else { cd9660_rrip_initialize_inode(node); /* * Not every node needs a NM set - only if the name is * actually different. IE: If a file is TEST -> TEST, * no NM. test -> TEST, need a NM * * The rr_moved_dir needs to be assigned a NM record as well. */ if (node == diskStructure->rr_moved_dir) { cd9660_rrip_add_NM(node, RRIP_DEFAULT_MOVE_DIR_NAME); } else if ((node->node != NULL) && ((strlen(node->node->name) != (uint8_t)node->isoDirRecord->name_len[0]) || (memcmp(node->node->name,node->isoDirRecord->name, (uint8_t)node->isoDirRecord->name_len[0]) != 0))) { cd9660_rrip_NM(node); } /* Rock ridge directory relocation code here. */ /* First handle the CL for the placeholder file. */ if (node->rr_relocated != NULL) { current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_CL, "CL", SUSP_LOC_ENTRY); cd9660_rrip_CL(current, node); TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } /* Handle RE*/ if (node->rr_real_parent != NULL) { current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_RE, "RE", SUSP_LOC_ENTRY); cd9660_rrip_RE(current,node); TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } } return 1; } struct ISO_SUSP_ATTRIBUTES* cd9660node_susp_create_node(int susp_type, int entry_type, const char *type_id, int write_loc) { struct ISO_SUSP_ATTRIBUTES* temp; if ((temp = malloc(sizeof(struct ISO_SUSP_ATTRIBUTES))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660node_susp_create_node"); exit(1); } temp->susp_type = susp_type; temp->entry_type = entry_type; temp->last_in_suf = 0; /* Phase this out */ temp->type_of[0] = type_id[0]; temp->type_of[1] = type_id[1]; temp->write_location = write_loc; /* * Since the first four bytes is common, lets go ahead and * set the type identifier, since we are passing that to this * function anyhow. */ temp->attr.su_entry.SP.h.type[0] = type_id[0]; temp->attr.su_entry.SP.h.type[1] = type_id[1]; return temp; } int cd9660_rrip_PL(struct ISO_SUSP_ATTRIBUTES* p, cd9660node *node __unused) { p->attr.rr_entry.PL.h.length[0] = 12; p->attr.rr_entry.PL.h.version[0] = 1; return 1; } int cd9660_rrip_CL(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *node __unused) { p->attr.rr_entry.CL.h.length[0] = 12; p->attr.rr_entry.CL.h.version[0] = 1; return 1; } int cd9660_rrip_RE(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *node __unused) { p->attr.rr_entry.RE.h.length[0] = 4; p->attr.rr_entry.RE.h.version[0] = 1; return 1; } void cd9660_createSL(cd9660node *node) { struct ISO_SUSP_ATTRIBUTES* current; int path_count, dir_count, done, i, j, dir_copied; char temp_cr[255]; char temp_sl[255]; /* used in copying continuation entry*/ char* sl_ptr; sl_ptr = node->node->symlink; done = 0; path_count = 0; dir_count = 0; dir_copied = 0; current = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_SL, "SL", SUSP_LOC_ENTRY); current->attr.rr_entry.SL.h.version[0] = 1; current->attr.rr_entry.SL.flags[0] = SL_FLAGS_NONE; if (*sl_ptr == '/') { temp_cr[0] = SL_FLAGS_ROOT; temp_cr[1] = 0; memcpy(current->attr.rr_entry.SL.component + path_count, temp_cr, 2); path_count += 2; sl_ptr++; } for (i = 0; i < (dir_count + 2); i++) temp_cr[i] = '\0'; while (!done) { while ((*sl_ptr != '/') && (*sl_ptr != '\0')) { dir_copied = 1; if (*sl_ptr == '.') { if ((*(sl_ptr + 1) == '/') || (*(sl_ptr + 1) == '\0')) { temp_cr[0] = SL_FLAGS_CURRENT; sl_ptr++; } else if(*(sl_ptr + 1) == '.') { if ((*(sl_ptr + 2) == '/') || (*(sl_ptr + 2) == '\0')) { temp_cr[0] = SL_FLAGS_PARENT; sl_ptr += 2; } } else { temp_cr[dir_count+2] = *sl_ptr; sl_ptr++; dir_count++; } } else { temp_cr[dir_count + 2] = *sl_ptr; sl_ptr++; dir_count++; } } if ((path_count + dir_count) >= 249) { current->attr.rr_entry.SL.flags[0] |= SL_FLAGS_CONTINUE; j = 0; if (path_count <= 249) { while(j != (249 - path_count)) { temp_sl[j] = temp_cr[j]; j++; } temp_sl[0] = SL_FLAGS_CONTINUE; temp_sl[1] = j - 2; memcpy( current->attr.rr_entry.SL.component + path_count, temp_sl, j); } path_count += j; current->attr.rr_entry.SL.h.length[0] = path_count + 5; TAILQ_INSERT_TAIL(&node->head, current, rr_ll); current= cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_SL, "SL", SUSP_LOC_ENTRY); current->attr.rr_entry.SL.h.version[0] = 1; current->attr.rr_entry.SL.flags[0] = SL_FLAGS_NONE; path_count = 0; if (dir_count > 2) { while (j != dir_count + 2) { current->attr.rr_entry.SL.component[ path_count + 2] = temp_cr[j]; j++; path_count++; } current->attr.rr_entry.SL.component[1] = path_count; path_count+= 2; } else { while(j != dir_count) { current->attr.rr_entry.SL.component[ path_count+2] = temp_cr[j]; j++; path_count++; } } } else { if (dir_copied == 1) { temp_cr[1] = dir_count; memcpy(current->attr.rr_entry.SL.component + path_count, temp_cr, dir_count + 2); path_count += dir_count + 2; } } if (*sl_ptr == '\0') { done = 1; current->attr.rr_entry.SL.h.length[0] = path_count + 5; TAILQ_INSERT_TAIL(&node->head, current, rr_ll); } else { sl_ptr++; dir_count = 0; dir_copied = 0; for(i = 0; i < 255; i++) { temp_cr[i] = '\0'; } } } } int cd9660node_rrip_px(struct ISO_SUSP_ATTRIBUTES *v, fsnode *pxinfo) { v->attr.rr_entry.PX.h.length[0] = 44; v->attr.rr_entry.PX.h.version[0] = 1; cd9660_bothendian_dword(pxinfo->inode->st.st_mode, v->attr.rr_entry.PX.mode); cd9660_bothendian_dword(pxinfo->inode->st.st_nlink, v->attr.rr_entry.PX.links); cd9660_bothendian_dword(pxinfo->inode->st.st_uid, v->attr.rr_entry.PX.uid); cd9660_bothendian_dword(pxinfo->inode->st.st_gid, v->attr.rr_entry.PX.gid); cd9660_bothendian_dword(pxinfo->inode->st.st_ino, v->attr.rr_entry.PX.serial); return 1; } int cd9660node_rrip_pn(struct ISO_SUSP_ATTRIBUTES *pn_field, fsnode *fnode) { pn_field->attr.rr_entry.PN.h.length[0] = 20; pn_field->attr.rr_entry.PN.h.version[0] = 1; if (sizeof (fnode->inode->st.st_rdev) > 4) cd9660_bothendian_dword( (uint64_t)fnode->inode->st.st_rdev >> 32, pn_field->attr.rr_entry.PN.high); else cd9660_bothendian_dword(0, pn_field->attr.rr_entry.PN.high); cd9660_bothendian_dword(fnode->inode->st.st_rdev & 0xffffffff, pn_field->attr.rr_entry.PN.low); return 1; } #if 0 int cd9660node_rrip_nm(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *file_node) { int nm_length = strlen(file_node->isoDirRecord->name) + 5; p->attr.rr_entry.NM.h.type[0] = 'N'; p->attr.rr_entry.NM.h.type[1] = 'M'; sprintf(p->attr.rr_entry.NM.altname, "%s", file_node->isoDirRecord->name); p->attr.rr_entry.NM.h.length[0] = (unsigned char)nm_length; p->attr.rr_entry.NM.h.version[0] = (unsigned char)1; p->attr.rr_entry.NM.flags[0] = (unsigned char) NM_PARENT; return 1; } #endif int cd9660node_rrip_tf(struct ISO_SUSP_ATTRIBUTES *p, fsnode *_node) { p->attr.rr_entry.TF.flags[0] = TF_MODIFY | TF_ACCESS | TF_ATTRIBUTES; p->attr.rr_entry.TF.h.length[0] = 5; p->attr.rr_entry.TF.h.version[0] = 1; /* * Need to add creation time, backup time, * expiration time, and effective time. */ cd9660_time_915(p->attr.rr_entry.TF.timestamp, _node->inode->st.st_atime); p->attr.rr_entry.TF.h.length[0] += 7; cd9660_time_915(p->attr.rr_entry.TF.timestamp + 7, _node->inode->st.st_mtime); p->attr.rr_entry.TF.h.length[0] += 7; cd9660_time_915(p->attr.rr_entry.TF.timestamp + 14, _node->inode->st.st_ctime); p->attr.rr_entry.TF.h.length[0] += 7; return 1; } int cd9660_susp_sp(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *spinfo __unused) { p->attr.su_entry.SP.h.length[0] = 7; p->attr.su_entry.SP.h.version[0] = 1; p->attr.su_entry.SP.check[0] = 0xBE; p->attr.su_entry.SP.check[1] = 0xEF; p->attr.su_entry.SP.len_skp[0] = 0; return 1; } int cd9660_susp_st(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *stinfo __unused) { p->attr.su_entry.ST.h.type[0] = 'S'; p->attr.su_entry.ST.h.type[1] = 'T'; p->attr.su_entry.ST.h.length[0] = 4; p->attr.su_entry.ST.h.version[0] = 1; return 1; } int cd9660_susp_ce(struct ISO_SUSP_ATTRIBUTES *p, cd9660node *spinfo __unused) { p->attr.su_entry.CE.h.length[0] = 28; p->attr.su_entry.CE.h.version[0] = 1; /* Other attributes dont matter right now, will be updated later */ return 1; } int cd9660_susp_pd(struct ISO_SUSP_ATTRIBUTES *p __unused, int length __unused) { return 1; } void cd9660_rrip_add_NM(cd9660node *node, const char *name) { int working,len; const char *p; struct ISO_SUSP_ATTRIBUTES *r; /* * Each NM record has 254 byes to work with. This means that * the name data itself only has 249 bytes to work with. So, a * name with 251 characters would require two nm records. */ p = name; working = 1; while (working) { r = cd9660node_susp_create_node(SUSP_TYPE_RRIP, SUSP_ENTRY_RRIP_NM, "NM", SUSP_LOC_ENTRY); r->attr.rr_entry.NM.h.version[0] = 1; r->attr.rr_entry.NM.flags[0] = RRIP_NM_FLAGS_NONE; len = strlen(p); if (len > 249) { len = 249; r->attr.rr_entry.NM.flags[0] = RRIP_NM_FLAGS_CONTINUE; } else { working = 0; } memcpy(r->attr.rr_entry.NM.altname, p, len); r->attr.rr_entry.NM.h.length[0] = 5 + len; TAILQ_INSERT_TAIL(&node->head, r, rr_ll); p += len; } } void cd9660_rrip_NM(cd9660node *node) { cd9660_rrip_add_NM(node, node->node->name); } struct ISO_SUSP_ATTRIBUTES* cd9660_susp_ER(cd9660node *node, u_char ext_version, const char* ext_id, const char* ext_des, const char* ext_src) { int l; struct ISO_SUSP_ATTRIBUTES *r; r = cd9660node_susp_create_node(SUSP_TYPE_SUSP, SUSP_ENTRY_SUSP_ER, "ER", SUSP_LOC_DOT); /* Fixed data is 8 bytes */ r->attr.su_entry.ER.h.length[0] = 8; r->attr.su_entry.ER.h.version[0] = 1; r->attr.su_entry.ER.len_id[0] = (u_char)strlen(ext_id); r->attr.su_entry.ER.len_des[0] = (u_char)strlen(ext_des); r->attr.su_entry.ER.len_src[0] = (u_char)strlen(ext_src); l = r->attr.su_entry.ER.len_id[0] + r->attr.su_entry.ER.len_src[0] + r->attr.su_entry.ER.len_des[0]; /* Everything must fit. */ assert(l + r->attr.su_entry.ER.h.length[0] <= 254); r->attr.su_entry.ER.h.length[0] += (u_char)l; r->attr.su_entry.ER.ext_ver[0] = ext_version; memcpy(r->attr.su_entry.ER.ext_data, ext_id, (int)r->attr.su_entry.ER.len_id[0]); l = (int) r->attr.su_entry.ER.len_id[0]; memcpy(r->attr.su_entry.ER.ext_data + l,ext_des, (int)r->attr.su_entry.ER.len_des[0]); l += (int)r->attr.su_entry.ER.len_des[0]; memcpy(r->attr.su_entry.ER.ext_data + l,ext_src, (int)r->attr.su_entry.ER.len_src[0]); TAILQ_INSERT_TAIL(&node->head, r, rr_ll); return r; } struct ISO_SUSP_ATTRIBUTES* cd9660_susp_ES(struct ISO_SUSP_ATTRIBUTES *last __unused, cd9660node *node __unused) { return NULL; } Index: stable/11/usr.sbin/makefs/cd9660.c =================================================================== --- stable/11/usr.sbin/makefs/cd9660.c (revision 332979) +++ stable/11/usr.sbin/makefs/cd9660.c (revision 332980) @@ -1,2197 +1,2198 @@ /* $NetBSD: cd9660.c,v 1.32 2011/08/23 17:09:11 christos Exp $ */ /*- * SPDX-License-Identifier: BSD-2-Clause-NetBSD AND BSD-4-Clause * * Copyright (c) 2005 Daniel Watt, Walter Deignan, Ryan Gabrys, Alan * Perez-Rathke and Ram Vedam. All rights reserved. * * This code was written by Daniel Watt, Walter Deignan, Ryan Gabrys, * Alan Perez-Rathke and Ram Vedam. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY DANIEL WATT, WALTER DEIGNAN, RYAN * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL DANIEL WATT, WALTER DEIGNAN, RYAN * GABRYS, ALAN PEREZ-RATHKE AND RAM VEDAM BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE,DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. */ /* * Copyright (c) 2001 Wasabi Systems, Inc. * All rights reserved. * * Written by Luke Mewburn for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); -#include -#include #include #include +#include +#include +#include #include "makefs.h" #include "cd9660.h" #include "cd9660/iso9660_rrip.h" #include "cd9660/cd9660_archimedes.h" static void cd9660_finalize_PVD(iso9660_disk *); static cd9660node *cd9660_allocate_cd9660node(void); static void cd9660_set_defaults(iso9660_disk *); static int cd9660_arguments_set_string(const char *, const char *, int, char, char *); static void cd9660_populate_iso_dir_record( struct _iso_directory_record_cd9660 *, u_char, u_char, u_char, const char *); static void cd9660_setup_root_node(iso9660_disk *); static int cd9660_setup_volume_descriptors(iso9660_disk *); #if 0 static int cd9660_fill_extended_attribute_record(cd9660node *); #endif static void cd9660_sort_nodes(cd9660node *); static int cd9660_translate_node_common(iso9660_disk *, cd9660node *); static int cd9660_translate_node(iso9660_disk *, fsnode *, cd9660node *); static int cd9660_compare_filename(const char *, const char *); static void cd9660_sorted_child_insert(cd9660node *, cd9660node *); static int cd9660_handle_collisions(iso9660_disk *, cd9660node *, int); static cd9660node *cd9660_rename_filename(iso9660_disk *, cd9660node *, int, int); static void cd9660_copy_filenames(iso9660_disk *, cd9660node *); static void cd9660_sorting_nodes(cd9660node *); static int cd9660_count_collisions(cd9660node *); static cd9660node *cd9660_rrip_move_directory(iso9660_disk *, cd9660node *); static int cd9660_add_dot_records(iso9660_disk *, cd9660node *); static void cd9660_convert_structure(iso9660_disk *, fsnode *, cd9660node *, int, int *, int *); static void cd9660_free_structure(cd9660node *); static int cd9660_generate_path_table(iso9660_disk *); static int cd9660_level1_convert_filename(iso9660_disk *, const char *, char *, int); static int cd9660_level2_convert_filename(iso9660_disk *, const char *, char *, int); #if 0 static int cd9660_joliet_convert_filename(iso9660_disk *, const char *, char *, int); #endif static int cd9660_convert_filename(iso9660_disk *, const char *, char *, int); static void cd9660_populate_dot_records(iso9660_disk *, cd9660node *); static int64_t cd9660_compute_offsets(iso9660_disk *, cd9660node *, int64_t); #if 0 static int cd9660_copy_stat_info(cd9660node *, cd9660node *, int); #endif static cd9660node *cd9660_create_virtual_entry(iso9660_disk *, const char *, cd9660node *, int, int); static cd9660node *cd9660_create_file(iso9660_disk *, const char *, cd9660node *, cd9660node *); static cd9660node *cd9660_create_directory(iso9660_disk *, const char *, cd9660node *, cd9660node *); static cd9660node *cd9660_create_special_directory(iso9660_disk *, u_char, cd9660node *); /* * Allocate and initialize a cd9660node * @returns struct cd9660node * Pointer to new node, or NULL on error */ static cd9660node * cd9660_allocate_cd9660node(void) { cd9660node *temp; if ((temp = calloc(1, sizeof(cd9660node))) == NULL) err(EXIT_FAILURE, "%s: calloc", __func__); TAILQ_INIT(&temp->cn_children); temp->parent = temp->dot_record = temp->dot_dot_record = NULL; temp->ptnext = temp->ptprev = temp->ptlast = NULL; temp->node = NULL; temp->isoDirRecord = NULL; temp->isoExtAttributes = NULL; temp->rr_real_parent = temp->rr_relocated = NULL; temp->su_tail_data = NULL; return temp; } int cd9660_defaults_set = 0; /** * Set default values for cd9660 extension to makefs */ static void cd9660_set_defaults(iso9660_disk *diskStructure) { /*Fix the sector size for now, though the spec allows for other sizes*/ diskStructure->sectorSize = 2048; /* Set up defaults in our own structure */ diskStructure->verbose_level = 0; diskStructure->keep_bad_images = 0; diskStructure->follow_sym_links = 0; diskStructure->isoLevel = 2; diskStructure->rock_ridge_enabled = 0; diskStructure->rock_ridge_renamed_dir_name = 0; diskStructure->rock_ridge_move_count = 0; diskStructure->rr_moved_dir = 0; diskStructure->archimedes_enabled = 0; diskStructure->chrp_boot = 0; diskStructure->include_padding_areas = 1; /* Spec breaking functionality */ diskStructure->allow_deep_trees = diskStructure->allow_start_dot = diskStructure->allow_max_name = diskStructure->allow_illegal_chars = diskStructure->allow_lowercase = diskStructure->allow_multidot = diskStructure->omit_trailing_period = 0; /* Make sure the PVD is clear */ memset(&diskStructure->primaryDescriptor, 0, 2048); memset(diskStructure->primaryDescriptor.publisher_id, 0x20,128); memset(diskStructure->primaryDescriptor.preparer_id, 0x20,128); memset(diskStructure->primaryDescriptor.application_id, 0x20,128); memset(diskStructure->primaryDescriptor.copyright_file_id, 0x20,37); memset(diskStructure->primaryDescriptor.abstract_file_id, 0x20,37); memset(diskStructure->primaryDescriptor.bibliographic_file_id, 0x20,37); strcpy(diskStructure->primaryDescriptor.system_id, "FreeBSD"); cd9660_defaults_set = 1; /* Boot support: Initially disabled */ diskStructure->has_generic_bootimage = 0; diskStructure->generic_bootimage = NULL; diskStructure->boot_image_directory = 0; /*memset(diskStructure->boot_descriptor, 0, 2048);*/ diskStructure->is_bootable = 0; TAILQ_INIT(&diskStructure->boot_images); LIST_INIT(&diskStructure->boot_entries); } void cd9660_prep_opts(fsinfo_t *fsopts) { iso9660_disk *diskStructure; if ((diskStructure = calloc(1, sizeof(*diskStructure))) == NULL) err(EXIT_FAILURE, "%s: calloc", __func__); #define OPT_STR(letter, name, desc) \ { letter, name, NULL, OPT_STRBUF, 0, 0, desc } #define OPT_NUM(letter, name, field, min, max, desc) \ { letter, name, &diskStructure->field, \ sizeof(diskStructure->field) == 8 ? OPT_INT64 : \ (sizeof(diskStructure->field) == 4 ? OPT_INT32 : \ (sizeof(diskStructure->field) == 2 ? OPT_INT16 : OPT_INT8)), \ min, max, desc } #define OPT_BOOL(letter, name, field, desc) \ OPT_NUM(letter, name, field, 0, 1, desc) const option_t cd9660_options[] = { OPT_NUM('l', "isolevel", isoLevel, 1, 2, "ISO Level"), OPT_NUM('v', "verbose", verbose_level, 0, 2, "Turns on verbose output"), OPT_BOOL('h', "help", displayHelp, "Show help message"), OPT_BOOL('S', "follow-symlinks", follow_sym_links, "Resolve symlinks in pathnames"), OPT_BOOL('R', "rockridge", rock_ridge_enabled, "Enable Rock-Ridge extensions"), OPT_BOOL('C', "chrp-boot", chrp_boot, "Enable CHRP boot"), OPT_BOOL('K', "keep-bad-images", keep_bad_images, "Keep bad images"), OPT_BOOL('D', "allow-deep-trees", allow_deep_trees, "Allow trees more than 8 levels"), OPT_BOOL('a', "allow-max-name", allow_max_name, "Allow 37 char filenames (unimplemented)"), OPT_BOOL('i', "allow-illegal-chars", allow_illegal_chars, "Allow illegal characters in filenames"), OPT_BOOL('d', "allow-multidot", allow_multidot, "Allow multiple periods in filenames"), OPT_BOOL('o', "omit-trailing-period", omit_trailing_period, "Omit trailing periods in filenames"), OPT_BOOL('\0', "allow-lowercase", allow_lowercase, "Allow lowercase characters in filenames"), OPT_BOOL('\0', "archimedes", archimedes_enabled, "Enable Archimedes structure"), OPT_BOOL('\0', "no-trailing-padding", include_padding_areas, "Include padding areas"), OPT_STR('A', "applicationid", "Application Identifier"), OPT_STR('P', "publisher", "Publisher Identifier"), OPT_STR('p', "preparer", "Preparer Identifier"), OPT_STR('L', "label", "Disk Label"), OPT_STR('V', "volumeid", "Volume Set Identifier"), OPT_STR('B', "bootimage", "Boot image parameter"), OPT_STR('G', "generic-bootimage", "Generic boot image param"), OPT_STR('\0', "bootimagedir", "Boot image directory"), OPT_STR('\0', "no-emul-boot", "No boot emulation"), OPT_STR('\0', "no-boot", "No boot support"), OPT_STR('\0', "hard-disk-boot", "Boot from hard disk"), OPT_STR('\0', "boot-load-segment", "Boot load segment"), { .name = NULL } }; fsopts->fs_specific = diskStructure; fsopts->fs_options = copy_opts(cd9660_options); cd9660_set_defaults(diskStructure); } void cd9660_cleanup_opts(fsinfo_t *fsopts) { free(fsopts->fs_specific); free(fsopts->fs_options); } static int cd9660_arguments_set_string(const char *val, const char *fieldtitle, int length, char testmode, char * dest) { int len, test; if (val == NULL) warnx("error: The %s requires a string argument", fieldtitle); else if ((len = strlen(val)) <= length) { if (testmode == 'd') test = cd9660_valid_d_chars(val); else test = cd9660_valid_a_chars(val); if (test) { memcpy(dest, val, len); if (test == 2) cd9660_uppercase_characters(dest, len); return 1; } else warnx("error: The %s must be composed of " "%c-characters", fieldtitle, testmode); } else warnx("error: The %s must be at most 32 characters long", fieldtitle); return 0; } /* * Command-line parsing function */ int cd9660_parse_opts(const char *option, fsinfo_t *fsopts) { int rv, i; iso9660_disk *diskStructure = fsopts->fs_specific; option_t *cd9660_options = fsopts->fs_options; char buf[1024]; const char *name, *desc; assert(option != NULL); if (debug & DEBUG_FS_PARSE_OPTS) printf("cd9660_parse_opts: got `%s'\n", option); i = set_option(cd9660_options, option, buf, sizeof(buf)); if (i == -1) return 0; if (cd9660_options[i].name == NULL) abort(); name = cd9660_options[i].name; desc = cd9660_options[i].desc; switch (cd9660_options[i].letter) { case 'h': case 'S': rv = 0; /* this is not handled yet */ break; case 'L': rv = cd9660_arguments_set_string(buf, desc, 32, 'd', diskStructure->primaryDescriptor.volume_id); break; case 'A': rv = cd9660_arguments_set_string(buf, desc, 128, 'a', diskStructure->primaryDescriptor.application_id); break; case 'P': rv = cd9660_arguments_set_string(buf, desc, 128, 'a', diskStructure->primaryDescriptor.publisher_id); break; case 'p': rv = cd9660_arguments_set_string(buf, desc, 128, 'a', diskStructure->primaryDescriptor.preparer_id); break; case 'V': rv = cd9660_arguments_set_string(buf, desc, 128, 'a', diskStructure->primaryDescriptor.volume_set_id); break; /* Boot options */ case 'B': if (buf[0] == '\0') { warnx("The Boot Image parameter requires a valid boot" "information string"); rv = 0; } else rv = cd9660_add_boot_disk(diskStructure, buf); break; case 'G': if (buf[0] == '\0') { warnx("The Generic Boot Image parameter requires a" " valid boot information string"); rv = 0; } else rv = cd9660_add_generic_bootimage(diskStructure, buf); break; default: if (strcmp(name, "bootimagedir") == 0) { /* * XXXfvdl this is unused. */ if (buf[0] == '\0') { warnx("The Boot Image Directory parameter" " requires a directory name\n"); rv = 0; } else { diskStructure->boot_image_directory = malloc(strlen(buf) + 1); if (diskStructure->boot_image_directory == NULL) err(1, "malloc"); /* BIG TODO: Add the max length function here */ rv = cd9660_arguments_set_string(buf, desc, 12, 'd', diskStructure->boot_image_directory); } } else if (strcmp(name, "no-emul-boot") == 0 || strcmp(name, "no-boot") == 0 || strcmp(name, "hard-disk-boot") == 0) { /* RRIP */ cd9660_eltorito_add_boot_option(diskStructure, name, 0); rv = 1; } else if (strcmp(name, "boot-load-segment") == 0) { if (buf[0] == '\0') { warnx("Option `%s' doesn't contain a value", name); rv = 0; } else { cd9660_eltorito_add_boot_option(diskStructure, name, buf); rv = 1; } } else rv = 1; } return rv; } /* * Main function for cd9660_makefs * Builds the ISO image file * @param const char *image The image filename to create * @param const char *dir The directory that is being read * @param struct fsnode *root The root node of the filesystem tree * @param struct fsinfo_t *fsopts Any options */ void cd9660_makefs(const char *image, const char *dir, fsnode *root, fsinfo_t *fsopts) { int64_t startoffset; int numDirectories; uint64_t pathTableSectors; int64_t firstAvailableSector; int64_t totalSpace; int error; cd9660node *real_root; iso9660_disk *diskStructure = fsopts->fs_specific; if (diskStructure->verbose_level > 0) printf("cd9660_makefs: ISO level is %i\n", diskStructure->isoLevel); if (diskStructure->isoLevel < 2 && diskStructure->allow_multidot) errx(1, "allow-multidot requires iso level of 2\n"); assert(image != NULL); assert(dir != NULL); assert(root != NULL); if (diskStructure->displayHelp) { /* * Display help here - probably want to put it in * a separate function */ return; } if (diskStructure->verbose_level > 0) printf("cd9660_makefs: image %s directory %s root %p\n", image, dir, root); /* Set up some constants. Later, these will be defined with options */ /* Counter needed for path tables */ numDirectories = 0; /* Convert tree to our own format */ /* Actually, we now need to add the REAL root node, at level 0 */ real_root = cd9660_allocate_cd9660node(); if ((real_root->isoDirRecord = malloc( sizeof(iso_directory_record_cd9660) )) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_makefs"); exit(1); } /* Leave filename blank for root */ memset(real_root->isoDirRecord->name, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING); real_root->level = 0; diskStructure->rootNode = real_root; real_root->type = CD9660_TYPE_DIR; error = 0; real_root->node = root; cd9660_convert_structure(diskStructure, root, real_root, 1, &numDirectories, &error); if (TAILQ_EMPTY(&real_root->cn_children)) { errx(1, "cd9660_makefs: converted directory is empty. " "Tree conversion failed\n"); } else if (error != 0) { errx(1, "cd9660_makefs: tree conversion failed\n"); } else { if (diskStructure->verbose_level > 0) printf("cd9660_makefs: tree converted\n"); } /* Add the dot and dot dot records */ cd9660_add_dot_records(diskStructure, real_root); cd9660_setup_root_node(diskStructure); if (diskStructure->verbose_level > 0) printf("cd9660_makefs: done converting tree\n"); /* non-SUSP extensions */ if (diskStructure->archimedes_enabled) archimedes_convert_tree(diskStructure->rootNode); /* Rock ridge / SUSP init pass */ if (diskStructure->rock_ridge_enabled) { cd9660_susp_initialize(diskStructure, diskStructure->rootNode, diskStructure->rootNode, NULL); } /* Build path table structure */ diskStructure->pathTableLength = cd9660_generate_path_table( diskStructure); pathTableSectors = CD9660_BLOCKS(diskStructure->sectorSize, diskStructure->pathTableLength); firstAvailableSector = cd9660_setup_volume_descriptors(diskStructure); if (diskStructure->is_bootable) { firstAvailableSector = cd9660_setup_boot(diskStructure, firstAvailableSector); if (firstAvailableSector < 0) errx(1, "setup_boot failed"); } /* LE first, then BE */ diskStructure->primaryLittleEndianTableSector = firstAvailableSector; diskStructure->primaryBigEndianTableSector = diskStructure->primaryLittleEndianTableSector + pathTableSectors; /* Set the secondary ones to -1, not going to use them for now */ diskStructure->secondaryBigEndianTableSector = -1; diskStructure->secondaryLittleEndianTableSector = -1; diskStructure->dataFirstSector = diskStructure->primaryBigEndianTableSector + pathTableSectors; if (diskStructure->verbose_level > 0) printf("cd9660_makefs: Path table conversion complete. " "Each table is %i bytes, or %" PRIu64 " sectors.\n", diskStructure->pathTableLength, pathTableSectors); startoffset = diskStructure->sectorSize*diskStructure->dataFirstSector; totalSpace = cd9660_compute_offsets(diskStructure, real_root, startoffset); diskStructure->totalSectors = diskStructure->dataFirstSector + CD9660_BLOCKS(diskStructure->sectorSize, totalSpace); /* Disabled until pass 1 is done */ if (diskStructure->rock_ridge_enabled) { diskStructure->susp_continuation_area_start_sector = diskStructure->totalSectors; diskStructure->totalSectors += CD9660_BLOCKS(diskStructure->sectorSize, diskStructure->susp_continuation_area_size); cd9660_susp_finalize(diskStructure, diskStructure->rootNode); } cd9660_finalize_PVD(diskStructure); /* Add padding sectors, just for testing purposes right now */ /* diskStructure->totalSectors+=150; */ /* Debugging output */ if (diskStructure->verbose_level > 0) { printf("cd9660_makefs: Sectors 0-15 reserved\n"); printf("cd9660_makefs: Primary path tables starts in sector %" PRId64 "\n", diskStructure->primaryLittleEndianTableSector); printf("cd9660_makefs: File data starts in sector %" PRId64 "\n", diskStructure->dataFirstSector); printf("cd9660_makefs: Total sectors: %" PRId64 "\n", diskStructure->totalSectors); } /* * Add padding sectors at the end * TODO: Clean this up and separate padding */ if (diskStructure->include_padding_areas) diskStructure->totalSectors += 150; cd9660_write_image(diskStructure, image); if (diskStructure->verbose_level > 1) { debug_print_volume_descriptor_information(diskStructure); debug_print_tree(diskStructure, real_root, 0); debug_print_path_tree(real_root); } /* Clean up data structures */ cd9660_free_structure(real_root); if (diskStructure->verbose_level > 0) printf("cd9660_makefs: done\n"); } /* Generic function pointer - implement later */ typedef int (*cd9660node_func)(cd9660node *); static void cd9660_finalize_PVD(iso9660_disk *diskStructure) { time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL); /* root should be a fixed size of 34 bytes since it has no name */ memcpy(diskStructure->primaryDescriptor.root_directory_record, diskStructure->rootNode->dot_record->isoDirRecord, 34); /* In RRIP, this might be longer than 34 */ diskStructure->primaryDescriptor.root_directory_record[0] = 34; /* Set up all the important numbers in the PVD */ cd9660_bothendian_dword(diskStructure->totalSectors, (unsigned char *)diskStructure->primaryDescriptor.volume_space_size); cd9660_bothendian_word(1, (unsigned char *)diskStructure->primaryDescriptor.volume_set_size); cd9660_bothendian_word(1, (unsigned char *) diskStructure->primaryDescriptor.volume_sequence_number); cd9660_bothendian_word(diskStructure->sectorSize, (unsigned char *) diskStructure->primaryDescriptor.logical_block_size); cd9660_bothendian_dword(diskStructure->pathTableLength, (unsigned char *)diskStructure->primaryDescriptor.path_table_size); cd9660_731(diskStructure->primaryLittleEndianTableSector, (u_char *)diskStructure->primaryDescriptor.type_l_path_table); cd9660_732(diskStructure->primaryBigEndianTableSector, (u_char *)diskStructure->primaryDescriptor.type_m_path_table); diskStructure->primaryDescriptor.file_structure_version[0] = 1; /* Pad all strings with spaces instead of nulls */ cd9660_pad_string_spaces(diskStructure->primaryDescriptor.volume_id, 32); cd9660_pad_string_spaces(diskStructure->primaryDescriptor.system_id, 32); cd9660_pad_string_spaces(diskStructure->primaryDescriptor.volume_set_id, 128); cd9660_pad_string_spaces(diskStructure->primaryDescriptor.publisher_id, 128); cd9660_pad_string_spaces(diskStructure->primaryDescriptor.preparer_id, 128); cd9660_pad_string_spaces(diskStructure->primaryDescriptor.application_id, 128); cd9660_pad_string_spaces( diskStructure->primaryDescriptor.copyright_file_id, 37); cd9660_pad_string_spaces( diskStructure->primaryDescriptor.abstract_file_id, 37); cd9660_pad_string_spaces( diskStructure->primaryDescriptor.bibliographic_file_id, 37); /* Setup dates */ cd9660_time_8426( (unsigned char *)diskStructure->primaryDescriptor.creation_date, tstamp); cd9660_time_8426( (unsigned char *)diskStructure->primaryDescriptor.modification_date, tstamp); #if 0 cd9660_set_date(diskStructure->primaryDescriptor.expiration_date, tstamp); #endif memset(diskStructure->primaryDescriptor.expiration_date, '0', 16); diskStructure->primaryDescriptor.expiration_date[16] = 0; cd9660_time_8426( (unsigned char *)diskStructure->primaryDescriptor.effective_date, tstamp); /* make this sane */ cd9660_time_915(diskStructure->rootNode->dot_record->isoDirRecord->date, tstamp); } static void cd9660_populate_iso_dir_record(struct _iso_directory_record_cd9660 *record, u_char ext_attr_length, u_char flags, u_char name_len, const char * name) { record->ext_attr_length[0] = ext_attr_length; record->flags[0] = ISO_FLAG_CLEAR | flags; record->file_unit_size[0] = 0; record->interleave[0] = 0; cd9660_bothendian_word(1, record->volume_sequence_number); record->name_len[0] = name_len; memset(record->name, '\0', sizeof (record->name)); memcpy(record->name, name, name_len); record->length[0] = 33 + name_len; /* Todo : better rounding */ record->length[0] += (record->length[0] & 1) ? 1 : 0; } static void cd9660_setup_root_node(iso9660_disk *diskStructure) { cd9660_populate_iso_dir_record(diskStructure->rootNode->isoDirRecord, 0, ISO_FLAG_DIRECTORY, 1, "\0"); } /*********** SUPPORT FUNCTIONS ***********/ static int cd9660_setup_volume_descriptors(iso9660_disk *diskStructure) { /* Boot volume descriptor should come second */ int sector = 16; /* For now, a fixed 2 : PVD and terminator */ volume_descriptor *temp, *t; /* Set up the PVD */ if ((temp = malloc(sizeof(volume_descriptor))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors"); exit(1); } temp->volumeDescriptorData = (unsigned char *)&diskStructure->primaryDescriptor; temp->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_PVD; temp->volumeDescriptorData[6] = 1; temp->sector = sector; memcpy(temp->volumeDescriptorData + 1, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5); diskStructure->firstVolumeDescriptor = temp; sector++; /* Set up boot support if enabled. BVD must reside in sector 17 */ if (diskStructure->is_bootable) { if ((t = malloc(sizeof(volume_descriptor))) == NULL) { CD9660_MEM_ALLOC_ERROR( "cd9660_setup_volume_descriptors"); exit(1); } if ((t->volumeDescriptorData = malloc(2048)) == NULL) { CD9660_MEM_ALLOC_ERROR( "cd9660_setup_volume_descriptors"); exit(1); } temp->next = t; temp = t; memset(t->volumeDescriptorData, 0, 2048); t->sector = 17; if (diskStructure->verbose_level > 0) printf("Setting up boot volume descriptor\n"); cd9660_setup_boot_volume_descriptor(diskStructure, t); sector++; } /* Set up the terminator */ if ((t = malloc(sizeof(volume_descriptor))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors"); exit(1); } if ((t->volumeDescriptorData = malloc(2048)) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_setup_volume_descriptors"); exit(1); } temp->next = t; memset(t->volumeDescriptorData, 0, 2048); t->volumeDescriptorData[0] = ISO_VOLUME_DESCRIPTOR_TERMINATOR; t->next = NULL; t->volumeDescriptorData[6] = 1; t->sector = sector; memcpy(t->volumeDescriptorData + 1, ISO_VOLUME_DESCRIPTOR_STANDARD_ID, 5); sector++; return sector; } #if 0 /* * Populate EAR at some point. Not required, but is used by NetBSD's * cd9660 support */ static int cd9660_fill_extended_attribute_record(cd9660node *node) { if ((node->isoExtAttributes = malloc(sizeof(struct iso_extended_attributes))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_fill_extended_attribute_record"); exit(1); }; return 1; } #endif static int cd9660_translate_node_common(iso9660_disk *diskStructure, cd9660node *newnode) { time_t tstamp = stampst.st_ino ? stampst.st_mtime : time(NULL); int test; u_char flag; char temp[ISO_FILENAME_MAXLENGTH_WITH_PADDING]; /* Now populate the isoDirRecord structure */ memset(temp, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING); test = cd9660_convert_filename(diskStructure, newnode->node->name, temp, !(S_ISDIR(newnode->node->type))); flag = ISO_FLAG_CLEAR; if (S_ISDIR(newnode->node->type)) flag |= ISO_FLAG_DIRECTORY; cd9660_populate_iso_dir_record(newnode->isoDirRecord, 0, flag, strlen(temp), temp); /* Set the various dates */ /* If we want to use the current date and time */ cd9660_time_915(newnode->isoDirRecord->date, tstamp); cd9660_bothendian_dword(newnode->fileDataLength, newnode->isoDirRecord->size); /* If the file is a link, we want to set the size to 0 */ if (S_ISLNK(newnode->node->type)) newnode->fileDataLength = 0; return 1; } /* * Translate fsnode to cd9660node * Translate filenames and other metadata, including dates, sizes, * permissions, etc * @param struct fsnode * The node generated by makefs * @param struct cd9660node * The intermediate node to be written to * @returns int 0 on failure, 1 on success */ static int cd9660_translate_node(iso9660_disk *diskStructure, fsnode *node, cd9660node *newnode) { if (node == NULL) { if (diskStructure->verbose_level > 0) printf("cd9660_translate_node: NULL node passed, " "returning\n"); return 0; } if ((newnode->isoDirRecord = malloc(sizeof(iso_directory_record_cd9660))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_translate_node"); return 0; } /* Set the node pointer */ newnode->node = node; /* Set the size */ if (!(S_ISDIR(node->type))) newnode->fileDataLength = node->inode->st.st_size; if (cd9660_translate_node_common(diskStructure, newnode) == 0) return 0; /* Finally, overwrite some of the values that are set by default */ cd9660_time_915(newnode->isoDirRecord->date, stampst.st_ino ? stampst.st_mtime : node->inode->st.st_mtime); return 1; } /* * Compares two ISO filenames * @param const char * The first file name * @param const char * The second file name * @returns : -1 if first is less than second, 0 if they are the same, 1 if * the second is greater than the first */ static int cd9660_compare_filename(const char *first, const char *second) { /* * This can be made more optimal once it has been tested * (the extra character, for example, is for testing) */ int p1 = 0; int p2 = 0; char c1, c2; /* First, on the filename */ while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1 && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION-1) { c1 = first[p1]; c2 = second[p2]; if (c1 == '.' && c2 =='.') break; else if (c1 == '.') { p2++; c1 = ' '; } else if (c2 == '.') { p1++; c2 = ' '; } else { p1++; p2++; } if (c1 < c2) return -1; else if (c1 > c2) { return 1; } } if (first[p1] == '.' && second[p2] == '.') { p1++; p2++; while (p1 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1 && p2 < ISO_FILENAME_MAXLENGTH_BEFORE_VERSION - 1) { c1 = first[p1]; c2 = second[p2]; if (c1 == ';' && c2 == ';') break; else if (c1 == ';') { p2++; c1 = ' '; } else if (c2 == ';') { p1++; c2 = ' '; } else { p1++; p2++; } if (c1 < c2) return -1; else if (c1 > c2) return 1; } } return 0; } /* * Insert a node into list with ISO sorting rules * @param cd9660node * The head node of the list * @param cd9660node * The node to be inserted */ static void cd9660_sorted_child_insert(cd9660node *parent, cd9660node *cn_new) { int compare; cd9660node *cn; struct cd9660_children_head *head = &parent->cn_children; /* TODO: Optimize? */ cn_new->parent = parent; /* * first will either be 0, the . or the .. * if . or .., this means no other entry may be written before first * if 0, the new node may be inserted at the head */ TAILQ_FOREACH(cn, head, cn_next_child) { /* * Dont insert a node twice - * that would cause an infinite loop */ if (cn_new == cn) return; compare = cd9660_compare_filename(cn_new->isoDirRecord->name, cn->isoDirRecord->name); if (compare == 0) compare = cd9660_compare_filename(cn_new->node->name, cn->node->name); if (compare < 0) break; } if (cn == NULL) TAILQ_INSERT_TAIL(head, cn_new, cn_next_child); else TAILQ_INSERT_BEFORE(cn, cn_new, cn_next_child); } /* * Called After cd9660_sorted_child_insert * handles file collisions by suffixing each filname with ~n * where n represents the files respective place in the ordering */ static int cd9660_handle_collisions(iso9660_disk *diskStructure, cd9660node *colliding, int past) { cd9660node *iter, *next, *prev; int skip; int delete_chars = 0; int temp_past = past; int temp_skip; int flag = 0; cd9660node *end_of_range; for (iter = TAILQ_FIRST(&colliding->cn_children); iter != NULL && (next = TAILQ_NEXT(iter, cn_next_child)) != NULL;) { if (strcmp(iter->isoDirRecord->name, next->isoDirRecord->name) != 0) { iter = TAILQ_NEXT(iter, cn_next_child); continue; } flag = 1; temp_skip = skip = cd9660_count_collisions(iter); end_of_range = iter; while (temp_skip > 0) { temp_skip--; end_of_range = TAILQ_NEXT(end_of_range, cn_next_child); } temp_past = past; while (temp_past > 0) { if ((next = TAILQ_NEXT(end_of_range, cn_next_child)) != NULL) end_of_range = next; else if ((prev = TAILQ_PREV(iter, cd9660_children_head, cn_next_child)) != NULL) iter = prev; else delete_chars++; temp_past--; } skip += past; iter = cd9660_rename_filename(diskStructure, iter, skip, delete_chars); } return flag; } static cd9660node * cd9660_rename_filename(iso9660_disk *diskStructure, cd9660node *iter, int num, int delete_chars) { int i = 0; int numbts, digit, digits, temp, powers, count; char *naming; int maxlength; char *tmp; if (diskStructure->verbose_level > 0) printf("Rename_filename called\n"); assert(1 <= diskStructure->isoLevel && diskStructure->isoLevel <= 2); /* TODO : A LOT of chanes regarding 8.3 filenames */ if (diskStructure->isoLevel == 1) maxlength = 8; else if (diskStructure->isoLevel == 2) maxlength = 31; else maxlength = ISO_FILENAME_MAXLENGTH_BEFORE_VERSION; tmp = malloc(ISO_FILENAME_MAXLENGTH_WITH_PADDING); while (i < num && iter) { powers = 1; count = 0; digits = 1; while (((int)(i / powers) ) >= 10) { digits++; powers = powers * 10; } naming = iter->o_name; /* while ((*naming != '.') && (*naming != ';')) { naming++; count++; } */ while (count < maxlength) { if (*naming == ';') break; naming++; count++; } if ((count + digits) < maxlength) numbts = count; else numbts = maxlength - (digits); numbts -= delete_chars; /* 8.3 rules - keep the extension, add before the dot */ /* * This code makes a bunch of assumptions. * See if you can spot them all :) */ /* if (diskStructure->isoLevel == 1) { numbts = 8 - digits - delete_chars; if (dot < 0) { } else { if (dot < 8) { memmove(&tmp[numbts],&tmp[dot],4); } } } */ /* (copying just the filename before the '.' */ memcpy(tmp, (iter->o_name), numbts); /* adding the appropriate number following the name */ temp = i; while (digits > 0) { digit = (int)(temp / powers); temp = temp - digit * powers; sprintf(&tmp[numbts] , "%d", digit); digits--; numbts++; powers = powers / 10; } while ((*naming != ';') && (numbts < maxlength)) { tmp[numbts] = (*naming); naming++; numbts++; } tmp[numbts] = ';'; tmp[numbts+1] = '1'; tmp[numbts+2] = '\0'; /* * now tmp has exactly the identifier * we want so we'll copy it back to record */ memcpy((iter->isoDirRecord->name), tmp, numbts + 3); iter = TAILQ_NEXT(iter, cn_next_child); i++; } free(tmp); return iter; } /* Todo: Figure out why these functions are nec. */ static void cd9660_copy_filenames(iso9660_disk *diskStructure, cd9660node *node) { cd9660node *cn; if (TAILQ_EMPTY(&node->cn_children)) return; if (TAILQ_FIRST(&node->cn_children)->isoDirRecord == NULL) { debug_print_tree(diskStructure, diskStructure->rootNode, 0); exit(1); } TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) { cd9660_copy_filenames(diskStructure, cn); memcpy(cn->o_name, cn->isoDirRecord->name, ISO_FILENAME_MAXLENGTH_WITH_PADDING); } } static void cd9660_sorting_nodes(cd9660node *node) { cd9660node *cn; TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) cd9660_sorting_nodes(cn); cd9660_sort_nodes(node); } /* XXX Bubble sort. */ static void cd9660_sort_nodes(cd9660node *node) { cd9660node *cn, *next; do { TAILQ_FOREACH(cn, &node->cn_children, cn_next_child) { if ((next = TAILQ_NEXT(cn, cn_next_child)) == NULL) return; else if (strcmp(next->isoDirRecord->name, cn->isoDirRecord->name) >= 0) continue; TAILQ_REMOVE(&node->cn_children, next, cn_next_child); TAILQ_INSERT_BEFORE(cn, next, cn_next_child); break; } } while (cn != NULL); } static int cd9660_count_collisions(cd9660node *copy) { int count = 0; cd9660node *iter, *next; for (iter = copy; (next = TAILQ_NEXT(iter, cn_next_child)) != NULL; iter = next) { if (cd9660_compare_filename(iter->isoDirRecord->name, next->isoDirRecord->name) == 0) count++; else return count; } #if 0 if ((next = TAILQ_NEXT(iter, cn_next_child)) != NULL) { printf("cd9660_recurse_on_collision: count is %i \n", count); compare = cd9660_compare_filename(iter->isoDirRecord->name, next->isoDirRecord->name); if (compare == 0) { count++; return cd9660_recurse_on_collision(next, count); } else return count; } #endif return count; } static cd9660node * cd9660_rrip_move_directory(iso9660_disk *diskStructure, cd9660node *dir) { char newname[9]; cd9660node *tfile; /* * This function needs to: * 1) Create an empty virtual file in place of the old directory * 2) Point the virtual file to the new directory * 3) Point the relocated directory to its old parent * 4) Move the directory specified by dir into rr_moved_dir, * and rename it to "diskStructure->rock_ridge_move_count" (as a string) */ /* First see if the moved directory even exists */ if (diskStructure->rr_moved_dir == NULL) { diskStructure->rr_moved_dir = cd9660_create_directory( diskStructure, ISO_RRIP_DEFAULT_MOVE_DIR_NAME, diskStructure->rootNode, dir); if (diskStructure->rr_moved_dir == NULL) return 0; cd9660_time_915(diskStructure->rr_moved_dir->isoDirRecord->date, stampst.st_ino ? stampst.st_mtime : start_time.tv_sec); } /* Create a file with the same ORIGINAL name */ tfile = cd9660_create_file(diskStructure, dir->node->name, dir->parent, dir); if (tfile == NULL) return NULL; diskStructure->rock_ridge_move_count++; snprintf(newname, sizeof(newname), "%08i", diskStructure->rock_ridge_move_count); /* Point to old parent */ dir->rr_real_parent = dir->parent; /* Place the placeholder file */ if (TAILQ_EMPTY(&dir->rr_real_parent->cn_children)) { TAILQ_INSERT_HEAD(&dir->rr_real_parent->cn_children, tfile, cn_next_child); } else { cd9660_sorted_child_insert(dir->rr_real_parent, tfile); } /* Point to new parent */ dir->parent = diskStructure->rr_moved_dir; /* Point the file to the moved directory */ tfile->rr_relocated = dir; /* Actually move the directory */ cd9660_sorted_child_insert(diskStructure->rr_moved_dir, dir); /* TODO: Inherit permissions / ownership (basically the entire inode) */ /* Set the new name */ memset(dir->isoDirRecord->name, 0, ISO_FILENAME_MAXLENGTH_WITH_PADDING); strncpy(dir->isoDirRecord->name, newname, 8); dir->isoDirRecord->length[0] = 34 + 8; dir->isoDirRecord->name_len[0] = 8; return dir; } static int cd9660_add_dot_records(iso9660_disk *diskStructure, cd9660node *root) { struct cd9660_children_head *head = &root->cn_children; cd9660node *cn; TAILQ_FOREACH(cn, head, cn_next_child) { if ((cn->type & CD9660_TYPE_DIR) == 0) continue; /* Recursion first */ cd9660_add_dot_records(diskStructure, cn); } cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOT, root); cd9660_create_special_directory(diskStructure, CD9660_TYPE_DOTDOT, root); return 1; } /* * Convert node to cd9660 structure * This function is designed to be called recursively on the root node of * the filesystem * Lots of recursion going on here, want to make sure it is efficient * @param struct fsnode * The root node to be converted * @param struct cd9660* The parent node (should not be NULL) * @param int Current directory depth * @param int* Running count of the number of directories that are being created */ static void cd9660_convert_structure(iso9660_disk *diskStructure, fsnode *root, cd9660node *parent_node, int level, int *numDirectories, int *error) { fsnode *iterator = root; cd9660node *this_node; int working_level; int add; int flag = 0; int counter = 0; /* * Newer, more efficient method, reduces recursion depth */ if (root == NULL) { warnx("%s: root is null\n", __func__); return; } /* Test for an empty directory - makefs still gives us the . record */ if ((S_ISDIR(root->type)) && (root->name[0] == '.') && (root->name[1] == '\0')) { root = root->next; if (root == NULL) return; } if ((this_node = cd9660_allocate_cd9660node()) == NULL) { CD9660_MEM_ALLOC_ERROR(__func__); } /* * To reduce the number of recursive calls, we will iterate over * the next pointers to the right. */ while (iterator != NULL) { add = 1; /* * Increment the directory count if this is a directory * Ignore "." entries. We will generate them later */ if (!S_ISDIR(iterator->type) || strcmp(iterator->name, ".") != 0) { /* Translate the node, including its filename */ this_node->parent = parent_node; cd9660_translate_node(diskStructure, iterator, this_node); this_node->level = level; if (S_ISDIR(iterator->type)) { (*numDirectories)++; this_node->type = CD9660_TYPE_DIR; working_level = level + 1; /* * If at level 8, directory would be at 8 * and have children at 9 which is not * allowed as per ISO spec */ if (level == 8) { if ((!diskStructure->allow_deep_trees) && (!diskStructure->rock_ridge_enabled)) { warnx("error: found entry " "with depth greater " "than 8."); (*error) = 1; return; } else if (diskStructure-> rock_ridge_enabled) { working_level = 3; /* * Moved directory is actually * at level 2. */ this_node->level = working_level - 1; if (cd9660_rrip_move_directory( diskStructure, this_node) == NULL) { warnx("Failure in " "cd9660_rrip_" "move_directory" ); (*error) = 1; return; } add = 0; } } /* Do the recursive call on the children */ if (iterator->child != NULL) { cd9660_convert_structure(diskStructure, iterator->child, this_node, working_level, numDirectories, error); if ((*error) == 1) { warnx("%s: Error on recursive " "call", __func__); return; } } } else { /* Only directories should have children */ assert(iterator->child == NULL); this_node->type = CD9660_TYPE_FILE; } /* * Finally, do a sorted insert */ if (add) { cd9660_sorted_child_insert( parent_node, this_node); } /*Allocate new temp_node */ if (iterator->next != NULL) { this_node = cd9660_allocate_cd9660node(); if (this_node == NULL) CD9660_MEM_ALLOC_ERROR(__func__); } } iterator = iterator->next; } /* cd9660_handle_collisions(first_node); */ /* TODO: need cleanup */ cd9660_copy_filenames(diskStructure, parent_node); do { flag = cd9660_handle_collisions(diskStructure, parent_node, counter); counter++; cd9660_sorting_nodes(parent_node); } while ((flag == 1) && (counter < 100)); } /* * Clean up the cd9660node tree * This is designed to be called recursively on the root node * @param struct cd9660node *root The node to free * @returns void */ static void cd9660_free_structure(cd9660node *root) { cd9660node *cn; while ((cn = TAILQ_FIRST(&root->cn_children)) != NULL) { TAILQ_REMOVE(&root->cn_children, cn, cn_next_child); cd9660_free_structure(cn); } free(root); } /* * Be a little more memory conservative: * instead of having the TAILQ_ENTRY as part of the cd9660node, * just create a temporary structure */ struct ptq_entry { TAILQ_ENTRY(ptq_entry) ptq; cd9660node *node; } *n; #define PTQUEUE_NEW(n,s,r,t){\ n = malloc(sizeof(struct s)); \ if (n == NULL) \ return r; \ n->node = t;\ } /* * Generate the path tables * The specific implementation of this function is left as an exercise to the * programmer. It could be done recursively. Make sure you read how the path * table has to be laid out, it has levels. * @param struct iso9660_disk *disk The disk image * @returns int The number of built path tables (between 1 and 4), 0 on failure */ static int cd9660_generate_path_table(iso9660_disk *diskStructure) { cd9660node *cn, *dirNode = diskStructure->rootNode; cd9660node *last = dirNode; int pathTableSize = 0; /* computed as we go */ int counter = 1; /* root gets a count of 0 */ TAILQ_HEAD(cd9660_pt_head, ptq_entry) pt_head; TAILQ_INIT(&pt_head); PTQUEUE_NEW(n, ptq_entry, -1, diskStructure->rootNode); /* Push the root node */ TAILQ_INSERT_HEAD(&pt_head, n, ptq); /* Breadth-first traversal of file structure */ while (pt_head.tqh_first != 0) { n = pt_head.tqh_first; dirNode = n->node; TAILQ_REMOVE(&pt_head, pt_head.tqh_first, ptq); free(n); /* Update the size */ pathTableSize += ISO_PATHTABLE_ENTRY_BASESIZE + dirNode->isoDirRecord->name_len[0]+ (dirNode->isoDirRecord->name_len[0] % 2 == 0 ? 0 : 1); /* includes the padding bit */ dirNode->ptnumber=counter; if (dirNode != last) { last->ptnext = dirNode; dirNode->ptprev = last; } last = dirNode; /* Push children onto queue */ TAILQ_FOREACH(cn, &dirNode->cn_children, cn_next_child) { /* * Dont add the DOT and DOTDOT types to the path * table. */ if ((cn->type != CD9660_TYPE_DOT) && (cn->type != CD9660_TYPE_DOTDOT)) { if (S_ISDIR(cn->node->type)) { PTQUEUE_NEW(n, ptq_entry, -1, cn); TAILQ_INSERT_TAIL(&pt_head, n, ptq); } } } counter++; } return pathTableSize; } void cd9660_compute_full_filename(cd9660node *node, char *buf) { int len; len = CD9660MAXPATH + 1; len = snprintf(buf, len, "%s/%s/%s", node->node->root, node->node->path, node->node->name); if (len > CD9660MAXPATH) errx(1, "Pathname too long."); } /* NEW filename conversion method */ typedef int(*cd9660_filename_conversion_functor)(iso9660_disk *, const char *, char *, int); /* * TODO: These two functions are almost identical. * Some code cleanup is possible here * * XXX bounds checking! */ static int cd9660_level1_convert_filename(iso9660_disk *diskStructure, const char *oldname, char *newname, int is_file) { /* * ISO 9660 : 10.1 * File Name shall not contain more than 8 d or d1 characters * File Name Extension shall not contain more than 3 d or d1 characters * Directory Identifier shall not contain more than 8 d or d1 characters */ int namelen = 0; int extlen = 0; int found_ext = 0; while (*oldname != '\0' && extlen < 3) { /* Handle period first, as it is special */ if (*oldname == '.') { if (found_ext) { *newname++ = '_'; extlen ++; } else { *newname++ = '.'; found_ext = 1; } } else { /* cut RISC OS file type off ISO name */ if (diskStructure->archimedes_enabled && *oldname == ',' && strlen(oldname) == 4) break; /* Enforce 12.3 / 8 */ if (namelen == 8 && !found_ext) break; if (islower((unsigned char)*oldname)) *newname++ = toupper((unsigned char)*oldname); else if (isupper((unsigned char)*oldname) || isdigit((unsigned char)*oldname)) *newname++ = *oldname; else *newname++ = '_'; if (found_ext) extlen++; else namelen++; } oldname++; } if (is_file) { if (!found_ext && !diskStructure->omit_trailing_period) *newname++ = '.'; /* Add version */ sprintf(newname, ";%i", 1); } return namelen + extlen + found_ext; } /* XXX bounds checking! */ static int cd9660_level2_convert_filename(iso9660_disk *diskStructure, const char *oldname, char *newname, int is_file) { /* * ISO 9660 : 7.5.1 * File name : 0+ d or d1 characters * separator 1 (.) * File name extension : 0+ d or d1 characters * separator 2 (;) * File version number (5 characters, 1-32767) * 1 <= Sum of File name and File name extension <= 30 */ int namelen = 0; int extlen = 0; int found_ext = 0; while (*oldname != '\0' && namelen + extlen < 30) { /* Handle period first, as it is special */ if (*oldname == '.') { if (found_ext) { if (diskStructure->allow_multidot) { *newname++ = '.'; } else { *newname++ = '_'; } extlen ++; } else { *newname++ = '.'; found_ext = 1; } } else { /* cut RISC OS file type off ISO name */ if (diskStructure->archimedes_enabled && *oldname == ',' && strlen(oldname) == 4) break; if (islower((unsigned char)*oldname)) *newname++ = toupper((unsigned char)*oldname); else if (isupper((unsigned char)*oldname) || isdigit((unsigned char)*oldname)) *newname++ = *oldname; else if (diskStructure->allow_multidot && *oldname == '.') { *newname++ = '.'; } else { *newname++ = '_'; } if (found_ext) extlen++; else namelen++; } oldname ++; } if (is_file) { if (!found_ext && !diskStructure->omit_trailing_period) *newname++ = '.'; /* Add version */ sprintf(newname, ";%i", 1); } return namelen + extlen + found_ext; } #if 0 static int cd9660_joliet_convert_filename(iso9660_disk *diskStructure, const char *oldname, char *newname, int is_file) { /* TODO: implement later, move to cd9660_joliet.c ?? */ } #endif /* * Convert a file name to ISO compliant file name * @param char * oldname The original filename * @param char ** newname The new file name, in the appropriate character * set and of appropriate length * @param int 1 if file, 0 if directory * @returns int The length of the new string */ static int cd9660_convert_filename(iso9660_disk *diskStructure, const char *oldname, char *newname, int is_file) { assert(1 <= diskStructure->isoLevel && diskStructure->isoLevel <= 2); /* NEW */ cd9660_filename_conversion_functor conversion_function = NULL; if (diskStructure->isoLevel == 1) conversion_function = &cd9660_level1_convert_filename; else if (diskStructure->isoLevel == 2) conversion_function = &cd9660_level2_convert_filename; return (*conversion_function)(diskStructure, oldname, newname, is_file); } int cd9660_compute_record_size(iso9660_disk *diskStructure, cd9660node *node) { int size = node->isoDirRecord->length[0]; if (diskStructure->rock_ridge_enabled) size += node->susp_entry_size; size += node->su_tail_size; size += size & 1; /* Ensure length of record is even. */ assert(size <= 254); return size; } static void cd9660_populate_dot_records(iso9660_disk *diskStructure, cd9660node *node) { node->dot_record->fileDataSector = node->fileDataSector; memcpy(node->dot_record->isoDirRecord,node->isoDirRecord, 34); node->dot_record->isoDirRecord->name_len[0] = 1; node->dot_record->isoDirRecord->name[0] = 0; node->dot_record->isoDirRecord->name[1] = 0; node->dot_record->isoDirRecord->length[0] = 34; node->dot_record->fileRecordSize = cd9660_compute_record_size(diskStructure, node->dot_record); if (node == diskStructure->rootNode) { node->dot_dot_record->fileDataSector = node->fileDataSector; memcpy(node->dot_dot_record->isoDirRecord,node->isoDirRecord, 34); } else { node->dot_dot_record->fileDataSector = node->parent->fileDataSector; memcpy(node->dot_dot_record->isoDirRecord, node->parent->isoDirRecord,34); } node->dot_dot_record->isoDirRecord->name_len[0] = 1; node->dot_dot_record->isoDirRecord->name[0] = 1; node->dot_dot_record->isoDirRecord->name[1] = 0; node->dot_dot_record->isoDirRecord->length[0] = 34; node->dot_dot_record->fileRecordSize = cd9660_compute_record_size(diskStructure, node->dot_dot_record); } /* * @param struct cd9660node *node The node * @param int The offset (in bytes) - SHOULD align to the beginning of a sector * @returns int The total size of files and directory entries (should be * a multiple of sector size) */ static int64_t cd9660_compute_offsets(iso9660_disk *diskStructure, cd9660node *node, int64_t startOffset) { /* * This function needs to compute the size of directory records and * runs, file lengths, and set the appropriate variables both in * cd9660node and isoDirEntry */ int64_t used_bytes = 0; int64_t current_sector_usage = 0; cd9660node *child; fsinode *inode; int64_t r; assert(node != NULL); /* * NOTE : There needs to be some special case detection for * the "real root" node, since for it, node->node is undefined */ node->fileDataSector = -1; if (node->type & CD9660_TYPE_DIR) { node->fileRecordSize = cd9660_compute_record_size( diskStructure, node); /*Set what sector this directory starts in*/ node->fileDataSector = CD9660_BLOCKS(diskStructure->sectorSize,startOffset); cd9660_bothendian_dword(node->fileDataSector, node->isoDirRecord->extent); /* * First loop over children, need to know the size of * their directory records */ node->fileSectorsUsed = 1; TAILQ_FOREACH(child, &node->cn_children, cn_next_child) { node->fileDataLength += cd9660_compute_record_size(diskStructure, child); if ((cd9660_compute_record_size(diskStructure, child) + current_sector_usage) >= diskStructure->sectorSize) { current_sector_usage = 0; node->fileSectorsUsed++; } current_sector_usage += cd9660_compute_record_size(diskStructure, child); } cd9660_bothendian_dword(node->fileSectorsUsed * diskStructure->sectorSize,node->isoDirRecord->size); /* * This should point to the sector after the directory * record (or, the first byte in that sector) */ used_bytes += node->fileSectorsUsed * diskStructure->sectorSize; for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child); child != NULL; child = TAILQ_NEXT(child, cn_next_child)) { /* Directories need recursive call */ if (S_ISDIR(child->node->type)) { r = cd9660_compute_offsets(diskStructure, child, used_bytes + startOffset); if (r != -1) used_bytes += r; else return -1; } } /* Explicitly set the . and .. records */ cd9660_populate_dot_records(diskStructure, node); /* Finally, do another iteration to write the file data*/ for (child = TAILQ_NEXT(node->dot_dot_record, cn_next_child); child != NULL; child = TAILQ_NEXT(child, cn_next_child)) { /* Files need extent set */ if (S_ISDIR(child->node->type)) continue; child->fileRecordSize = cd9660_compute_record_size(diskStructure, child); child->fileSectorsUsed = CD9660_BLOCKS(diskStructure->sectorSize, child->fileDataLength); inode = child->node->inode; if ((inode->flags & FI_ALLOCATED) == 0) { inode->ino = CD9660_BLOCKS(diskStructure->sectorSize, used_bytes + startOffset); inode->flags |= FI_ALLOCATED; used_bytes += child->fileSectorsUsed * diskStructure->sectorSize; } else { INODE_WARNX(("%s: already allocated inode %d " "data sectors at %" PRIu32, __func__, (int)inode->st.st_ino, inode->ino)); } child->fileDataSector = inode->ino; cd9660_bothendian_dword(child->fileDataSector, child->isoDirRecord->extent); } } return used_bytes; } #if 0 /* Might get rid of this func */ static int cd9660_copy_stat_info(cd9660node *from, cd9660node *to, int file) { to->node->inode->st.st_dev = 0; to->node->inode->st.st_ino = 0; to->node->inode->st.st_size = 0; to->node->inode->st.st_blksize = from->node->inode->st.st_blksize; to->node->inode->st.st_atime = from->node->inode->st.st_atime; to->node->inode->st.st_mtime = from->node->inode->st.st_mtime; to->node->inode->st.st_ctime = from->node->inode->st.st_ctime; to->node->inode->st.st_uid = from->node->inode->st.st_uid; to->node->inode->st.st_gid = from->node->inode->st.st_gid; to->node->inode->st.st_mode = from->node->inode->st.st_mode; /* Clear out type */ to->node->inode->st.st_mode = to->node->inode->st.st_mode & ~(S_IFMT); if (file) to->node->inode->st.st_mode |= S_IFREG; else to->node->inode->st.st_mode |= S_IFDIR; return 1; } #endif static cd9660node * cd9660_create_virtual_entry(iso9660_disk *diskStructure, const char *name, cd9660node *parent, int file, int insert) { cd9660node *temp; fsnode * tfsnode; assert(parent != NULL); temp = cd9660_allocate_cd9660node(); if (temp == NULL) return NULL; if ((tfsnode = malloc(sizeof(fsnode))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry"); return NULL; } /* Assume for now name is a valid length */ if ((tfsnode->name = malloc(strlen(name) + 1)) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry"); return NULL; } if ((temp->isoDirRecord = malloc(sizeof(iso_directory_record_cd9660))) == NULL) { CD9660_MEM_ALLOC_ERROR("cd9660_create_virtual_entry"); return NULL; } strcpy(tfsnode->name, name); cd9660_convert_filename(diskStructure, tfsnode->name, temp->isoDirRecord->name, file); temp->node = tfsnode; temp->parent = parent; if (insert) { if (temp->parent != NULL) { temp->level = temp->parent->level + 1; if (!TAILQ_EMPTY(&temp->parent->cn_children)) cd9660_sorted_child_insert(temp->parent, temp); else TAILQ_INSERT_HEAD(&temp->parent->cn_children, temp, cn_next_child); } } if (parent->node != NULL) { tfsnode->type = parent->node->type; } /* Clear out file type bits */ tfsnode->type &= ~(S_IFMT); if (file) tfsnode->type |= S_IFREG; else tfsnode->type |= S_IFDIR; /* Indicate that there is no spec entry (inode) */ tfsnode->flags &= ~(FSNODE_F_HASSPEC); #if 0 cd9660_copy_stat_info(parent, temp, file); #endif return temp; } static cd9660node * cd9660_create_file(iso9660_disk *diskStructure, const char *name, cd9660node *parent, cd9660node *me) { cd9660node *temp; temp = cd9660_create_virtual_entry(diskStructure, name, parent, 1, 1); if (temp == NULL) return NULL; temp->fileDataLength = 0; temp->type = CD9660_TYPE_FILE | CD9660_TYPE_VIRTUAL; if ((temp->node->inode = calloc(1, sizeof(fsinode))) == NULL) return NULL; *temp->node->inode = *me->node->inode; if (cd9660_translate_node_common(diskStructure, temp) == 0) return NULL; return temp; } /* * Create a new directory which does not exist on disk * @param const char * name The name to assign to the directory * @param const char * parent Pointer to the parent directory * @returns cd9660node * Pointer to the new directory */ static cd9660node * cd9660_create_directory(iso9660_disk *diskStructure, const char *name, cd9660node *parent, cd9660node *me) { cd9660node *temp; temp = cd9660_create_virtual_entry(diskStructure, name, parent, 0, 1); if (temp == NULL) return NULL; temp->node->type |= S_IFDIR; temp->type = CD9660_TYPE_DIR | CD9660_TYPE_VIRTUAL; if ((temp->node->inode = calloc(1, sizeof(fsinode))) == NULL) return NULL; *temp->node->inode = *me->node->inode; if (cd9660_translate_node_common(diskStructure, temp) == 0) return NULL; return temp; } static cd9660node * cd9660_create_special_directory(iso9660_disk *diskStructure, u_char type, cd9660node *parent) { cd9660node *temp, *first; char na[2]; assert(parent != NULL); if (type == CD9660_TYPE_DOT) na[0] = 0; else if (type == CD9660_TYPE_DOTDOT) na[0] = 1; else return 0; na[1] = 0; if ((temp = cd9660_create_virtual_entry(diskStructure, na, parent, 0, 0)) == NULL) return NULL; temp->parent = parent; temp->type = type; temp->isoDirRecord->length[0] = 34; /* Dot record is always first */ if (type == CD9660_TYPE_DOT) { parent->dot_record = temp; TAILQ_INSERT_HEAD(&parent->cn_children, temp, cn_next_child); /* DotDot should be second */ } else if (type == CD9660_TYPE_DOTDOT) { parent->dot_dot_record = temp; /* * If the first child is the dot record, insert * this second. Otherwise, insert it at the head. */ if ((first = TAILQ_FIRST(&parent->cn_children)) == NULL || (first->type & CD9660_TYPE_DOT) == 0) { TAILQ_INSERT_HEAD(&parent->cn_children, temp, cn_next_child); } else { TAILQ_INSERT_AFTER(&parent->cn_children, first, temp, cn_next_child); } } return temp; } int cd9660_add_generic_bootimage(iso9660_disk *diskStructure, const char *bootimage) { struct stat stbuf; assert(bootimage != NULL); if (*bootimage == '\0') { warnx("Error: Boot image must be a filename"); return 0; } if ((diskStructure->generic_bootimage = strdup(bootimage)) == NULL) { warn("%s: strdup", __func__); return 0; } /* Get information about the file */ if (lstat(diskStructure->generic_bootimage, &stbuf) == -1) err(EXIT_FAILURE, "%s: lstat(\"%s\")", __func__, diskStructure->generic_bootimage); if (stbuf.st_size > 32768) { warnx("Error: Boot image must be no greater than 32768 bytes"); return 0; } if (diskStructure->verbose_level > 0) { printf("Generic boot image image has size %lld\n", (long long)stbuf.st_size); } diskStructure->has_generic_bootimage = 1; return 1; } Index: stable/11/usr.sbin/makefs/ffs/ffs_bswap.c =================================================================== --- stable/11/usr.sbin/makefs/ffs/ffs_bswap.c (revision 332979) +++ stable/11/usr.sbin/makefs/ffs/ffs_bswap.c (revision 332980) @@ -1,265 +1,266 @@ /* $NetBSD: ffs_bswap.c,v 1.28 2004/05/25 14:54:59 hannken Exp $ */ /*- * SPDX-License-Identifier: BSD-2-Clause-NetBSD * * Copyright (c) 1998 Manuel Bouyer. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Manuel Bouyer. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); #include #if defined(_KERNEL) #include #endif -#include -#include "ffs/ufs_bswap.h" -#include - #if !defined(_KERNEL) #include +#include #include #include #include #define panic(x) printf("%s\n", (x)), abort() #endif + +#include +#include "ffs/ufs_bswap.h" +#include #define fs_old_postbloff fs_spare5[0] #define fs_old_rotbloff fs_spare5[1] #define fs_old_postbl_start fs_maxbsize #define fs_old_headswitch fs_id[0] #define fs_old_trkseek fs_id[1] #define fs_old_csmask fs_spare1[0] #define fs_old_csshift fs_spare1[1] #define FS_42POSTBLFMT -1 /* 4.2BSD rotational table format */ #define FS_DYNAMICPOSTBLFMT 1 /* dynamic rotational table format */ void ffs_csum_swap(struct csum *o, struct csum *n, int size); void ffs_csumtotal_swap(struct csum_total *o, struct csum_total *n); void ffs_sb_swap(struct fs *o, struct fs *n) { size_t i; u_int32_t *o32, *n32; /* * In order to avoid a lot of lines, as the first N fields (52) * of the superblock up to fs_fmod are u_int32_t, we just loop * here to convert them. */ o32 = (u_int32_t *)o; n32 = (u_int32_t *)n; for (i = 0; i < offsetof(struct fs, fs_fmod) / sizeof(u_int32_t); i++) n32[i] = bswap32(o32[i]); n->fs_swuid = bswap64(o->fs_swuid); n->fs_cgrotor = bswap32(o->fs_cgrotor); /* Unused */ n->fs_old_cpc = bswap32(o->fs_old_cpc); /* These fields overlap with a possible location for the * historic FS_DYNAMICPOSTBLFMT postbl table, and with the * first half of the historic FS_42POSTBLFMT postbl table. */ n->fs_maxbsize = bswap32(o->fs_maxbsize); n->fs_sblockloc = bswap64(o->fs_sblockloc); ffs_csumtotal_swap(&o->fs_cstotal, &n->fs_cstotal); n->fs_time = bswap64(o->fs_time); n->fs_size = bswap64(o->fs_size); n->fs_dsize = bswap64(o->fs_dsize); n->fs_csaddr = bswap64(o->fs_csaddr); n->fs_pendingblocks = bswap64(o->fs_pendingblocks); n->fs_pendinginodes = bswap32(o->fs_pendinginodes); /* These fields overlap with the second half of the * historic FS_42POSTBLFMT postbl table */ for (i = 0; i < FSMAXSNAP; i++) n->fs_snapinum[i] = bswap32(o->fs_snapinum[i]); n->fs_avgfilesize = bswap32(o->fs_avgfilesize); n->fs_avgfpdir = bswap32(o->fs_avgfpdir); /* fs_sparecon[28] - ignore for now */ n->fs_flags = bswap32(o->fs_flags); n->fs_contigsumsize = bswap32(o->fs_contigsumsize); n->fs_maxsymlinklen = bswap32(o->fs_maxsymlinklen); n->fs_old_inodefmt = bswap32(o->fs_old_inodefmt); n->fs_maxfilesize = bswap64(o->fs_maxfilesize); n->fs_qbmask = bswap64(o->fs_qbmask); n->fs_qfmask = bswap64(o->fs_qfmask); n->fs_state = bswap32(o->fs_state); n->fs_old_postblformat = bswap32(o->fs_old_postblformat); n->fs_old_nrpos = bswap32(o->fs_old_nrpos); n->fs_old_postbloff = bswap32(o->fs_old_postbloff); n->fs_old_rotbloff = bswap32(o->fs_old_rotbloff); n->fs_magic = bswap32(o->fs_magic); } void ffs_dinode1_swap(struct ufs1_dinode *o, struct ufs1_dinode *n) { n->di_mode = bswap16(o->di_mode); n->di_nlink = bswap16(o->di_nlink); n->di_size = bswap64(o->di_size); n->di_atime = bswap32(o->di_atime); n->di_atimensec = bswap32(o->di_atimensec); n->di_mtime = bswap32(o->di_mtime); n->di_mtimensec = bswap32(o->di_mtimensec); n->di_ctime = bswap32(o->di_ctime); n->di_ctimensec = bswap32(o->di_ctimensec); memcpy(n->di_db, o->di_db, sizeof(n->di_db)); memcpy(n->di_ib, o->di_ib, sizeof(n->di_ib)); n->di_flags = bswap32(o->di_flags); n->di_blocks = bswap32(o->di_blocks); n->di_gen = bswap32(o->di_gen); n->di_uid = bswap32(o->di_uid); n->di_gid = bswap32(o->di_gid); } void ffs_dinode2_swap(struct ufs2_dinode *o, struct ufs2_dinode *n) { n->di_mode = bswap16(o->di_mode); n->di_nlink = bswap16(o->di_nlink); n->di_uid = bswap32(o->di_uid); n->di_gid = bswap32(o->di_gid); n->di_blksize = bswap32(o->di_blksize); n->di_size = bswap64(o->di_size); n->di_blocks = bswap64(o->di_blocks); n->di_atime = bswap64(o->di_atime); n->di_atimensec = bswap32(o->di_atimensec); n->di_mtime = bswap64(o->di_mtime); n->di_mtimensec = bswap32(o->di_mtimensec); n->di_ctime = bswap64(o->di_ctime); n->di_ctimensec = bswap32(o->di_ctimensec); n->di_birthtime = bswap64(o->di_ctime); n->di_birthnsec = bswap32(o->di_ctimensec); n->di_gen = bswap32(o->di_gen); n->di_kernflags = bswap32(o->di_kernflags); n->di_flags = bswap32(o->di_flags); n->di_extsize = bswap32(o->di_extsize); memcpy(n->di_extb, o->di_extb, sizeof(n->di_extb)); memcpy(n->di_db, o->di_db, sizeof(n->di_db)); memcpy(n->di_ib, o->di_ib, sizeof(n->di_ib)); } void ffs_csum_swap(struct csum *o, struct csum *n, int size) { size_t i; u_int32_t *oint, *nint; oint = (u_int32_t*)o; nint = (u_int32_t*)n; for (i = 0; i < size / sizeof(u_int32_t); i++) nint[i] = bswap32(oint[i]); } void ffs_csumtotal_swap(struct csum_total *o, struct csum_total *n) { n->cs_ndir = bswap64(o->cs_ndir); n->cs_nbfree = bswap64(o->cs_nbfree); n->cs_nifree = bswap64(o->cs_nifree); n->cs_nffree = bswap64(o->cs_nffree); } /* * Note that ffs_cg_swap may be called with o == n. */ void ffs_cg_swap(struct cg *o, struct cg *n, struct fs *fs) { int i; u_int32_t *n32, *o32; u_int16_t *n16, *o16; int32_t btotoff, boff, clustersumoff; n->cg_firstfield = bswap32(o->cg_firstfield); n->cg_magic = bswap32(o->cg_magic); n->cg_old_time = bswap32(o->cg_old_time); n->cg_cgx = bswap32(o->cg_cgx); n->cg_old_ncyl = bswap16(o->cg_old_ncyl); n->cg_old_niblk = bswap16(o->cg_old_niblk); n->cg_ndblk = bswap32(o->cg_ndblk); n->cg_cs.cs_ndir = bswap32(o->cg_cs.cs_ndir); n->cg_cs.cs_nbfree = bswap32(o->cg_cs.cs_nbfree); n->cg_cs.cs_nifree = bswap32(o->cg_cs.cs_nifree); n->cg_cs.cs_nffree = bswap32(o->cg_cs.cs_nffree); n->cg_rotor = bswap32(o->cg_rotor); n->cg_frotor = bswap32(o->cg_frotor); n->cg_irotor = bswap32(o->cg_irotor); for (i = 0; i < MAXFRAG; i++) n->cg_frsum[i] = bswap32(o->cg_frsum[i]); n->cg_old_btotoff = bswap32(o->cg_old_btotoff); n->cg_old_boff = bswap32(o->cg_old_boff); n->cg_iusedoff = bswap32(o->cg_iusedoff); n->cg_freeoff = bswap32(o->cg_freeoff); n->cg_nextfreeoff = bswap32(o->cg_nextfreeoff); n->cg_clustersumoff = bswap32(o->cg_clustersumoff); n->cg_clusteroff = bswap32(o->cg_clusteroff); n->cg_nclusterblks = bswap32(o->cg_nclusterblks); n->cg_niblk = bswap32(o->cg_niblk); n->cg_initediblk = bswap32(o->cg_initediblk); n->cg_time = bswap64(o->cg_time); if (fs->fs_magic == FS_UFS2_MAGIC) return; if (n->cg_magic == CG_MAGIC) { btotoff = n->cg_old_btotoff; boff = n->cg_old_boff; clustersumoff = n->cg_clustersumoff; } else { btotoff = bswap32(n->cg_old_btotoff); boff = bswap32(n->cg_old_boff); clustersumoff = bswap32(n->cg_clustersumoff); } n32 = (u_int32_t *)((u_int8_t *)n + btotoff); o32 = (u_int32_t *)((u_int8_t *)o + btotoff); n16 = (u_int16_t *)((u_int8_t *)n + boff); o16 = (u_int16_t *)((u_int8_t *)o + boff); for (i = 0; i < fs->fs_old_cpg; i++) n32[i] = bswap32(o32[i]); for (i = 0; i < fs->fs_old_cpg * fs->fs_old_nrpos; i++) n16[i] = bswap16(o16[i]); n32 = (u_int32_t *)((u_int8_t *)n + clustersumoff); o32 = (u_int32_t *)((u_int8_t *)o + clustersumoff); for (i = 1; i < fs->fs_contigsumsize + 1; i++) n32[i] = bswap32(o32[i]); } Index: stable/11/usr.sbin/makefs/ffs/ffs_subr.c =================================================================== --- stable/11/usr.sbin/makefs/ffs/ffs_subr.c (revision 332979) +++ stable/11/usr.sbin/makefs/ffs/ffs_subr.c (revision 332980) @@ -1,193 +1,194 @@ /* $NetBSD: ffs_subr.c,v 1.32 2003/12/30 12:33:24 pk Exp $ */ /* * Copyright (c) 1982, 1986, 1989, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * @(#)ffs_subr.c 8.5 (Berkeley) 3/21/95 */ #include __FBSDID("$FreeBSD$"); #include +#include #include #include #include "ffs/ffs_extern.h" #include "ffs/ufs_bswap.h" /* * Update the frsum fields to reflect addition or deletion * of some frags. */ void ffs_fragacct_swap(struct fs *fs, int fragmap, int32_t fraglist[], int cnt, int needswap) { int inblk; int field, subfield; int siz, pos; inblk = (int)(fragtbl[fs->fs_frag][fragmap]) << 1; fragmap <<= 1; for (siz = 1; siz < fs->fs_frag; siz++) { if ((inblk & (1 << (siz + (fs->fs_frag & (NBBY - 1))))) == 0) continue; field = around[siz]; subfield = inside[siz]; for (pos = siz; pos <= fs->fs_frag; pos++) { if ((fragmap & field) == subfield) { fraglist[siz] = ufs_rw32( ufs_rw32(fraglist[siz], needswap) + cnt, needswap); pos += siz; field <<= siz; subfield <<= siz; } field <<= 1; subfield <<= 1; } } } /* * block operations * * check if a block is available * returns true if all the corresponding bits in the free map are 1 * returns false if any corresponding bit in the free map is 0 */ int ffs_isblock(fs, cp, h) struct fs *fs; u_char *cp; int32_t h; { u_char mask; switch ((int)fs->fs_fragshift) { case 3: return (cp[h] == 0xff); case 2: mask = 0x0f << ((h & 0x1) << 2); return ((cp[h >> 1] & mask) == mask); case 1: mask = 0x03 << ((h & 0x3) << 1); return ((cp[h >> 2] & mask) == mask); case 0: mask = 0x01 << (h & 0x7); return ((cp[h >> 3] & mask) == mask); default: panic("ffs_isblock: unknown fs_fragshift %d", (int)fs->fs_fragshift); } } /* * check if a block is completely allocated * returns true if all the corresponding bits in the free map are 0 * returns false if any corresponding bit in the free map is 1 */ int ffs_isfreeblock(fs, cp, h) struct fs *fs; u_char *cp; int32_t h; { switch ((int)fs->fs_fragshift) { case 3: return (cp[h] == 0); case 2: return ((cp[h >> 1] & (0x0f << ((h & 0x1) << 2))) == 0); case 1: return ((cp[h >> 2] & (0x03 << ((h & 0x3) << 1))) == 0); case 0: return ((cp[h >> 3] & (0x01 << (h & 0x7))) == 0); default: panic("ffs_isfreeblock: unknown fs_fragshift %d", (int)fs->fs_fragshift); } } /* * take a block out of the map */ void ffs_clrblock(fs, cp, h) struct fs *fs; u_char *cp; int32_t h; { switch ((int)fs->fs_fragshift) { case 3: cp[h] = 0; return; case 2: cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2)); return; case 1: cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1)); return; case 0: cp[h >> 3] &= ~(0x01 << (h & 0x7)); return; default: panic("ffs_clrblock: unknown fs_fragshift %d", (int)fs->fs_fragshift); } } /* * put a block into the map */ void ffs_setblock(fs, cp, h) struct fs *fs; u_char *cp; int32_t h; { switch ((int)fs->fs_fragshift) { case 3: cp[h] = 0xff; return; case 2: cp[h >> 1] |= (0x0f << ((h & 0x1) << 2)); return; case 1: cp[h >> 2] |= (0x03 << ((h & 0x3) << 1)); return; case 0: cp[h >> 3] |= (0x01 << (h & 0x7)); return; default: panic("ffs_setblock: unknown fs_fragshift %d", (int)fs->fs_fragshift); } } Index: stable/11/usr.sbin/makefs/mtree.c =================================================================== --- stable/11/usr.sbin/makefs/mtree.c (revision 332979) +++ stable/11/usr.sbin/makefs/mtree.c (revision 332980) @@ -1,1122 +1,1127 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2011 Marcel Moolenaar * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include +#include #include #include #include "makefs.h" + +#ifndef ENOATTR +#define ENOATTR ENOMSG +#endif #define IS_DOT(nm) ((nm)[0] == '.' && (nm)[1] == '\0') #define IS_DOTDOT(nm) ((nm)[0] == '.' && (nm)[1] == '.' && (nm)[2] == '\0') struct mtree_fileinfo { SLIST_ENTRY(mtree_fileinfo) next; FILE *fp; const char *name; u_int line; }; /* Global state used while parsing. */ static SLIST_HEAD(, mtree_fileinfo) mtree_fileinfo = SLIST_HEAD_INITIALIZER(mtree_fileinfo); static fsnode *mtree_root; static fsnode *mtree_current; static fsnode mtree_global; static fsinode mtree_global_inode; static u_int errors, warnings; static void mtree_error(const char *, ...) __printflike(1, 2); static void mtree_warning(const char *, ...) __printflike(1, 2); static int mtree_file_push(const char *name, FILE *fp) { struct mtree_fileinfo *fi; fi = malloc(sizeof(*fi)); if (fi == NULL) return (ENOMEM); if (strcmp(name, "-") == 0) fi->name = strdup("(stdin)"); else fi->name = strdup(name); if (fi->name == NULL) { free(fi); return (ENOMEM); } fi->fp = fp; fi->line = 0; SLIST_INSERT_HEAD(&mtree_fileinfo, fi, next); return (0); } static void mtree_print(const char *msgtype, const char *fmt, va_list ap) { struct mtree_fileinfo *fi; if (msgtype != NULL) { fi = SLIST_FIRST(&mtree_fileinfo); if (fi != NULL) fprintf(stderr, "%s:%u: ", fi->name, fi->line); fprintf(stderr, "%s: ", msgtype); } vfprintf(stderr, fmt, ap); } static void mtree_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); mtree_print("error", fmt, ap); va_end(ap); errors++; fputc('\n', stderr); } static void mtree_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); mtree_print("warning", fmt, ap); va_end(ap); warnings++; fputc('\n', stderr); } #ifndef MAKEFS_MAX_TREE_DEPTH # define MAKEFS_MAX_TREE_DEPTH (MAXPATHLEN/2) #endif /* construct path to node->name */ static char * mtree_file_path(fsnode *node) { fsnode *pnode; struct sbuf *sb; char *res, *rp[MAKEFS_MAX_TREE_DEPTH]; int depth; depth = 0; rp[depth] = node->name; for (pnode = node->parent; pnode && depth < MAKEFS_MAX_TREE_DEPTH - 1; pnode = pnode->parent) { if (strcmp(pnode->name, ".") == 0) break; rp[++depth] = pnode->name; } sb = sbuf_new_auto(); if (sb == NULL) { errno = ENOMEM; return (NULL); } while (depth > 0) { sbuf_cat(sb, rp[depth--]); sbuf_putc(sb, '/'); } sbuf_cat(sb, rp[depth]); sbuf_finish(sb); res = strdup(sbuf_data(sb)); sbuf_delete(sb); if (res == NULL) errno = ENOMEM; return res; } /* mtree_resolve() sets errno to indicate why NULL was returned. */ static char * mtree_resolve(const char *spec, int *istemp) { struct sbuf *sb; char *res, *var = NULL; const char *base, *p, *v; size_t len; int c, error, quoted, subst; len = strlen(spec); if (len == 0) { errno = EINVAL; return (NULL); } c = (len > 1) ? (spec[0] == spec[len - 1]) ? spec[0] : 0 : 0; *istemp = (c == '`') ? 1 : 0; subst = (c == '`' || c == '"') ? 1 : 0; quoted = (subst || c == '\'') ? 1 : 0; if (!subst) { res = strdup(spec + quoted); if (res != NULL && quoted) res[len - 2] = '\0'; return (res); } sb = sbuf_new_auto(); if (sb == NULL) { errno = ENOMEM; return (NULL); } base = spec + 1; len -= 2; error = 0; while (len > 0) { p = strchr(base, '$'); if (p == NULL) { sbuf_bcat(sb, base, len); base += len; len = 0; continue; } /* The following is safe. spec always starts with a quote. */ if (p[-1] == '\\') p--; if (base != p) { sbuf_bcat(sb, base, p - base); len -= p - base; base = p; } if (*p == '\\') { sbuf_putc(sb, '$'); base += 2; len -= 2; continue; } /* Skip the '$'. */ base++; len--; /* Handle ${X} vs $X. */ v = base; if (*base == '{') { p = strchr(v, '}'); if (p == NULL) p = v; } else p = v; len -= (p + 1) - base; base = p + 1; if (v == p) { sbuf_putc(sb, *v); continue; } error = ENOMEM; var = calloc(p - v, 1); if (var == NULL) break; memcpy(var, v + 1, p - v - 1); if (strcmp(var, ".CURDIR") == 0) { res = getcwd(NULL, 0); if (res == NULL) break; } else if (strcmp(var, ".PROG") == 0) { res = strdup(getprogname()); if (res == NULL) break; } else { v = getenv(var); if (v != NULL) { res = strdup(v); if (res == NULL) break; } else res = NULL; } error = 0; if (res != NULL) { sbuf_cat(sb, res); free(res); } free(var); var = NULL; } free(var); sbuf_finish(sb); res = (error == 0) ? strdup(sbuf_data(sb)) : NULL; sbuf_delete(sb); if (res == NULL) errno = ENOMEM; return (res); } static int skip_over(FILE *fp, const char *cs) { int c; c = getc(fp); while (c != EOF && strchr(cs, c) != NULL) c = getc(fp); if (c != EOF) { ungetc(c, fp); return (0); } return (ferror(fp) ? errno : -1); } static int skip_to(FILE *fp, const char *cs) { int c; c = getc(fp); while (c != EOF && strchr(cs, c) == NULL) c = getc(fp); if (c != EOF) { ungetc(c, fp); return (0); } return (ferror(fp) ? errno : -1); } static int read_word(FILE *fp, char *buf, size_t bufsz) { struct mtree_fileinfo *fi; size_t idx, qidx; int c, done, error, esc, qlvl; if (bufsz == 0) return (EINVAL); done = 0; esc = 0; idx = 0; qidx = -1; qlvl = 0; do { c = getc(fp); switch (c) { case EOF: buf[idx] = '\0'; error = ferror(fp) ? errno : -1; if (error == -1) mtree_error("unexpected end of file"); return (error); case '#': /* comment -- skip to end of line. */ if (!esc) { error = skip_to(fp, "\n"); if (!error) continue; } break; case '\\': esc++; break; case '`': case '\'': case '"': if (esc) break; if (qlvl == 0) { qlvl++; qidx = idx; } else if (c == buf[qidx]) { qlvl--; if (qlvl > 0) { do { qidx--; } while (buf[qidx] != '`' && buf[qidx] != '\'' && buf[qidx] != '"'); } else qidx = -1; } else { qlvl++; qidx = idx; } break; case ' ': case '\t': case '\n': if (!esc && qlvl == 0) { ungetc(c, fp); c = '\0'; done = 1; break; } if (c == '\n') { /* * We going to eat the newline ourselves. */ if (qlvl > 0) mtree_warning("quoted word straddles " "onto next line."); fi = SLIST_FIRST(&mtree_fileinfo); fi->line++; } break; default: if (esc) buf[idx++] = '\\'; break; } buf[idx++] = c; esc = 0; } while (idx < bufsz && !done); if (idx >= bufsz) { mtree_error("word too long to fit buffer (max %zu characters)", bufsz); skip_to(fp, " \t\n"); } return (0); } static fsnode * create_node(const char *name, u_int type, fsnode *parent, fsnode *global) { fsnode *n; n = calloc(1, sizeof(*n)); if (n == NULL) return (NULL); n->name = strdup(name); if (n->name == NULL) { free(n); return (NULL); } n->type = (type == 0) ? global->type : type; n->parent = parent; n->inode = calloc(1, sizeof(*n->inode)); if (n->inode == NULL) { free(n->name); free(n); return (NULL); } /* Assign global options/defaults. */ bcopy(global->inode, n->inode, sizeof(*n->inode)); n->inode->st.st_mode = (n->inode->st.st_mode & ~S_IFMT) | n->type; if (n->type == S_IFLNK) n->symlink = global->symlink; else if (n->type == S_IFREG) n->contents = global->contents; return (n); } static void destroy_node(fsnode *n) { assert(n != NULL); assert(n->name != NULL); assert(n->inode != NULL); free(n->inode); free(n->name); free(n); } static int read_number(const char *tok, u_int base, intmax_t *res, intmax_t min, intmax_t max) { char *end; intmax_t val; val = strtoimax(tok, &end, base); if (end == tok || end[0] != '\0') return (EINVAL); if (val < min || val > max) return (EDOM); *res = val; return (0); } static int read_mtree_keywords(FILE *fp, fsnode *node) { char keyword[PATH_MAX]; char *name, *p, *value; gid_t gid; uid_t uid; struct stat *st, sb; intmax_t num; u_long flset, flclr; int error, istemp, type; st = &node->inode->st; do { error = skip_over(fp, " \t"); if (error) break; error = read_word(fp, keyword, sizeof(keyword)); if (error) break; if (keyword[0] == '\0') break; value = strchr(keyword, '='); if (value != NULL) *value++ = '\0'; /* * We use EINVAL, ENOATTR, ENOSYS and ENXIO to signal * certain conditions: * EINVAL - Value provided for a keyword that does * not take a value. The value is ignored. * ENOATTR - Value missing for a keyword that needs * a value. The keyword is ignored. * ENOSYS - Unsupported keyword encountered. The * keyword is ignored. * ENXIO - Value provided for a keyword that does * not take a value. The value is ignored. */ switch (keyword[0]) { case 'c': if (strcmp(keyword, "contents") == 0) { if (value == NULL) { error = ENOATTR; break; } node->contents = strdup(value); } else error = ENOSYS; break; case 'f': if (strcmp(keyword, "flags") == 0) { if (value == NULL) { error = ENOATTR; break; } flset = flclr = 0; if (!strtofflags(&value, &flset, &flclr)) { st->st_flags &= ~flclr; st->st_flags |= flset; } else error = errno; } else error = ENOSYS; break; case 'g': if (strcmp(keyword, "gid") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, UINT_MAX); if (!error) st->st_gid = num; } else if (strcmp(keyword, "gname") == 0) { if (value == NULL) { error = ENOATTR; break; } if (gid_from_group(value, &gid) == 0) st->st_gid = gid; else error = EINVAL; } else error = ENOSYS; break; case 'l': if (strcmp(keyword, "link") == 0) { if (value == NULL) { error = ENOATTR; break; } node->symlink = malloc(strlen(value) + 1); if (node->symlink == NULL) { error = errno; break; } if (strunvis(node->symlink, value) < 0) { error = errno; break; } } else error = ENOSYS; break; case 'm': if (strcmp(keyword, "mode") == 0) { if (value == NULL) { error = ENOATTR; break; } if (value[0] >= '0' && value[0] <= '9') { error = read_number(value, 8, &num, 0, 07777); if (!error) { st->st_mode &= S_IFMT; st->st_mode |= num; } } else { /* Symbolic mode not supported. */ error = EINVAL; break; } } else error = ENOSYS; break; case 'o': if (strcmp(keyword, "optional") == 0) { if (value != NULL) error = ENXIO; node->flags |= FSNODE_F_OPTIONAL; } else error = ENOSYS; break; case 's': if (strcmp(keyword, "size") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, INTMAX_MAX); if (!error) st->st_size = num; } else error = ENOSYS; break; case 't': if (strcmp(keyword, "time") == 0) { if (value == NULL) { error = ENOATTR; break; } p = strchr(value, '.'); if (p != NULL) *p++ = '\0'; error = read_number(value, 10, &num, 0, INTMAX_MAX); if (error) break; st->st_atime = num; st->st_ctime = num; st->st_mtime = num; if (p == NULL) break; error = read_number(p, 10, &num, 0, INTMAX_MAX); if (error) break; if (num != 0) error = EINVAL; } else if (strcmp(keyword, "type") == 0) { if (value == NULL) { error = ENOATTR; break; } if (strcmp(value, "dir") == 0) node->type = S_IFDIR; else if (strcmp(value, "file") == 0) node->type = S_IFREG; else if (strcmp(value, "link") == 0) node->type = S_IFLNK; else error = EINVAL; } else error = ENOSYS; break; case 'u': if (strcmp(keyword, "uid") == 0) { if (value == NULL) { error = ENOATTR; break; } error = read_number(value, 10, &num, 0, UINT_MAX); if (!error) st->st_uid = num; } else if (strcmp(keyword, "uname") == 0) { if (value == NULL) { error = ENOATTR; break; } if (uid_from_user(value, &uid) == 0) st->st_uid = uid; else error = EINVAL; } else error = ENOSYS; break; default: error = ENOSYS; break; } switch (error) { case EINVAL: mtree_error("%s: invalid value '%s'", keyword, value); break; case ENOATTR: mtree_error("%s: keyword needs a value", keyword); break; case ENOSYS: mtree_warning("%s: unsupported keyword", keyword); break; case ENXIO: mtree_error("%s: keyword does not take a value", keyword); break; } } while (1); if (error) return (error); st->st_mode = (st->st_mode & ~S_IFMT) | node->type; /* Nothing more to do for the global defaults. */ if (node->name == NULL) return (0); /* * Be intelligent about the file type. */ if (node->contents != NULL) { if (node->symlink != NULL) { mtree_error("%s: both link and contents keywords " "defined", node->name); return (0); } type = S_IFREG; } else if (node->type != 0) { type = node->type; if (type == S_IFREG) { /* the named path is the default contents */ node->contents = mtree_file_path(node); } } else type = (node->symlink != NULL) ? S_IFLNK : S_IFDIR; if (node->type == 0) node->type = type; if (node->type != type) { mtree_error("%s: file type and defined keywords to not match", node->name); return (0); } st->st_mode = (st->st_mode & ~S_IFMT) | node->type; if (node->contents == NULL) return (0); name = mtree_resolve(node->contents, &istemp); if (name == NULL) return (errno); if (stat(name, &sb) != 0) { mtree_error("%s: contents file '%s' not found", node->name, name); free(name); return (0); } /* * Check for hardlinks. If the contents key is used, then the check * will only trigger if the contents file is a link even if it is used * by more than one file */ if (sb.st_nlink > 1) { fsinode *curino; st->st_ino = sb.st_ino; st->st_dev = sb.st_dev; curino = link_check(node->inode); if (curino != NULL) { free(node->inode); node->inode = curino; node->inode->nlink++; } } free(node->contents); node->contents = name; st->st_size = sb.st_size; return (0); } static int read_mtree_command(FILE *fp) { char cmd[10]; int error; error = read_word(fp, cmd, sizeof(cmd)); if (error) goto out; error = read_mtree_keywords(fp, &mtree_global); out: skip_to(fp, "\n"); (void)getc(fp); return (error); } static int read_mtree_spec1(FILE *fp, bool def, const char *name) { fsnode *last, *node, *parent; u_int type; int error; assert(name[0] != '\0'); /* * Treat '..' specially, because it only changes our current * directory. We don't create a node for it. We simply ignore * any keywords that may appear on the line as well. * Going up a directory is a little non-obvious. A directory * node has a corresponding '.' child. The parent of '.' is * not the '.' node of the parent directory, but the directory * node within the parent to which the child relates. However, * going up a directory means we need to find the '.' node to * which the directoy node is linked. This we can do via the * first * pointer, because '.' is always the first entry in a * directory. */ if (IS_DOTDOT(name)) { /* This deals with NULL pointers as well. */ if (mtree_current == mtree_root) { mtree_warning("ignoring .. in root directory"); return (0); } node = mtree_current; assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); /* Get the corresponding directory node in the parent. */ node = mtree_current->parent; assert(node != NULL); assert(!IS_DOT(node->name)); node = node->first; assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); mtree_current = node; return (0); } /* * If we don't have a current directory and the first specification * (either implicit or defined) is not '.', then we need to create * a '.' node first (using a recursive call). */ if (!IS_DOT(name) && mtree_current == NULL) { error = read_mtree_spec1(fp, false, "."); if (error) return (error); } /* * Lookup the name in the current directory (if we have a current * directory) to make sure we do not create multiple nodes for the * same component. For non-definitions, if we find a node with the * same name, simply change the current directory. For definitions * more happens. */ last = NULL; node = mtree_current; while (node != NULL) { assert(node->first == mtree_current); if (strcmp(name, node->name) == 0) { if (def == true) { if (!dupsok) mtree_error( "duplicate definition of %s", name); else mtree_warning( "duplicate definition of %s", name); return (0); } if (node->type != S_IFDIR) { mtree_error("%s is not a directory", name); return (0); } assert(!IS_DOT(name)); node = node->child; assert(node != NULL); assert(IS_DOT(node->name)); mtree_current = node; return (0); } last = node; node = last->next; } parent = (mtree_current != NULL) ? mtree_current->parent : NULL; type = (def == false || IS_DOT(name)) ? S_IFDIR : 0; node = create_node(name, type, parent, &mtree_global); if (node == NULL) return (ENOMEM); if (def == true) { error = read_mtree_keywords(fp, node); if (error) { destroy_node(node); return (error); } } node->first = (mtree_current != NULL) ? mtree_current : node; if (last != NULL) last->next = node; if (node->type != S_IFDIR) return (0); if (!IS_DOT(node->name)) { parent = node; node = create_node(".", S_IFDIR, parent, parent); if (node == NULL) { last->next = NULL; destroy_node(parent); return (ENOMEM); } parent->child = node; node->first = node; } assert(node != NULL); assert(IS_DOT(node->name)); assert(node->first == node); mtree_current = node; if (mtree_root == NULL) mtree_root = node; return (0); } static int read_mtree_spec(FILE *fp) { char pathspec[PATH_MAX], pathtmp[4*PATH_MAX + 1]; char *cp; int error; error = read_word(fp, pathtmp, sizeof(pathtmp)); if (error) goto out; if (strnunvis(pathspec, PATH_MAX, pathtmp) == -1) { error = errno; goto out; } error = 0; cp = strchr(pathspec, '/'); if (cp != NULL) { /* Absolute pathname */ mtree_current = mtree_root; do { *cp++ = '\0'; /* Disallow '..' as a component. */ if (IS_DOTDOT(pathspec)) { mtree_error("absolute path cannot contain " ".. component"); goto out; } /* Ignore multiple adjacent slashes and '.'. */ if (pathspec[0] != '\0' && !IS_DOT(pathspec)) error = read_mtree_spec1(fp, false, pathspec); memmove(pathspec, cp, strlen(cp) + 1); cp = strchr(pathspec, '/'); } while (!error && cp != NULL); /* Disallow '.' and '..' as the last component. */ if (!error && (IS_DOT(pathspec) || IS_DOTDOT(pathspec))) { mtree_error("absolute path cannot contain . or .. " "components"); goto out; } } /* Ignore absolute specfications that end with a slash. */ if (!error && pathspec[0] != '\0') error = read_mtree_spec1(fp, true, pathspec); out: skip_to(fp, "\n"); (void)getc(fp); return (error); } fsnode * read_mtree(const char *fname, fsnode *node) { struct mtree_fileinfo *fi; FILE *fp; int c, error; /* We do not yet support nesting... */ assert(node == NULL); if (strcmp(fname, "-") == 0) fp = stdin; else { fp = fopen(fname, "r"); if (fp == NULL) err(1, "Can't open `%s'", fname); } error = mtree_file_push(fname, fp); if (error) goto out; bzero(&mtree_global, sizeof(mtree_global)); bzero(&mtree_global_inode, sizeof(mtree_global_inode)); mtree_global.inode = &mtree_global_inode; mtree_global_inode.nlink = 1; mtree_global_inode.st.st_nlink = 1; mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime = mtree_global_inode.st.st_mtime = time(NULL); errors = warnings = 0; setgroupent(1); setpassent(1); mtree_root = node; mtree_current = node; do { /* Start of a new line... */ fi = SLIST_FIRST(&mtree_fileinfo); fi->line++; error = skip_over(fp, " \t"); if (error) break; c = getc(fp); if (c == EOF) { error = ferror(fp) ? errno : -1; break; } switch (c) { case '\n': /* empty line */ error = 0; break; case '#': /* comment -- skip to end of line. */ error = skip_to(fp, "\n"); if (!error) (void)getc(fp); break; case '/': /* special commands */ error = read_mtree_command(fp); break; default: /* specification */ ungetc(c, fp); error = read_mtree_spec(fp); break; } } while (!error); endpwent(); endgrent(); if (error <= 0 && (errors || warnings)) { warnx("%u error(s) and %u warning(s) in mtree manifest", errors, warnings); if (errors) exit(1); } out: if (error > 0) errc(1, error, "Error reading mtree file"); if (fp != stdin) fclose(fp); if (mtree_root != NULL) return (mtree_root); /* Handle empty specifications. */ node = create_node(".", S_IFDIR, NULL, &mtree_global); node->first = node; return (node); } Index: stable/11/usr.sbin/makefs/walk.c =================================================================== --- stable/11/usr.sbin/makefs/walk.c (revision 332979) +++ stable/11/usr.sbin/makefs/walk.c (revision 332980) @@ -1,703 +1,704 @@ /* $NetBSD: walk.c,v 1.24 2008/12/28 21:51:46 christos Exp $ */ /* * SPDX-License-Identifier: BSD-4-Clause * * Copyright (c) 2001 Wasabi Systems, Inc. * All rights reserved. * * Written by Luke Mewburn for Wasabi Systems, Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed for the NetBSD Project by * Wasabi Systems, Inc. * 4. The name of Wasabi Systems, Inc. may not be used to endorse * or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL WASABI SYSTEMS, INC * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include +#include #include #include #include #include #include #include #include #include #include #include "makefs.h" #include "mtree.h" #include "extern.h" static void apply_specdir(const char *, NODE *, fsnode *, int); static void apply_specentry(const char *, NODE *, fsnode *); static fsnode *create_fsnode(const char *, const char *, const char *, struct stat *); /* * walk_dir -- * build a tree of fsnodes from `root' and `dir', with a parent * fsnode of `parent' (which may be NULL for the root of the tree). * append the tree to a fsnode of `join' if it is not NULL. * each "level" is a directory, with the "." entry guaranteed to be * at the start of the list, and without ".." entries. */ fsnode * walk_dir(const char *root, const char *dir, fsnode *parent, fsnode *join) { fsnode *first, *cur, *prev, *last; DIR *dirp; struct dirent *dent; char path[MAXPATHLEN + 1]; struct stat stbuf; char *name, *rp; int dot, len; assert(root != NULL); assert(dir != NULL); len = snprintf(path, sizeof(path), "%s/%s", root, dir); if (len >= (int)sizeof(path)) errx(1, "Pathname too long."); if (debug & DEBUG_WALK_DIR) printf("walk_dir: %s %p\n", path, parent); if ((dirp = opendir(path)) == NULL) err(1, "Can't opendir `%s'", path); rp = path + strlen(root) + 1; if (join != NULL) { first = cur = join; while (cur->next != NULL) cur = cur->next; prev = cur; } else first = prev = NULL; last = prev; while ((dent = readdir(dirp)) != NULL) { name = dent->d_name; dot = 0; if (name[0] == '.') switch (name[1]) { case '\0': /* "." */ if (join != NULL) continue; dot = 1; break; case '.': /* ".." */ if (name[2] == '\0') continue; /* FALLTHROUGH */ default: dot = 0; } if (debug & DEBUG_WALK_DIR_NODE) printf("scanning %s/%s/%s\n", root, dir, name); if (snprintf(path + len, sizeof(path) - len, "/%s", name) >= (int)sizeof(path) - len) errx(1, "Pathname too long."); if (lstat(path, &stbuf) == -1) err(1, "Can't lstat `%s'", path); #ifdef S_ISSOCK if (S_ISSOCK(stbuf.st_mode & S_IFMT)) { if (debug & DEBUG_WALK_DIR_NODE) printf(" skipping socket %s\n", path); continue; } #endif if (join != NULL) { cur = join->next; for (;;) { if (cur == NULL || strcmp(cur->name, name) == 0) break; if (cur == last) { cur = NULL; break; } cur = cur->next; } if (cur != NULL) { if (S_ISDIR(cur->type) && S_ISDIR(stbuf.st_mode)) { if (debug & DEBUG_WALK_DIR_NODE) printf("merging %s with %p\n", path, cur->child); cur->child = walk_dir(root, rp, cur, cur->child); continue; } errx(1, "Can't merge %s `%s' with existing %s", inode_type(stbuf.st_mode), path, inode_type(cur->type)); } } cur = create_fsnode(root, dir, name, &stbuf); cur->parent = parent; if (dot) { /* ensure "." is at the start of the list */ cur->next = first; first = cur; if (! prev) prev = cur; cur->first = first; } else { /* not "." */ if (prev) prev->next = cur; prev = cur; if (!first) first = cur; cur->first = first; if (S_ISDIR(cur->type)) { cur->child = walk_dir(root, rp, cur, NULL); continue; } } if (stbuf.st_nlink > 1) { fsinode *curino; curino = link_check(cur->inode); if (curino != NULL) { free(cur->inode); cur->inode = curino; cur->inode->nlink++; if (debug & DEBUG_WALK_DIR_LINKCHECK) printf("link_check: found [%llu, %llu]\n", (unsigned long long)curino->st.st_dev, (unsigned long long)curino->st.st_ino); } } if (S_ISLNK(cur->type)) { char slink[PATH_MAX+1]; int llen; llen = readlink(path, slink, sizeof(slink) - 1); if (llen == -1) err(1, "Readlink `%s'", path); slink[llen] = '\0'; if ((cur->symlink = strdup(slink)) == NULL) err(1, "Memory allocation error"); } } assert(first != NULL); if (join == NULL) for (cur = first->next; cur != NULL; cur = cur->next) cur->first = first; if (closedir(dirp) == -1) err(1, "Can't closedir `%s/%s'", root, dir); return (first); } static fsnode * create_fsnode(const char *root, const char *path, const char *name, struct stat *stbuf) { fsnode *cur; if ((cur = calloc(1, sizeof(fsnode))) == NULL || (cur->path = strdup(path)) == NULL || (cur->name = strdup(name)) == NULL || (cur->inode = calloc(1, sizeof(fsinode))) == NULL) err(1, "Memory allocation error"); cur->root = root; cur->type = stbuf->st_mode & S_IFMT; cur->inode->nlink = 1; cur->inode->st = *stbuf; if (stampst.st_ino) { cur->inode->st.st_atime = stampst.st_atime; cur->inode->st.st_mtime = stampst.st_mtime; cur->inode->st.st_ctime = stampst.st_ctime; #if HAVE_STRUCT_STAT_ST_MTIMENSEC cur->inode->st.st_atimensec = stampst.st_atimensec; cur->inode->st.st_mtimensec = stampst.st_mtimensec; cur->inode->st.st_ctimensec = stampst.st_ctimensec; #endif #if HAVE_STRUCT_STAT_BIRTHTIME cur->inode->st.st_birthtime = stampst.st_birthtime; cur->inode->st.st_birthtimensec = stampst.st_birthtimensec; #endif } return (cur); } /* * free_fsnodes -- * Removes node from tree and frees it and all of * its descendants. */ void free_fsnodes(fsnode *node) { fsnode *cur, *next; assert(node != NULL); /* for ".", start with actual parent node */ if (node->first == node) { assert(node->name[0] == '.' && node->name[1] == '\0'); if (node->parent) { assert(node->parent->child == node); node = node->parent; } } /* Find ourselves in our sibling list and unlink */ if (node->first != node) { for (cur = node->first; cur->next; cur = cur->next) { if (cur->next == node) { cur->next = node->next; node->next = NULL; break; } } } for (cur = node; cur != NULL; cur = next) { next = cur->next; if (cur->child) { cur->child->parent = NULL; free_fsnodes(cur->child); } if (cur->inode->nlink-- == 1) free(cur->inode); if (cur->symlink) free(cur->symlink); free(cur->path); free(cur->name); free(cur); } } /* * apply_specfile -- * read in the mtree(8) specfile, and apply it to the tree * at dir,parent. parameters in parent on equivalent types * will be changed to those found in specfile, and missing * entries will be added. */ void apply_specfile(const char *specfile, const char *dir, fsnode *parent, int speconly) { struct timeval start; FILE *fp; NODE *root; assert(specfile != NULL); assert(parent != NULL); if (debug & DEBUG_APPLY_SPECFILE) printf("apply_specfile: %s, %s %p\n", specfile, dir, parent); /* read in the specfile */ if ((fp = fopen(specfile, "r")) == NULL) err(1, "Can't open `%s'", specfile); TIMER_START(start); root = spec(fp); TIMER_RESULTS(start, "spec"); if (fclose(fp) == EOF) err(1, "Can't close `%s'", specfile); /* perform some sanity checks */ if (root == NULL) errx(1, "Specfile `%s' did not contain a tree", specfile); assert(strcmp(root->name, ".") == 0); assert(root->type == F_DIR); /* merge in the changes */ apply_specdir(dir, root, parent, speconly); } static void apply_specdir(const char *dir, NODE *specnode, fsnode *dirnode, int speconly) { char path[MAXPATHLEN + 1]; NODE *curnode; fsnode *curfsnode; assert(specnode != NULL); assert(dirnode != NULL); if (debug & DEBUG_APPLY_SPECFILE) printf("apply_specdir: %s %p %p\n", dir, specnode, dirnode); if (specnode->type != F_DIR) errx(1, "Specfile node `%s/%s' is not a directory", dir, specnode->name); if (dirnode->type != S_IFDIR) errx(1, "Directory node `%s/%s' is not a directory", dir, dirnode->name); apply_specentry(dir, specnode, dirnode); /* Remove any filesystem nodes not found in specfile */ /* XXX inefficient. This is O^2 in each dir and it would * have been better never to have walked this part of the tree * to begin with */ if (speconly) { fsnode *next; assert(dirnode->name[0] == '.' && dirnode->name[1] == '\0'); for (curfsnode = dirnode->next; curfsnode != NULL; curfsnode = next) { next = curfsnode->next; for (curnode = specnode->child; curnode != NULL; curnode = curnode->next) { if (strcmp(curnode->name, curfsnode->name) == 0) break; } if (curnode == NULL) { if (debug & DEBUG_APPLY_SPECONLY) { printf("apply_specdir: trimming %s/%s %p\n", dir, curfsnode->name, curfsnode); } free_fsnodes(curfsnode); } } } /* now walk specnode->child matching up with dirnode */ for (curnode = specnode->child; curnode != NULL; curnode = curnode->next) { if (debug & DEBUG_APPLY_SPECENTRY) printf("apply_specdir: spec %s\n", curnode->name); for (curfsnode = dirnode->next; curfsnode != NULL; curfsnode = curfsnode->next) { #if 0 /* too verbose for now */ if (debug & DEBUG_APPLY_SPECENTRY) printf("apply_specdir: dirent %s\n", curfsnode->name); #endif if (strcmp(curnode->name, curfsnode->name) == 0) break; } if (snprintf(path, sizeof(path), "%s/%s", dir, curnode->name) >= sizeof(path)) errx(1, "Pathname too long."); if (curfsnode == NULL) { /* need new entry */ struct stat stbuf; /* * don't add optional spec entries * that lack an existing fs entry */ if ((curnode->flags & F_OPT) && lstat(path, &stbuf) == -1) continue; /* check that enough info is provided */ #define NODETEST(t, m) \ if (!(t)) \ errx(1, "`%s': %s not provided", path, m) NODETEST(curnode->flags & F_TYPE, "type"); NODETEST(curnode->flags & F_MODE, "mode"); /* XXX: require F_TIME ? */ NODETEST(curnode->flags & F_GID || curnode->flags & F_GNAME, "group"); NODETEST(curnode->flags & F_UID || curnode->flags & F_UNAME, "user"); /* if (curnode->type == F_BLOCK || curnode->type == F_CHAR) NODETEST(curnode->flags & F_DEV, "device number");*/ #undef NODETEST if (debug & DEBUG_APPLY_SPECFILE) printf("apply_specdir: adding %s\n", curnode->name); /* build minimal fsnode */ memset(&stbuf, 0, sizeof(stbuf)); stbuf.st_mode = nodetoino(curnode->type); stbuf.st_nlink = 1; stbuf.st_mtime = stbuf.st_atime = stbuf.st_ctime = start_time.tv_sec; #if HAVE_STRUCT_STAT_ST_MTIMENSEC stbuf.st_mtimensec = stbuf.st_atimensec = stbuf.st_ctimensec = start_time.tv_nsec; #endif curfsnode = create_fsnode(".", ".", curnode->name, &stbuf); curfsnode->parent = dirnode->parent; curfsnode->first = dirnode; curfsnode->next = dirnode->next; dirnode->next = curfsnode; if (curfsnode->type == S_IFDIR) { /* for dirs, make "." entry as well */ curfsnode->child = create_fsnode(".", ".", ".", &stbuf); curfsnode->child->parent = curfsnode; curfsnode->child->first = curfsnode->child; } if (curfsnode->type == S_IFLNK) { assert(curnode->slink != NULL); /* for symlinks, copy the target */ if ((curfsnode->symlink = strdup(curnode->slink)) == NULL) err(1, "Memory allocation error"); } } apply_specentry(dir, curnode, curfsnode); if (curnode->type == F_DIR) { if (curfsnode->type != S_IFDIR) errx(1, "`%s' is not a directory", path); assert (curfsnode->child != NULL); apply_specdir(path, curnode, curfsnode->child, speconly); } } } static void apply_specentry(const char *dir, NODE *specnode, fsnode *dirnode) { assert(specnode != NULL); assert(dirnode != NULL); if (nodetoino(specnode->type) != dirnode->type) errx(1, "`%s/%s' type mismatch: specfile %s, tree %s", dir, specnode->name, inode_type(nodetoino(specnode->type)), inode_type(dirnode->type)); if (debug & DEBUG_APPLY_SPECENTRY) printf("apply_specentry: %s/%s\n", dir, dirnode->name); #define ASEPRINT(t, b, o, n) \ if (debug & DEBUG_APPLY_SPECENTRY) \ printf("\t\t\tchanging %s from " b " to " b "\n", \ t, o, n) if (specnode->flags & (F_GID | F_GNAME)) { ASEPRINT("gid", "%d", dirnode->inode->st.st_gid, specnode->st_gid); dirnode->inode->st.st_gid = specnode->st_gid; } if (specnode->flags & F_MODE) { ASEPRINT("mode", "%#o", dirnode->inode->st.st_mode & ALLPERMS, specnode->st_mode); dirnode->inode->st.st_mode &= ~ALLPERMS; dirnode->inode->st.st_mode |= (specnode->st_mode & ALLPERMS); } /* XXX: ignoring F_NLINK for now */ if (specnode->flags & F_SIZE) { ASEPRINT("size", "%lld", (long long)dirnode->inode->st.st_size, (long long)specnode->st_size); dirnode->inode->st.st_size = specnode->st_size; } if (specnode->flags & F_SLINK) { assert(dirnode->symlink != NULL); assert(specnode->slink != NULL); ASEPRINT("symlink", "%s", dirnode->symlink, specnode->slink); free(dirnode->symlink); if ((dirnode->symlink = strdup(specnode->slink)) == NULL) err(1, "Memory allocation error"); } if (specnode->flags & F_TIME) { ASEPRINT("time", "%ld", (long)dirnode->inode->st.st_mtime, (long)specnode->st_mtimespec.tv_sec); dirnode->inode->st.st_mtime = specnode->st_mtimespec.tv_sec; dirnode->inode->st.st_atime = specnode->st_mtimespec.tv_sec; dirnode->inode->st.st_ctime = start_time.tv_sec; #if HAVE_STRUCT_STAT_ST_MTIMENSEC dirnode->inode->st.st_mtimensec = specnode->st_mtimespec.tv_nsec; dirnode->inode->st.st_atimensec = specnode->st_mtimespec.tv_nsec; dirnode->inode->st.st_ctimensec = start_time.tv_nsec; #endif } if (specnode->flags & (F_UID | F_UNAME)) { ASEPRINT("uid", "%d", dirnode->inode->st.st_uid, specnode->st_uid); dirnode->inode->st.st_uid = specnode->st_uid; } #if HAVE_STRUCT_STAT_ST_FLAGS if (specnode->flags & F_FLAGS) { ASEPRINT("flags", "%#lX", (unsigned long)dirnode->inode->st.st_flags, (unsigned long)specnode->st_flags); dirnode->inode->st.st_flags = specnode->st_flags; } #endif /* if (specnode->flags & F_DEV) { ASEPRINT("rdev", "%#llx", (unsigned long long)dirnode->inode->st.st_rdev, (unsigned long long)specnode->st_rdev); dirnode->inode->st.st_rdev = specnode->st_rdev; }*/ #undef ASEPRINT dirnode->flags |= FSNODE_F_HASSPEC; } /* * dump_fsnodes -- * dump the fsnodes from `cur' */ void dump_fsnodes(fsnode *root) { fsnode *cur; char path[MAXPATHLEN + 1]; printf("dump_fsnodes: %s %p\n", root->path, root); for (cur = root; cur != NULL; cur = cur->next) { if (snprintf(path, sizeof(path), "%s/%s", cur->path, cur->name) >= (int)sizeof(path)) errx(1, "Pathname too long."); if (debug & DEBUG_DUMP_FSNODES_VERBOSE) printf("cur=%8p parent=%8p first=%8p ", cur, cur->parent, cur->first); printf("%7s: %s", inode_type(cur->type), path); if (S_ISLNK(cur->type)) { assert(cur->symlink != NULL); printf(" -> %s", cur->symlink); } else { assert (cur->symlink == NULL); } if (cur->inode->nlink > 1) printf(", nlinks=%d", cur->inode->nlink); putchar('\n'); if (cur->child) { assert (cur->type == S_IFDIR); dump_fsnodes(cur->child); } } printf("dump_fsnodes: finished %s/%s\n", root->path, root->name); } /* * inode_type -- * for a given inode type `mode', return a descriptive string. * for most cases, uses inotype() from mtree/misc.c */ const char * inode_type(mode_t mode) { if (S_ISREG(mode)) return ("file"); if (S_ISLNK(mode)) return ("symlink"); if (S_ISDIR(mode)) return ("dir"); if (S_ISLNK(mode)) return ("link"); if (S_ISFIFO(mode)) return ("fifo"); if (S_ISSOCK(mode)) return ("socket"); /* XXX should not happen but handle them */ if (S_ISCHR(mode)) return ("char"); if (S_ISBLK(mode)) return ("block"); return ("unknown"); } /* * link_check -- * return pointer to fsinode matching `entry's st_ino & st_dev if it exists, * otherwise add `entry' to table and return NULL */ /* This was borrowed from du.c and tweaked to keep an fsnode * pointer instead. -- dbj@netbsd.org */ fsinode * link_check(fsinode *entry) { static struct entry { fsinode *data; } *htable; static int htshift; /* log(allocated size) */ static int htmask; /* allocated size - 1 */ static int htused; /* 2*number of insertions */ int h, h2; uint64_t tmp; /* this constant is (1<<64)/((1+sqrt(5))/2) * aka (word size)/(golden ratio) */ const uint64_t HTCONST = 11400714819323198485ULL; const int HTBITS = 64; /* Never store zero in hashtable */ assert(entry); /* Extend hash table if necessary, keep load under 0.5 */ if (htused<<1 >= htmask) { struct entry *ohtable; if (!htable) htshift = 10; /* starting hashtable size */ else htshift++; /* exponential hashtable growth */ htmask = (1 << htshift) - 1; htused = 0; ohtable = htable; htable = calloc(htmask+1, sizeof(*htable)); if (!htable) err(1, "Memory allocation error"); /* populate newly allocated hashtable */ if (ohtable) { int i; for (i = 0; i <= htmask>>1; i++) if (ohtable[i].data) link_check(ohtable[i].data); free(ohtable); } } /* multiplicative hashing */ tmp = entry->st.st_dev; tmp <<= HTBITS>>1; tmp |= entry->st.st_ino; tmp *= HTCONST; h = tmp >> (HTBITS - htshift); h2 = 1 | ( tmp >> (HTBITS - (htshift<<1) - 1)); /* must be odd */ /* open address hashtable search with double hash probing */ while (htable[h].data) { if ((htable[h].data->st.st_ino == entry->st.st_ino) && (htable[h].data->st.st_dev == entry->st.st_dev)) { return htable[h].data; } h = (h + h2) & htmask; } /* Insert the current entry into hashtable */ htable[h].data = entry; htused++; return NULL; } Index: stable/11 =================================================================== --- stable/11 (revision 332979) +++ stable/11 (revision 332980) Property changes on: stable/11 ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,1 ## Merged /head:r307927