# # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2016 Toomas Soome # Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. # include $(SRC)/cmd/Makefile.cmd .PARALLEL: COMMON_SUBDIRS= \ filelist \ fiocompress \ scripts \ bootadm # Hammerhead: installboot removed - source files not present in tree i386_SUBDIRS= \ installgrub \ symdef # Hammerhead: sparc_SUBDIRS removed - amd64 only build COMMON_LINTSUBDIRS= \ bootadm i386_LINTSUBDIRS= \ fiocompress \ installgrub \ symdef # Hammerhead: sparc_LINTSUBDIRS removed - amd64 only build COMMON_MSGSUBDIRS= \ bootadm \ fiocompress i386_MSGSUBDIRS= \ installgrub # Hammerhead: sparc_MSGSUBDIRS removed - amd64 only build all: TARGET= all install: TARGET= install clean: TARGET= clean clobber: TARGET= clobber lint: TARGET= lint _msg: TARGET= _msg .KEEP_STATE: SUBDIRS = $(COMMON_SUBDIRS) $($(MACH)_SUBDIRS) LINTSUBDIRS = $(COMMON_LINTSUBDIRS) $($(MACH)_LINTSUBDIRS) MSGSUBDIRS = $(COMMON_MSGSUBDIRS) $($(MACH)_MSGSUBDIRS) all clean clobber: $(SUBDIRS) install: $(SUBDIRS) lint: $(LINTSUBDIRS) _msg: $(MSGSUBDIRS) FRC: $(SUBDIRS): FRC @cd $@; pwd; $(MAKE) $(TARGET) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # include $(SRC)/cmd/Makefile.cmd CFLAGS += $(CCVERBOSE) ROOTBOOT= $(ROOT)/boot ROOTBOOTSOLARIS= $(ROOTBOOT)/solaris ROOTBOOTSOLARISBIN= $(ROOTBOOTSOLARIS)/bin ROOTBOOTSOLARISBINPROG= $(BOOTPROG:%=$(ROOTBOOTSOLARISBIN)/%) $(ROOTBOOTSOLARISBINPROG) : FILEMODE= 0555 ROOTBOOTSOLARISDATA= $(DATA:%=$(ROOTBOOTSOLARIS)/%) $(ROOTBOOTSOLARISDATA) : FILEMODE= 0644 ROOTUSRSBINLINKS= $(SBINLINKS:%=$(ROOTUSRSBIN)/%) ROOTBOOTSOLARISBINLINKS= $(SBINLINKS:%=$(ROOTBOOTSOLARISBIN)/%) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # $(ROOTBOOT): $(INS.dir) $(ROOTBOOTSOLARIS): $(INS.dir) $(ROOTBOOTSOLARISBIN): $(INS.dir) $(ROOTBOOTSOLARIS)/%: % $(INS.file) $(ROOTBOOTSOLARISBIN)/%: % $(INS.file) $(ROOTUSRSBINLINKS): -$(RM) $@; $(SYMLINK) ../../sbin/$(@F) $@ $(ROOTBOOTSOLARISBINLINKS): $(RM) $@; $(SYMLINK) ../../sbin/$(@F) $@ include $(SRC)/cmd/Makefile.targ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Copyright 2016 Toomas Soome # Copyright 2016 Nexenta Systems, Inc. # Copyright 2018 OmniOS Community Edition (OmniOSce) Association. # Copyright (c) 2018, Joyent, Inc. PROG= bootadm SBINLINKS= $(PROG) OBJS= bootadm.o bootadm_upgrade.o bootadm_hyper.o bootadm_digest.o \ bootadm_loader.o POFILES= $(OBJS:%.o=%.po) include ../Makefile.com POFILE= bootadm_cmd.po .KEEP_STATE: LDLIBS_i386= -lfdisk LDLIBS += -lficl-sys -lmd -lcryptoutil -lnvpair -lgen -ladm -lefi LDLIBS += -lscf -lz -lbe -lzfs -lofmt $(LDLIBS_$(MACH)) CPPFLAGS += -D_FILE_OFFSET_BITS=64 CPPFLAGS += -I$(SRC)/uts/common -I$(SRC)/common -I$(SRC)/common/ficl SMOFF += all_func_returns CSTD= $(CSTD_GNU99) all: $(PROG) $(PROG): $(OBJS) bootadm.h $(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(POST_PROCESS) install: all $(ROOTSBINPROG) .WAIT $(ROOTUSRSBINLINKS) $(POFILE): $(POFILES) $(RM) $@ $(CAT) $(POFILES) > $@ clean: -$(RM) $(OBJS) $(POFILE) $(POFILES) include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Milan Jurik. All rights reserved. * Copyright (c) 2015 by Delphix. All rights reserved. * Copyright 2016 Toomas Soome * Copyright 2017 Nexenta Systems, Inc. * Copyright 2018 OmniOS Community Edition (OmniOSce) Association. * Copyright 2023 Oxide Computer Company */ /* * bootadm(8) is a new utility for managing bootability of * Solaris *Newboot* environments. It has two primary tasks: * - Allow end users to manage bootability of Newboot Solaris instances * - Provide services to other subsystems in Solaris (primarily Install) */ /* Headers */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef i386 #include #endif #include #include #include #include #include #include #include #include #include "bootadm.h" #ifndef TEXT_DOMAIN #define TEXT_DOMAIN "SUNW_OST_OSCMD" #endif /* TEXT_DOMAIN */ /* Type definitions */ /* Primary subcmds */ typedef enum { BAM_MENU = 3, BAM_ARCHIVE, BAM_INSTALL } subcmd_t; #define LINE_INIT 0 /* lineNum initial value */ #define ENTRY_INIT -1 /* entryNum initial value */ #define ALL_ENTRIES -2 /* selects all boot entries */ #define PARTNO_NOTFOUND -1 /* Solaris partition not found */ #define PARTNO_EFI -2 /* EFI partition table found */ #define GRUB_DIR "/boot/grub" #define GRUB_STAGE2 GRUB_DIR "/stage2" #define GRUB_MENU "/boot/grub/menu.lst" #define MENU_TMP "/boot/grub/menu.lst.tmp" #define GRUB_BACKUP_MENU "/etc/lu/GRUB_backup_menu" #define RAMDISK_SPECIAL "/devices/ramdisk" #define STUBBOOT "/stubboot" #define MULTIBOOT "/kernel/multiboot" #define GRUBSIGN_DIR "/boot/grub/bootsign" #define GRUBSIGN_BACKUP "/etc/bootsign" #define GRUBSIGN_UFS_PREFIX "rootfs" #define GRUBSIGN_ZFS_PREFIX "pool_" #define GRUBSIGN_LU_PREFIX "BE_" #define UFS_SIGNATURE_LIST "/var/run/grub_ufs_signatures" #define ZFS_LEGACY_MNTPT "/tmp/bootadm_mnt_zfs_legacy" /* SMF */ #define BOOT_ARCHIVE_FMRI "system/boot-archive:default" #define SCF_PG_CONFIG "config" #define SCF_PROPERTY_FORMAT "format" /* BE defaults */ #define BE_DEFAULTS "/etc/default/be" #define BE_DFLT_BE_HAS_GRUB "BE_HAS_GRUB=" #define BOOTADM_RDONLY_TEST "BOOTADM_RDONLY_TEST" /* lock related */ #define BAM_LOCK_FILE "/var/run/bootadm.lock" #define LOCK_FILE_PERMS (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) #define CREATE_RAMDISK "boot/solaris/bin/create_ramdisk" #define CREATE_DISKMAP "boot/solaris/bin/create_diskmap" #define EXTRACT_BOOT_FILELIST "boot/solaris/bin/extract_boot_filelist" #define GRUBDISK_MAP "/var/run/solaris_grubdisk.map" #define GRUB_slice "/etc/lu/GRUB_slice" #define GRUB_root "/etc/lu/GRUB_root" #define GRUB_fdisk "/etc/lu/GRUB_fdisk" #define GRUB_fdisk_target "/etc/lu/GRUB_fdisk_target" #define FINDROOT_INSTALLGRUB "/etc/lu/installgrub.findroot" #define LULIB "/usr/lib/lu/lulib" #define LULIB_PROPAGATE_FILE "lulib_propagate_file" #define CKSUM "/usr/bin/cksum" #define LU_MENU_CKSUM "/etc/lu/menu.cksum" #define BOOTADM "/sbin/bootadm" #define INSTALLGRUB "/sbin/installgrub" #define STAGE1 "/boot/grub/stage1" #define STAGE2 "/boot/grub/stage2" #define ETC_SYSTEM_DIR "etc/system.d" #define SELF_ASSEMBLY "etc/system.d/.self-assembly" /* * Default file attributes */ #define DEFAULT_DEV_MODE 0644 /* default permissions */ #define DEFAULT_DEV_UID 0 /* user root */ #define DEFAULT_DEV_GID 3 /* group sys */ /* * Menu related * menu_cmd_t and menu_cmds must be kept in sync */ char *menu_cmds[] = { "default", /* DEFAULT_CMD */ "timeout", /* TIMEOUT_CMD */ "title", /* TITLE_CMD */ "root", /* ROOT_CMD */ "kernel", /* KERNEL_CMD */ "kernel$", /* KERNEL_DOLLAR_CMD */ "module", /* MODULE_CMD */ "module$", /* MODULE_DOLLAR_CMD */ " ", /* SEP_CMD */ "#", /* COMMENT_CMD */ "chainloader", /* CHAINLOADER_CMD */ "args", /* ARGS_CMD */ "findroot", /* FINDROOT_CMD */ "bootfs", /* BOOTFS_CMD */ NULL }; char *bam_formats[] = { "hsfs", "ufs", "cpio", "ufs-nocompress", NULL }; #define BAM_FORMAT_UNSET -1 #define BAM_FORMAT_HSFS 0 short bam_format = BAM_FORMAT_UNSET; #define OPT_ENTRY_NUM "entry" /* * exec_cmd related */ typedef struct { line_t *head; line_t *tail; } filelist_t; #define BOOT_FILE_LIST "boot/solaris/filelist.ramdisk" #define ETC_FILE_LIST "etc/boot/solaris/filelist.ramdisk" #define FILE_STAT "boot/solaris/filestat.ramdisk" #define FILE_STAT_TMP "boot/solaris/filestat.ramdisk.tmp" #define DIR_PERMS (S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH) #define FILE_STAT_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH) #define FILE_STAT_TIMESTAMP "boot/solaris/timestamp.cache" /* Globals */ int bam_verbose; int bam_force; int bam_debug; int bam_skip_lock; static char *prog; static subcmd_t bam_cmd; char *bam_root; int bam_rootlen; static int bam_root_readonly; int bam_alt_root; static int bam_extend = 0; static int bam_purge = 0; static char *bam_subcmd; static char *bam_opt; static char **bam_argv; static char *bam_pool; static int bam_argc; static int bam_check; static int bam_saved_check; static int bam_smf_check; static int bam_lock_fd = -1; static int bam_zfs; static int bam_mbr; char rootbuf[PATH_MAX] = "/"; static char self_assembly[PATH_MAX]; static int bam_update_all; static int bam_alt_platform; static char *bam_platform; static char *bam_home_env = NULL; /* function prototypes */ static void parse_args_internal(int, char *[]); static void parse_args(int, char *argv[]); static error_t bam_menu(char *, char *, int, char *[]); static error_t bam_install(char *, char *); static error_t bam_archive(char *, char *); static void bam_lock(void); static void bam_unlock(void); static int exec_cmd(char *, filelist_t *); static error_t read_globals(menu_t *, char *, char *, int); static int menu_on_bootdisk(char *os_root, char *menu_root); static menu_t *menu_read(char *); static error_t menu_write(char *, menu_t *); static void linelist_free(line_t *); static void menu_free(menu_t *); static void filelist_free(filelist_t *); static error_t list2file(char *, char *, char *, line_t *); static error_t list_entry(menu_t *, char *, char *); static error_t list_setting(menu_t *, char *, char *); static error_t delete_all_entries(menu_t *, char *, char *); static error_t update_entry(menu_t *mp, char *menu_root, char *opt); static error_t update_temp(menu_t *mp, char *dummy, char *opt); static error_t install_bootloader(void); static error_t update_archive(char *, char *); static error_t list_archive(char *, char *); static error_t update_all(char *, char *); static error_t read_list(char *, filelist_t *); static error_t set_option(menu_t *, char *, char *); static error_t set_kernel(menu_t *, menu_cmd_t, char *, char *, size_t); static error_t get_kernel(menu_t *, menu_cmd_t, char *, size_t); static error_t build_etc_system_dir(char *); static char *expand_path(const char *); static long s_strtol(char *); static int s_fputs(char *, FILE *); static int is_amd64(void); static char *get_machine(void); static void append_to_flist(filelist_t *, char *); static int ufs_add_to_sign_list(char *sign); static error_t synchronize_BE_menu(void); /* Menu related sub commands */ static subcmd_defn_t menu_subcmds[] = { "set_option", OPT_ABSENT, set_option, 0, /* PUB */ "list_entry", OPT_OPTIONAL, list_entry, 1, /* PUB */ "delete_all_entries", OPT_ABSENT, delete_all_entries, 0, /* PVT */ "update_entry", OPT_REQ, update_entry, 0, /* menu */ "update_temp", OPT_OPTIONAL, update_temp, 0, /* reboot */ "upgrade", OPT_ABSENT, upgrade_menu, 0, /* menu */ "list_setting", OPT_OPTIONAL, list_setting, 1, /* menu */ "disable_hypervisor", OPT_ABSENT, cvt_to_metal, 0, /* menu */ "enable_hypervisor", OPT_ABSENT, cvt_to_hyper, 0, /* menu */ NULL, 0, NULL, 0 /* must be last */ }; /* Archive related sub commands */ static subcmd_defn_t arch_subcmds[] = { "update", OPT_ABSENT, update_archive, 0, /* PUB */ "update_all", OPT_ABSENT, update_all, 0, /* PVT */ "list", OPT_OPTIONAL, list_archive, 1, /* PUB */ NULL, 0, NULL, 0 /* must be last */ }; /* Install related sub commands */ static subcmd_defn_t inst_subcmds[] = { "install_bootloader", OPT_ABSENT, install_bootloader, 0, /* PUB */ NULL, 0, NULL, 0 /* must be last */ }; #define build_path(buf, len, root, prefix, suffix) \ snprintf((buf), (len), "%s%s%s", (root), (prefix), (suffix)) /* * Directory specific flags: * NEED_UPDATE : the specified archive needs to be updated * NO_EXTEND : don't extend the specified archive, but recreate it */ #define NEED_UPDATE 0x00000001 #define NO_EXTEND 0x00000002 #define set_dir_flag(f) (walk_arg.dirinfo.flags |= (f)) #define unset_dir_flag(f) (walk_arg.dirinfo.flags &= ~(f)) #define is_dir_flag_on(f) (walk_arg.dirinfo.flags & (f) ? 1 : 0) #define get_cachedir() (walk_arg.dirinfo.cdir_path) #define get_updatedir() (walk_arg.dirinfo.update_path) #define get_count() (walk_arg.dirinfo.count) #define has_cachedir() (walk_arg.dirinfo.has_dir) #define set_dir_present() (walk_arg.dirinfo.has_dir = 1) /* * dirinfo_t (specific cache directory information): * cdir_path: path to the archive cache directory * update_path: path to the update directory (contains the files that will be * used to extend the archive) * has_dir: the specified cache directory is active * count: the number of files to update * flags: directory specific flags */ typedef struct _dirinfo { char cdir_path[PATH_MAX]; char update_path[PATH_MAX]; int has_dir; int count; int flags; } dirinfo_t; /* * Update flags: * NEED_CACHE_DIR : cache directory is missing and needs to be created * IS_SPARC_TARGET : the target mountpoint is a SPARC environment * UPDATE_ERROR : an error occourred while traversing the list of files * RDONLY_FSCHK : the target filesystem is read-only * RAMDSK_FSCHK : the target filesystem is on a ramdisk */ #define NEED_CACHE_DIR 0x00000001 #define IS_SPARC_TARGET 0x00000002 #define UPDATE_ERROR 0x00000004 #define RDONLY_FSCHK 0x00000008 #define INVALIDATE_CACHE 0x00000010 #define is_flag_on(flag) (walk_arg.update_flags & flag ? 1 : 0) #define set_flag(flag) (walk_arg.update_flags |= flag) #define unset_flag(flag) (walk_arg.update_flags &= ~flag) /* * struct walk_arg : * update_flags: flags related to the current updating process * new_nvlp/old_nvlp: new and old list of archive-files / attributes pairs * sparcfile: list of file paths for mkisofs -path-list (SPARC only) */ static struct { int update_flags; nvlist_t *new_nvlp; nvlist_t *old_nvlp; FILE *sparcfile; dirinfo_t dirinfo; } walk_arg; struct safefile { char *name; struct safefile *next; }; static struct safefile *safefiles = NULL; /* * svc:/system/filesystem/usr:default service checks for this file and * does a boot archive update and then reboot the system. */ #define NEED_UPDATE_FILE "/etc/svc/volatile/boot_archive_needs_update" /* * svc:/system/boot-archive-update:default checks for this file and * updates the boot archive. */ #define NEED_UPDATE_SAFE_FILE "/etc/svc/volatile/boot_archive_safefile_update" /* Thanks growisofs */ #define CD_BLOCK ((off64_t)2048) #define VOLDESC_OFF 16 #define DVD_BLOCK (32*1024) #define MAX_IVDs 16 struct iso_pdesc { unsigned char type [1]; unsigned char id [5]; unsigned char void1 [80-5-1]; unsigned char volume_space_size [8]; unsigned char void2 [2048-80-8]; }; /* * COUNT_MAX: maximum number of changed files to justify a multisession update * BA_SIZE_MAX: maximum size of the boot_archive to justify a multisession * update */ #define COUNT_MAX 50 #define BA_SIZE_MAX (50 * 1024 * 1024) #define bam_nowrite() (bam_check || bam_smf_check) static int sync_menu = 1; /* whether we need to sync the BE menus */ static void usage(void) { (void) fprintf(stderr, "USAGE:\n"); /* archive usage */ (void) fprintf(stderr, "\t%s update-archive [-vnf] [-R altroot [-p platform]] " "[-F format]\n", prog); (void) fprintf(stderr, "\t%s list-archive [-R altroot [-p platform]]\n", prog); #if defined(_OBP) (void) fprintf(stderr, "\t%s install-bootloader [-fv] [-R altroot] [-P pool]\n", prog); #else (void) fprintf(stderr, "\t%s install-bootloader [-Mfv] [-R altroot] [-P pool]\n", prog); #endif #if !defined(_OBP) /* x86 only */ (void) fprintf(stderr, "\t%s set-menu [-R altroot] key=value\n", prog); (void) fprintf(stderr, "\t%s list-menu [-R altroot]\n", prog); #endif } /* * Best effort attempt to restore the $HOME value. */ static void restore_env() { char home_env[PATH_MAX]; if (bam_home_env) { (void) snprintf(home_env, sizeof (home_env), "HOME=%s", bam_home_env); (void) putenv(home_env); } } #define SLEEP_TIME 5 #define MAX_TRIES 4 /* * Sanitize the environment in which bootadm will execute its sub-processes * (ex. mkisofs). This is done to prevent those processes from attempting * to access files (ex. .mkisofsrc) or stat paths that might be on NFS * or, potentially, insecure. */ static void sanitize_env() { int stry = 0; /* don't depend on caller umask */ (void) umask(0022); /* move away from a potential unsafe current working directory */ while (chdir("/") == -1) { if (errno != EINTR) { bam_print("WARNING: unable to chdir to /"); break; } } bam_home_env = getenv("HOME"); while (bam_home_env != NULL && putenv("HOME=/") == -1) { if (errno == ENOMEM) { /* retry no more than MAX_TRIES times */ if (++stry > MAX_TRIES) { bam_print("WARNING: unable to recover from " "system memory pressure... aborting \n"); bam_exit(EXIT_FAILURE); } /* memory is tight, try to sleep */ bam_print("Attempting to recover from memory pressure: " "sleeping for %d seconds\n", SLEEP_TIME * stry); (void) sleep(SLEEP_TIME * stry); } else { bam_print("WARNING: unable to sanitize HOME\n"); } } } int main(int argc, char *argv[]) { error_t ret = BAM_SUCCESS; (void) setlocale(LC_ALL, ""); (void) textdomain(TEXT_DOMAIN); if ((prog = strrchr(argv[0], '/')) == NULL) { prog = argv[0]; } else { prog++; } INJECT_ERROR1("ASSERT_ON", assert(0)) sanitize_env(); parse_args(argc, argv); switch (bam_cmd) { case BAM_MENU: if (is_grub(bam_alt_root ? bam_root : "/")) { ret = bam_menu(bam_subcmd, bam_opt, bam_argc, bam_argv); } else { ret = bam_loader_menu(bam_subcmd, bam_opt, bam_argc, bam_argv); } break; case BAM_ARCHIVE: ret = bam_archive(bam_subcmd, bam_opt); break; case BAM_INSTALL: ret = bam_install(bam_subcmd, bam_opt); break; default: usage(); bam_exit(1); } if (ret != BAM_SUCCESS) bam_exit((ret == BAM_NOCHANGE) ? 2 : 1); bam_unlock(); return (0); } /* * Equivalence of public and internal commands: * update-archive -- -a update * list-archive -- -a list * set-menu -- -m set_option * list-menu -- -m list_entry * update-menu -- -m update_entry * install-bootloader -- -i install_bootloader */ static struct cmd_map { char *bam_cmdname; int bam_cmd; char *bam_subcmd; } cmd_map[] = { { "update-archive", BAM_ARCHIVE, "update"}, { "list-archive", BAM_ARCHIVE, "list"}, { "set-menu", BAM_MENU, "set_option"}, { "list-menu", BAM_MENU, "list_entry"}, { "update-menu", BAM_MENU, "update_entry"}, { "install-bootloader", BAM_INSTALL, "install_bootloader"}, { NULL, 0, NULL} }; /* * Commands syntax published in bootadm(8) are parsed here */ static void parse_args(int argc, char *argv[]) { struct cmd_map *cmp = cmd_map; /* command conforming to the final spec */ if (argc > 1 && argv[1][0] != '-') { /* * Map commands to internal table. */ while (cmp->bam_cmdname) { if (strcmp(argv[1], cmp->bam_cmdname) == 0) { bam_cmd = cmp->bam_cmd; bam_subcmd = cmp->bam_subcmd; break; } cmp++; } if (cmp->bam_cmdname == NULL) { usage(); bam_exit(1); } argc--; argv++; } parse_args_internal(argc, argv); } /* * A combination of public and private commands are parsed here. * The internal syntax and the corresponding functionality are: * -a update -- update-archive * -a list -- list-archive * -a update_all -- (reboot to sync all mnted OS archive) * -i install_bootloader -- install-bootloader * -m update_entry -- update-menu * -m list_entry -- list-menu * -m update_temp -- (reboot -- [boot-args]) * -m delete_all_entries -- (called from install) * -m enable_hypervisor [args] -- cvt_to_hyper * -m disable_hypervisor -- cvt_to_metal * -m list_setting [entry] [value] -- list_setting * * A set of private flags is there too: * -Q -- purge the cache directories and rebuild them * -e -- use the (faster) archive update approach (used by * reboot) * -L -- skip locking */ static void parse_args_internal(int argc, char *argv[]) { int c, i, error; extern char *optarg; extern int optind, opterr; #if defined(_OBP) const char *optstring = "a:d:fF:i:m:no:veQCLR:p:P:XZ"; #else const char *optstring = "a:d:fF:i:m:no:veQCMLR:p:P:XZ"; #endif /* Suppress error message from getopt */ opterr = 0; error = 0; while ((c = getopt(argc, argv, optstring)) != -1) { switch (c) { case 'a': if (bam_cmd) { error = 1; bam_error( _("multiple commands specified: -%c\n"), c); } bam_cmd = BAM_ARCHIVE; bam_subcmd = optarg; break; case 'd': if (bam_debug) { error = 1; bam_error( _("duplicate options specified: -%c\n"), c); } bam_debug = s_strtol(optarg); break; case 'f': bam_force = 1; break; case 'F': if (bam_format != BAM_FORMAT_UNSET) { error = 1; bam_error( _("multiple formats specified: -%c\n"), c); } for (i = 0; bam_formats[i] != NULL; i++) { if (strcmp(bam_formats[i], optarg) == 0) { bam_format = i; break; } } if (bam_format == BAM_FORMAT_UNSET) { error = 1; bam_error( _("unknown format specified: -%c %s\n"), c, optarg); } break; case 'Q': bam_purge = 1; break; case 'L': bam_skip_lock = 1; break; case 'i': if (bam_cmd) { error = 1; bam_error( _("multiple commands specified: -%c\n"), c); } bam_cmd = BAM_INSTALL; bam_subcmd = optarg; break; case 'm': if (bam_cmd) { error = 1; bam_error( _("multiple commands specified: -%c\n"), c); } bam_cmd = BAM_MENU; bam_subcmd = optarg; break; #if !defined(_OBP) case 'M': bam_mbr = 1; break; #endif case 'n': bam_check = 1; /* * We save the original value of bam_check. The new * approach in case of a read-only filesystem is to * behave as a check, so we need a way to restore the * original value after the evaluation of the read-only * filesystem has been done. * Even if we don't allow at the moment a check with * update_all, this approach is more robust than * simply resetting bam_check to zero. */ bam_saved_check = 1; break; case 'o': if (bam_opt) { error = 1; bam_error( _("duplicate options specified: -%c\n"), c); } bam_opt = optarg; break; case 'v': bam_verbose = 1; break; case 'C': bam_smf_check = 1; break; case 'P': if (bam_pool != NULL) { error = 1; bam_error( _("duplicate options specified: -%c\n"), c); } bam_pool = optarg; break; case 'R': if (bam_root) { error = 1; bam_error( _("duplicate options specified: -%c\n"), c); break; } else if (realpath(optarg, rootbuf) == NULL) { error = 1; bam_error(_("cannot resolve path %s: %s\n"), optarg, strerror(errno)); break; } bam_alt_root = 1; bam_root = rootbuf; bam_rootlen = strlen(rootbuf); break; case 'p': bam_alt_platform = 1; bam_platform = optarg; if (strcmp(bam_platform, "amd64") != 0 && strcmp(bam_platform, "i86pc") != 0) { error = 1; bam_error(_("invalid platform %s - must be " "amd64\n"), bam_platform); } break; case 'X': bam_is_hv = BAM_HV_PRESENT; break; case 'Z': bam_zfs = 1; break; case 'e': bam_extend = 1; break; case '?': error = 1; bam_error(_("invalid option or missing option " "argument: -%c\n"), optopt); break; default : error = 1; bam_error(_("invalid option or missing option " "argument: -%c\n"), c); break; } } /* * An alternate platform requires an alternate root */ if (bam_alt_platform && bam_alt_root == 0) { usage(); bam_exit(0); } /* * A command option must be specfied */ if (!bam_cmd) { if (bam_opt && strcmp(bam_opt, "all") == 0) { usage(); bam_exit(0); } bam_error(_("a command option must be specified\n")); error = 1; } if (error) { usage(); bam_exit(1); } if (optind > argc) { bam_error(_("Internal error: %s\n"), "parse_args"); bam_exit(1); } else if (optind < argc) { bam_argv = &argv[optind]; bam_argc = argc - optind; } /* * mbr and pool are options for install_bootloader */ if (bam_cmd != BAM_INSTALL && (bam_mbr || bam_pool != NULL)) { usage(); bam_exit(0); } /* * -n implies verbose mode */ if (bam_check) bam_verbose = 1; } error_t check_subcmd_and_options( char *subcmd, char *opt, subcmd_defn_t *table, error_t (**fp)()) { int i; if (subcmd == NULL) { bam_error(_("this command requires a sub-command\n")); return (BAM_ERROR); } if (strcmp(subcmd, "set_option") == 0) { if (bam_argc == 0 || bam_argv == NULL || bam_argv[0] == NULL) { bam_error(_("missing argument for sub-command\n")); usage(); return (BAM_ERROR); } else if (bam_argc > 1 || bam_argv[1] != NULL) { bam_error(_("invalid trailing arguments\n")); usage(); return (BAM_ERROR); } } else if (strcmp(subcmd, "update_all") == 0) { /* * The only option we accept for the "update_all" * subcmd is "fastboot". */ if (bam_argc > 1 || (bam_argc == 1 && strcmp(bam_argv[0], "fastboot") != 0)) { bam_error(_("invalid trailing arguments\n")); usage(); return (BAM_ERROR); } if (bam_argc == 1) sync_menu = 0; } else if (((strcmp(subcmd, "enable_hypervisor") != 0) && (strcmp(subcmd, "list_setting") != 0)) && (bam_argc || bam_argv)) { /* * Of the remaining subcommands, only "enable_hypervisor" and * "list_setting" take trailing arguments. */ bam_error(_("invalid trailing arguments\n")); usage(); return (BAM_ERROR); } if (bam_root == NULL) { bam_root = rootbuf; bam_rootlen = 1; } /* verify that subcmd is valid */ for (i = 0; table[i].subcmd != NULL; i++) { if (strcmp(table[i].subcmd, subcmd) == 0) break; } if (table[i].subcmd == NULL) { bam_error(_("invalid sub-command specified: %s\n"), subcmd); return (BAM_ERROR); } if (table[i].unpriv == 0 && geteuid() != 0) { bam_error(_("you must be root to run this command\n")); return (BAM_ERROR); } /* * Currently only privileged commands need a lock */ if (table[i].unpriv == 0) bam_lock(); /* subcmd verifies that opt is appropriate */ if (table[i].option != OPT_OPTIONAL) { if ((table[i].option == OPT_REQ) ^ (opt != NULL)) { if (opt) bam_error(_("this sub-command (%s) does not " "take options\n"), subcmd); else bam_error(_("an option is required for this " "sub-command: %s\n"), subcmd); return (BAM_ERROR); } } *fp = table[i].handler; return (BAM_SUCCESS); } /* * NOTE: A single "/" is also considered a trailing slash and will * be deleted. */ void elide_trailing_slash(const char *src, char *dst, size_t dstsize) { size_t dstlen; assert(src); assert(dst); (void) strlcpy(dst, src, dstsize); dstlen = strlen(dst); if (dst[dstlen - 1] == '/') { dst[dstlen - 1] = '\0'; } } static int is_safe_exec(char *path) { struct stat sb; if (lstat(path, &sb) != 0) { bam_error(_("stat of file failed: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } if (!S_ISREG(sb.st_mode)) { bam_error(_("%s is not a regular file, skipping\n"), path); return (BAM_ERROR); } if (sb.st_uid != getuid()) { bam_error(_("%s is not owned by %d, skipping\n"), path, getuid()); return (BAM_ERROR); } if (sb.st_mode & S_IWOTH || sb.st_mode & S_IWGRP) { bam_error(_("%s is others or group writable, skipping\n"), path); return (BAM_ERROR); } return (BAM_SUCCESS); } static error_t list_setting(menu_t *mp, char *which, char *setting) { line_t *lp; entry_t *ent; char *p = which; int entry; int found; assert(which); assert(setting); if (*which != '\0') { /* * If "which" is not a number, assume it's a setting we want * to look for and so set up the routine to look for "which" * in the default entry. */ while (*p != '\0') if (!(isdigit((int)*p++))) { setting = which; which = mp->curdefault->arg; break; } } else { which = mp->curdefault->arg; } entry = atoi(which); for (ent = mp->entries; ((ent != NULL) && (ent->entryNum != entry)); ent = ent->next) ; if (!ent) { bam_error(_("no matching entry found\n")); return (BAM_ERROR); } found = (*setting == '\0'); for (lp = ent->start; lp != NULL; lp = lp->next) { if ((*setting == '\0') && (lp->flags != BAM_COMMENT)) bam_print("%s\n", lp->line); else if (lp->cmd != NULL && strcmp(setting, lp->cmd) == 0) { bam_print("%s\n", lp->arg); found = 1; } if (lp == ent->end) break; } if (!found) { bam_error(_("no matching entry found\n")); return (BAM_ERROR); } return (BAM_SUCCESS); } static error_t install_bootloader(void) { nvlist_t *nvl; uint16_t flags = 0; int found = 0; struct extmnttab mnt; struct stat statbuf = {0}; be_node_list_t *be_nodes, *node; FILE *fp; char *root_ds = NULL; int ret = BAM_ERROR; if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) { bam_error(_("out of memory\n")); return (ret); } /* * if bam_alt_root is set, the stage files are used from alt root. * if pool is set, the target devices are pool devices, stage files * are read from pool bootfs unless alt root is set. * * use arguments as targets, stage files are from alt or current root * if no arguments and no pool, install on current boot pool. */ if (bam_alt_root) { if (stat(bam_root, &statbuf) != 0) { bam_error(_("stat of file failed: %s: %s\n"), bam_root, strerror(errno)); goto done; } if ((fp = fopen(MNTTAB, "r")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(errno)); goto done; } resetmnttab(fp); while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) { if (mnt.mnt_major == major(statbuf.st_dev) && mnt.mnt_minor == minor(statbuf.st_dev)) { found = 1; root_ds = strdup(mnt.mnt_special); break; } } (void) fclose(fp); if (found == 0) { bam_error(_("alternate root %s not in mnttab\n"), bam_root); goto done; } if (root_ds == NULL) { bam_error(_("out of memory\n")); goto done; } if (be_list(NULL, &be_nodes, BE_LIST_DEFAULT) != BE_SUCCESS) { bam_error(_("No BE's found\n")); goto done; } for (node = be_nodes; node != NULL; node = node->be_next_node) if (strcmp(root_ds, node->be_root_ds) == 0) break; if (node == NULL) bam_error(_("BE (%s) does not exist\n"), root_ds); free(root_ds); root_ds = NULL; if (node == NULL) { be_free_list(be_nodes); goto done; } ret = nvlist_add_string(nvl, BE_ATTR_ORIG_BE_NAME, node->be_node_name); ret |= nvlist_add_string(nvl, BE_ATTR_ORIG_BE_ROOT, node->be_root_ds); be_free_list(be_nodes); if (ret != 0) { ret = BAM_ERROR; goto done; } } if (bam_force) flags |= BE_INSTALLBOOT_FLAG_FORCE; if (bam_mbr) flags |= BE_INSTALLBOOT_FLAG_MBR; if (bam_verbose) flags |= BE_INSTALLBOOT_FLAG_VERBOSE; if (nvlist_add_uint16(nvl, BE_ATTR_INSTALL_FLAGS, flags) != 0) { bam_error(_("out of memory\n")); ret = BAM_ERROR; goto done; } /* * if altroot was set, we got be name and be root, only need * to set pool name as target. * if no altroot, need to find be name and root from pool. */ if (bam_pool != NULL) { ret = nvlist_add_string(nvl, BE_ATTR_ORIG_BE_POOL, bam_pool); if (ret != 0) { ret = BAM_ERROR; goto done; } if (found) { ret = be_installboot(nvl); if (ret != 0) ret = BAM_ERROR; goto done; } } if (be_list(NULL, &be_nodes, BE_LIST_DEFAULT) != BE_SUCCESS) { bam_error(_("No BE's found\n")); ret = BAM_ERROR; goto done; } if (bam_pool != NULL) { /* * find active be_node in bam_pool */ for (node = be_nodes; node != NULL; node = node->be_next_node) { if (strcmp(bam_pool, node->be_rpool) != 0) continue; if (node->be_active_on_boot) break; } if (node == NULL) { bam_error(_("No active BE in %s\n"), bam_pool); be_free_list(be_nodes); ret = BAM_ERROR; goto done; } ret = nvlist_add_string(nvl, BE_ATTR_ORIG_BE_NAME, node->be_node_name); ret |= nvlist_add_string(nvl, BE_ATTR_ORIG_BE_ROOT, node->be_root_ds); be_free_list(be_nodes); if (ret != 0) { ret = BAM_ERROR; goto done; } ret = be_installboot(nvl); if (ret != 0) ret = BAM_ERROR; goto done; } /* * get dataset for "/" and fill up the args. */ if ((fp = fopen(MNTTAB, "r")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(errno)); ret = BAM_ERROR; be_free_list(be_nodes); goto done; } resetmnttab(fp); found = 0; while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) { if (strcmp(mnt.mnt_mountp, "/") == 0) { found = 1; root_ds = strdup(mnt.mnt_special); break; } } (void) fclose(fp); if (found == 0) { bam_error(_("alternate root %s not in mnttab\n"), "/"); ret = BAM_ERROR; be_free_list(be_nodes); goto done; } if (root_ds == NULL) { bam_error(_("out of memory\n")); ret = BAM_ERROR; be_free_list(be_nodes); goto done; } for (node = be_nodes; node != NULL; node = node->be_next_node) { if (strcmp(root_ds, node->be_root_ds) == 0) break; } if (node == NULL) { bam_error(_("No such BE: %s\n"), root_ds); free(root_ds); be_free_list(be_nodes); ret = BAM_ERROR; goto done; } free(root_ds); ret = nvlist_add_string(nvl, BE_ATTR_ORIG_BE_NAME, node->be_node_name); ret |= nvlist_add_string(nvl, BE_ATTR_ORIG_BE_ROOT, node->be_root_ds); ret |= nvlist_add_string(nvl, BE_ATTR_ORIG_BE_POOL, node->be_rpool); be_free_list(be_nodes); if (ret != 0) ret = BAM_ERROR; else ret = be_installboot(nvl) ? BAM_ERROR : 0; done: nvlist_free(nvl); return (ret); } static error_t bam_install(char *subcmd, char *opt) { error_t (*f)(void); /* * Check arguments */ if (check_subcmd_and_options(subcmd, opt, inst_subcmds, &f) == BAM_ERROR) return (BAM_ERROR); return (f()); } static error_t bam_menu(char *subcmd, char *opt, int largc, char *largv[]) { error_t ret; char menu_path[PATH_MAX]; char clean_menu_root[PATH_MAX]; char path[PATH_MAX]; menu_t *menu; char menu_root[PATH_MAX]; struct stat sb; error_t (*f)(menu_t *mp, char *menu_path, char *opt); char *special = NULL; char *pool = NULL; zfs_mnted_t zmnted; char *zmntpt = NULL; char *osdev; char *osroot; const char *fcn = "bam_menu()"; /* * Menu sub-command only applies to GRUB (i.e. x86) */ if (!is_grub(bam_alt_root ? bam_root : "/")) { bam_error(_("not a GRUB 0.97 based Illumos instance. " "Operation not supported\n")); return (BAM_ERROR); } /* * Check arguments */ ret = check_subcmd_and_options(subcmd, opt, menu_subcmds, &f); if (ret == BAM_ERROR) { return (BAM_ERROR); } assert(bam_root); (void) strlcpy(menu_root, bam_root, sizeof (menu_root)); osdev = osroot = NULL; if (strcmp(subcmd, "update_entry") == 0) { assert(opt); osdev = strtok(opt, ","); assert(osdev); osroot = strtok(NULL, ","); if (osroot) { /* fixup bam_root so that it points at osroot */ if (realpath(osroot, rootbuf) == NULL) { bam_error(_("cannot resolve path %s: %s\n"), osroot, strerror(errno)); return (BAM_ERROR); } bam_alt_root = 1; bam_root = rootbuf; bam_rootlen = strlen(rootbuf); } } /* * We support menu on PCFS (under certain conditions), but * not the OS root */ if (is_pcfs(bam_root)) { bam_error(_("root <%s> on PCFS is not supported\n"), bam_root); return (BAM_ERROR); } if (stat(menu_root, &sb) == -1) { bam_error(_("cannot find GRUB menu\n")); return (BAM_ERROR); } BAM_DPRINTF(("%s: menu root is %s\n", fcn, menu_root)); /* * We no longer use the GRUB slice file. If it exists, then * the user is doing something that is unsupported (such as * standard upgrading an old Live Upgrade BE). If that * happens, mimic existing behavior i.e. pretend that it is * not a BE. Emit a warning though. */ if (bam_alt_root) { (void) snprintf(path, sizeof (path), "%s%s", bam_root, GRUB_slice); } else { (void) snprintf(path, sizeof (path), "%s", GRUB_slice); } if (bam_verbose && stat(path, &sb) == 0) bam_error(_("unsupported GRUB slice file (%s) exists - " "ignoring.\n"), path); if (is_zfs(menu_root)) { assert(strcmp(menu_root, bam_root) == 0); special = get_special(menu_root); INJECT_ERROR1("Z_MENU_GET_SPECIAL", special = NULL); if (special == NULL) { bam_error(_("cant find special file for " "mount-point %s\n"), menu_root); return (BAM_ERROR); } pool = strtok(special, "/"); INJECT_ERROR1("Z_MENU_GET_POOL", pool = NULL); if (pool == NULL) { free(special); bam_error(_("cant find pool for mount-point %s\n"), menu_root); return (BAM_ERROR); } BAM_DPRINTF(("%s: derived pool=%s from special\n", fcn, pool)); zmntpt = mount_top_dataset(pool, &zmnted); INJECT_ERROR1("Z_MENU_MOUNT_TOP_DATASET", zmntpt = NULL); if (zmntpt == NULL) { bam_error(_("cannot mount pool dataset for pool: %s\n"), pool); free(special); return (BAM_ERROR); } BAM_DPRINTF(("%s: top dataset mountpoint=%s\n", fcn, zmntpt)); (void) strlcpy(menu_root, zmntpt, sizeof (menu_root)); BAM_DPRINTF(("%s: zfs menu_root=%s\n", fcn, menu_root)); } elide_trailing_slash(menu_root, clean_menu_root, sizeof (clean_menu_root)); BAM_DPRINTF(("%s: cleaned menu root is <%s>\n", fcn, clean_menu_root)); (void) strlcpy(menu_path, clean_menu_root, sizeof (menu_path)); (void) strlcat(menu_path, GRUB_MENU, sizeof (menu_path)); BAM_DPRINTF(("%s: menu path is: %s\n", fcn, menu_path)); /* * If listing the menu, display the menu location */ if (strcmp(subcmd, "list_entry") == 0) bam_print(_("the location for the active GRUB menu is: %s\n"), menu_path); if ((menu = menu_read(menu_path)) == NULL) { bam_error(_("cannot find GRUB menu file: %s\n"), menu_path); free(special); return (BAM_ERROR); } /* * We already checked the following case in * check_subcmd_and_suboptions() above. Complete the * final step now. */ if (strcmp(subcmd, "set_option") == 0) { assert(largc == 1 && largv[0] && largv[1] == NULL); opt = largv[0]; } else if ((strcmp(subcmd, "enable_hypervisor") != 0) && (strcmp(subcmd, "list_setting") != 0)) { assert(largc == 0 && largv == NULL); } ret = get_boot_cap(bam_root); if (ret != BAM_SUCCESS) { BAM_DPRINTF(("%s: Failed to get boot capability\n", fcn)); goto out; } /* * Once the sub-cmd handler has run * only the line field is guaranteed to have valid values */ if (strcmp(subcmd, "update_entry") == 0) { ret = f(menu, menu_root, osdev); } else if (strcmp(subcmd, "upgrade") == 0) { ret = f(menu, bam_root, menu_root); } else if (strcmp(subcmd, "list_entry") == 0) { ret = f(menu, menu_path, opt); } else if (strcmp(subcmd, "list_setting") == 0) { ret = f(menu, ((largc > 0) ? largv[0] : ""), ((largc > 1) ? largv[1] : "")); } else if (strcmp(subcmd, "disable_hypervisor") == 0) { if (is_sparc()) { bam_error(_("%s operation unsupported on SPARC " "machines\n"), subcmd); ret = BAM_ERROR; } else { ret = f(menu, bam_root, NULL); } } else if (strcmp(subcmd, "enable_hypervisor") == 0) { if (is_sparc()) { bam_error(_("%s operation unsupported on SPARC " "machines\n"), subcmd); ret = BAM_ERROR; } else { char *extra_args = NULL; /* * Compress all arguments passed in the largv[] array * into one string that can then be appended to the * end of the kernel$ string the routine to enable the * hypervisor will build. * * This allows the caller to supply arbitrary unparsed * arguments, such as dom0 memory settings or APIC * options. * * This concatenation will be done without ANY syntax * checking whatsoever, so it's the responsibility of * the caller to make sure the arguments are valid and * do not duplicate arguments the conversion routines * may create. */ if (largc > 0) { int extra_len, i; for (extra_len = 0, i = 0; i < largc; i++) extra_len += strlen(largv[i]); /* * Allocate space for argument strings, * intervening spaces and terminating NULL. */ extra_args = alloca(extra_len + largc); (void) strcpy(extra_args, largv[0]); for (i = 1; i < largc; i++) { (void) strcat(extra_args, " "); (void) strcat(extra_args, largv[i]); } } ret = f(menu, bam_root, extra_args); } } else ret = f(menu, NULL, opt); if (ret == BAM_WRITE) { BAM_DPRINTF(("%s: writing menu to clean-menu-root: <%s>\n", fcn, clean_menu_root)); ret = menu_write(clean_menu_root, menu); } out: INJECT_ERROR1("POOL_SET", pool = "/pooldata"); assert((is_zfs(menu_root)) ^ (pool == NULL)); if (pool) { (void) umount_top_dataset(pool, zmnted, zmntpt); free(special); } menu_free(menu); return (ret); } static error_t bam_archive( char *subcmd, char *opt) { error_t ret; error_t (*f)(char *root, char *opt); const char *fcn = "bam_archive()"; /* * Add trailing / for archive subcommands */ if (rootbuf[strlen(rootbuf) - 1] != '/') (void) strcat(rootbuf, "/"); bam_rootlen = strlen(rootbuf); /* * Check arguments */ ret = check_subcmd_and_options(subcmd, opt, arch_subcmds, &f); if (ret != BAM_SUCCESS) { return (BAM_ERROR); } ret = get_boot_cap(rootbuf); if (ret != BAM_SUCCESS) { BAM_DPRINTF(("%s: Failed to get boot capability\n", fcn)); return (ret); } /* * Check archive not supported with update_all * since it is awkward to display out-of-sync * information for each BE. */ if (bam_check && strcmp(subcmd, "update_all") == 0) { bam_error(_("the check option is not supported with " "subcmd: %s\n"), subcmd); return (BAM_ERROR); } if (strcmp(subcmd, "update_all") == 0) bam_update_all = 1; ret = f(bam_root, opt); bam_update_all = 0; return (ret); } /*PRINTFLIKE1*/ void bam_error(char *format, ...) { va_list ap; va_start(ap, format); (void) fprintf(stderr, "%s: ", prog); (void) vfprintf(stderr, format, ap); va_end(ap); } /*PRINTFLIKE1*/ void bam_derror(char *format, ...) { va_list ap; assert(bam_debug); va_start(ap, format); (void) fprintf(stderr, "DEBUG: "); (void) vfprintf(stderr, format, ap); va_end(ap); } /*PRINTFLIKE1*/ void bam_print(char *format, ...) { va_list ap; va_start(ap, format); (void) vfprintf(stdout, format, ap); va_end(ap); } /*PRINTFLIKE1*/ void bam_print_stderr(char *format, ...) { va_list ap; va_start(ap, format); (void) vfprintf(stderr, format, ap); va_end(ap); } void bam_exit(int excode) { restore_env(); bam_unlock(); exit(excode); } static void bam_lock(void) { struct flock lock; pid_t pid; if (bam_skip_lock) return; bam_lock_fd = open(BAM_LOCK_FILE, O_CREAT|O_RDWR, LOCK_FILE_PERMS); if (bam_lock_fd < 0) { /* * We may be invoked early in boot for archive verification. * In this case, root is readonly and /var/run may not exist. * Proceed without the lock */ if (errno == EROFS || errno == ENOENT) { bam_root_readonly = 1; return; } bam_error(_("failed to open file: %s: %s\n"), BAM_LOCK_FILE, strerror(errno)); bam_exit(1); } lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(bam_lock_fd, F_SETLK, &lock) == -1) { if (errno != EACCES && errno != EAGAIN) { bam_error(_("failed to lock file: %s: %s\n"), BAM_LOCK_FILE, strerror(errno)); (void) close(bam_lock_fd); bam_lock_fd = -1; bam_exit(1); } pid = 0; (void) pread(bam_lock_fd, &pid, sizeof (pid_t), 0); bam_print( _("another instance of bootadm (pid %lu) is running\n"), pid); lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; if (fcntl(bam_lock_fd, F_SETLKW, &lock) == -1) { bam_error(_("failed to lock file: %s: %s\n"), BAM_LOCK_FILE, strerror(errno)); (void) close(bam_lock_fd); bam_lock_fd = -1; bam_exit(1); } } /* We own the lock now */ pid = getpid(); (void) write(bam_lock_fd, &pid, sizeof (pid)); } static void bam_unlock(void) { struct flock unlock; if (bam_skip_lock) return; /* * NOP if we don't hold the lock */ if (bam_lock_fd < 0) { return; } unlock.l_type = F_UNLCK; unlock.l_whence = SEEK_SET; unlock.l_start = 0; unlock.l_len = 0; if (fcntl(bam_lock_fd, F_SETLK, &unlock) == -1) { bam_error(_("failed to unlock file: %s: %s\n"), BAM_LOCK_FILE, strerror(errno)); } if (close(bam_lock_fd) == -1) { bam_error(_("failed to close file: %s: %s\n"), BAM_LOCK_FILE, strerror(errno)); } bam_lock_fd = -1; } static error_t list_archive(char *root, char *opt) { filelist_t flist; filelist_t *flistp = &flist; line_t *lp; assert(root); assert(opt == NULL); flistp->head = flistp->tail = NULL; if (read_list(root, flistp) != BAM_SUCCESS) { return (BAM_ERROR); } assert(flistp->head && flistp->tail); for (lp = flistp->head; lp; lp = lp->next) { bam_print(_("%s\n"), lp->line); } filelist_free(flistp); return (BAM_SUCCESS); } /* * This routine writes a list of lines to a file. * The list is *not* freed */ static error_t list2file(char *root, char *tmp, char *final, line_t *start) { char tmpfile[PATH_MAX]; char path[PATH_MAX]; FILE *fp; int ret; struct stat sb; mode_t mode; uid_t root_uid; gid_t sys_gid; struct passwd *pw; struct group *gp; const char *fcn = "list2file()"; (void) snprintf(path, sizeof (path), "%s%s", root, final); if (start == NULL) { /* Empty GRUB menu */ if (stat(path, &sb) != -1) { bam_print(_("file is empty, deleting file: %s\n"), path); if (unlink(path) != 0) { bam_error(_("failed to unlink file: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } else { return (BAM_SUCCESS); } } return (BAM_SUCCESS); } /* * Preserve attributes of existing file if possible, * otherwise ask the system for uid/gid of root/sys. * If all fails, fall back on hard-coded defaults. */ if (stat(path, &sb) != -1) { mode = sb.st_mode; root_uid = sb.st_uid; sys_gid = sb.st_gid; } else { mode = DEFAULT_DEV_MODE; if ((pw = getpwnam(DEFAULT_DEV_USER)) != NULL) { root_uid = pw->pw_uid; } else { bam_error(_("getpwnam: uid for %s failed, " "defaulting to %d\n"), DEFAULT_DEV_USER, DEFAULT_DEV_UID); root_uid = (uid_t)DEFAULT_DEV_UID; } if ((gp = getgrnam(DEFAULT_DEV_GROUP)) != NULL) { sys_gid = gp->gr_gid; } else { bam_error(_("getgrnam: gid for %s failed, " "defaulting to %d\n"), DEFAULT_DEV_GROUP, DEFAULT_DEV_GID); sys_gid = (gid_t)DEFAULT_DEV_GID; } } (void) snprintf(tmpfile, sizeof (tmpfile), "%s%s", root, tmp); /* Truncate tmpfile first */ fp = fopen(tmpfile, "w"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } ret = fclose(fp); INJECT_ERROR1("LIST2FILE_TRUNC_FCLOSE", ret = EOF); if (ret == EOF) { bam_error(_("failed to close file: %s: %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } /* Now open it in append mode */ fp = fopen(tmpfile, "a"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } for (; start; start = start->next) { ret = s_fputs(start->line, fp); INJECT_ERROR1("LIST2FILE_FPUTS", ret = EOF); if (ret == EOF) { bam_error(_("write to file failed: %s: %s\n"), tmpfile, strerror(errno)); (void) fclose(fp); return (BAM_ERROR); } } ret = fclose(fp); INJECT_ERROR1("LIST2FILE_APPEND_FCLOSE", ret = EOF); if (ret == EOF) { bam_error(_("failed to close file: %s: %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } /* * Set up desired attributes. Ignore failures on filesystems * not supporting these operations - pcfs reports unsupported * operations as EINVAL. */ ret = chmod(tmpfile, mode); if (ret == -1 && errno != EINVAL && errno != ENOTSUP) { bam_error(_("chmod operation on %s failed - %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } ret = chown(tmpfile, root_uid, sys_gid); if (ret == -1 && errno != EINVAL && errno != ENOTSUP) { bam_error(_("chgrp operation on %s failed - %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } /* * Do an atomic rename */ ret = rename(tmpfile, path); INJECT_ERROR1("LIST2FILE_RENAME", ret = -1); if (ret != 0) { bam_error(_("rename to file failed: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } BAM_DPRINTF(("%s: wrote file successfully: %s\n", fcn, path)); return (BAM_SUCCESS); } /* * Checks if the path specified (without the file name at the end) exists * and creates it if not. If the path exists and is not a directory, an attempt * to unlink is made. */ static int setup_path(char *path) { char *p; int ret; struct stat sb; p = strrchr(path, '/'); if (p != NULL) { *p = '\0'; if (stat(path, &sb) != 0 || !(S_ISDIR(sb.st_mode))) { /* best effort attempt, mkdirp will catch the error */ (void) unlink(path); if (bam_verbose) bam_print(_("need to create directory " "path for %s\n"), path); ret = mkdirp(path, DIR_PERMS); if (ret == -1) { bam_error(_("mkdir of %s failed: %s\n"), path, strerror(errno)); *p = '/'; return (BAM_ERROR); } } *p = '/'; return (BAM_SUCCESS); } return (BAM_SUCCESS); } typedef union { gzFile gzfile; int fdfile; } outfile; typedef struct { char path[PATH_MAX]; outfile out; } cachefile; static int setup_file(char *base, const char *path, cachefile *cf) { int ret; char *strip; /* init gzfile or fdfile in case we fail before opening */ if (bam_direct == BAM_DIRECT_DBOOT) cf->out.gzfile = NULL; else cf->out.fdfile = -1; /* strip the trailing altroot path */ strip = (char *)path + strlen(rootbuf); ret = snprintf(cf->path, sizeof (cf->path), "%s/%s", base, strip); if (ret >= sizeof (cf->path)) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } /* Check if path is present in the archive cache directory */ if (setup_path(cf->path) == BAM_ERROR) return (BAM_ERROR); if (bam_direct == BAM_DIRECT_DBOOT) { if ((cf->out.gzfile = gzopen(cf->path, "wb")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), cf->path, strerror(errno)); return (BAM_ERROR); } (void) gzsetparams(cf->out.gzfile, Z_BEST_SPEED, Z_DEFAULT_STRATEGY); } else { if ((cf->out.fdfile = open(cf->path, O_WRONLY | O_CREAT, 0644)) == -1) { bam_error(_("failed to open file: %s: %s\n"), cf->path, strerror(errno)); return (BAM_ERROR); } } return (BAM_SUCCESS); } static int cache_write(cachefile cf, char *buf, int size) { int err; if (bam_direct == BAM_DIRECT_DBOOT) { if (gzwrite(cf.out.gzfile, buf, size) < 1) { bam_error(_("failed to write to %s\n"), gzerror(cf.out.gzfile, &err)); if (err == Z_ERRNO && bam_verbose) { bam_error(_("write to file failed: %s: %s\n"), cf.path, strerror(errno)); } return (BAM_ERROR); } } else { if (write(cf.out.fdfile, buf, size) < 1) { bam_error(_("write to file failed: %s: %s\n"), cf.path, strerror(errno)); return (BAM_ERROR); } } return (BAM_SUCCESS); } static int cache_close(cachefile cf) { int ret; if (bam_direct == BAM_DIRECT_DBOOT) { if (cf.out.gzfile) { ret = gzclose(cf.out.gzfile); if (ret != Z_OK) { bam_error(_("failed to close file: %s: %s\n"), cf.path, strerror(errno)); return (BAM_ERROR); } } } else { if (cf.out.fdfile != -1) { ret = close(cf.out.fdfile); if (ret != 0) { bam_error(_("failed to close file: %s: %s\n"), cf.path, strerror(errno)); return (BAM_ERROR); } } } return (BAM_SUCCESS); } static int dircache_updatefile(const char *path) { int ret, exitcode; char buf[4096 * 4]; FILE *infile; cachefile outfile, outupdt; if (bam_nowrite()) { set_dir_flag(NEED_UPDATE); return (BAM_SUCCESS); } if (!has_cachedir()) return (BAM_SUCCESS); if ((infile = fopen(path, "rb")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } ret = setup_file(get_cachedir(), path, &outfile); if (ret == BAM_ERROR) { exitcode = BAM_ERROR; goto out; } if (!is_dir_flag_on(NO_EXTEND)) { ret = setup_file(get_updatedir(), path, &outupdt); if (ret == BAM_ERROR) set_dir_flag(NO_EXTEND); } while ((ret = fread(buf, 1, sizeof (buf), infile)) > 0) { if (cache_write(outfile, buf, ret) == BAM_ERROR) { exitcode = BAM_ERROR; goto out; } if (!is_dir_flag_on(NO_EXTEND)) if (cache_write(outupdt, buf, ret) == BAM_ERROR) set_dir_flag(NO_EXTEND); } set_dir_flag(NEED_UPDATE); get_count()++; if (get_count() > COUNT_MAX) set_dir_flag(NO_EXTEND); exitcode = BAM_SUCCESS; out: (void) fclose(infile); if (cache_close(outfile) == BAM_ERROR) exitcode = BAM_ERROR; if (!is_dir_flag_on(NO_EXTEND) && cache_close(outupdt) == BAM_ERROR) exitcode = BAM_ERROR; if (exitcode == BAM_ERROR) set_flag(UPDATE_ERROR); return (exitcode); } static int dircache_updatedir(const char *path, int updt) { int ret; char dpath[PATH_MAX]; char *strip; struct stat sb; strip = (char *)path + strlen(rootbuf); ret = snprintf(dpath, sizeof (dpath), "%s/%s", updt ? get_updatedir() : get_cachedir(), strip); if (ret >= sizeof (dpath)) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); set_flag(UPDATE_ERROR); return (BAM_ERROR); } if (stat(dpath, &sb) == 0 && S_ISDIR(sb.st_mode)) return (BAM_SUCCESS); if (updt) { if (!is_dir_flag_on(NO_EXTEND)) if (!bam_nowrite() && mkdirp(dpath, DIR_PERMS) == -1) set_dir_flag(NO_EXTEND); } else { if (!bam_nowrite() && mkdirp(dpath, DIR_PERMS) == -1) { set_flag(UPDATE_ERROR); return (BAM_ERROR); } } set_dir_flag(NEED_UPDATE); return (BAM_SUCCESS); } #define DO_CACHE_DIR 0 #define DO_UPDATE_DIR 1 #if defined(_LP64) || defined(_LONGLONG_TYPE) typedef Elf64_Ehdr _elfhdr; #else typedef Elf32_Ehdr _elfhdr; #endif /* * This routine updates the contents of the cache directory */ static int update_dircache(const char *path, int flags) { int rc = BAM_SUCCESS; switch (flags) { case FTW_F: { int fd; _elfhdr elf; if ((fd = open(path, O_RDONLY)) < 0) { bam_error(_("failed to open file: %s: %s\n"), path, strerror(errno)); set_flag(UPDATE_ERROR); rc = BAM_ERROR; break; } /* * libelf and gelf would be a cleaner and easier way to handle * this, but libelf fails compilation if _ILP32 is defined && * _FILE_OFFSET_BITS is != 32 ... */ if (read(fd, (void *)&elf, sizeof (_elfhdr)) < 0) { bam_error(_("read failed for file: %s: %s\n"), path, strerror(errno)); set_flag(UPDATE_ERROR); (void) close(fd); rc = BAM_ERROR; break; } (void) close(fd); if (memcmp(elf.e_ident, ELFMAG, 4) != 0) { /* Not an ELF file, include in archive */ rc = dircache_updatefile(path); } else { /* Include 64-bit ELF files only */ switch (elf.e_ident[EI_CLASS]) { case ELFCLASS32: bam_print(_("WARNING: ELF file %s is 32-bit " "and will be excluded\n"), path); break; case ELFCLASS64: rc = dircache_updatefile(path); break; default: bam_print(_("WARNING: ELF file %s is neither " "32-bit nor 64-bit\n"), path); break; } } break; } case FTW_D: if (strstr(path, "/amd64") != NULL) { if (has_cachedir()) { rc = dircache_updatedir(path, DO_UPDATE_DIR); if (rc == BAM_SUCCESS) rc = dircache_updatedir(path, DO_CACHE_DIR); } } break; default: rc = BAM_ERROR; break; } return (rc); } /*ARGSUSED*/ static int cmpstat( const char *file, const struct stat *st, int flags, struct FTW *ftw) { uint_t sz; uint64_t *value; uint64_t filestat[2]; int error, ret, status; struct safefile *safefilep; FILE *fp; struct stat sb; regex_t re; /* * On SPARC we create/update links too. */ if (flags != FTW_F && flags != FTW_D && (flags == FTW_SL && !is_flag_on(IS_SPARC_TARGET))) return (0); /* * Ignore broken links */ if (flags == FTW_SL && stat(file, &sb) < 0) return (0); /* * new_nvlp may be NULL if there were errors earlier * but this is not fatal to update determination. */ if (walk_arg.new_nvlp) { filestat[0] = st->st_size; filestat[1] = st->st_mtime; error = nvlist_add_uint64_array(walk_arg.new_nvlp, file + bam_rootlen, filestat, 2); if (error) bam_error(_("failed to update stat data for: %s: %s\n"), file, strerror(error)); } /* * If we are invoked as part of system/filesystem/boot-archive, then * there are a number of things we should not worry about */ if (bam_smf_check) { /* ignore amd64 modules unless we are booted amd64. */ if (!is_amd64() && strstr(file, "/amd64/") != 0) return (0); /* read in list of safe files */ if (safefiles == NULL) { fp = fopen("/boot/solaris/filelist.safe", "r"); if (fp != NULL) { safefiles = s_calloc(1, sizeof (struct safefile)); safefilep = safefiles; safefilep->name = s_calloc(1, MAXPATHLEN + MAXNAMELEN); safefilep->next = NULL; while (s_fgets(safefilep->name, MAXPATHLEN + MAXNAMELEN, fp) != NULL) { safefilep->next = s_calloc(1, sizeof (struct safefile)); safefilep = safefilep->next; safefilep->name = s_calloc(1, MAXPATHLEN + MAXNAMELEN); safefilep->next = NULL; } (void) fclose(fp); } } } /* * On SPARC we create a -path-list file for mkisofs */ if (is_flag_on(IS_SPARC_TARGET) && !bam_nowrite()) { if (flags != FTW_D) { char *strip; strip = (char *)file + strlen(rootbuf); (void) fprintf(walk_arg.sparcfile, "/%s=%s\n", strip, file); } } /* * We are transitioning from the old model to the dircache or the cache * directory was removed: create the entry without further checkings. */ if (is_flag_on(NEED_CACHE_DIR)) { if (bam_verbose) bam_print(_(" new %s\n"), file); if (is_flag_on(IS_SPARC_TARGET)) { set_dir_flag(NEED_UPDATE); return (0); } ret = update_dircache(file, flags); if (ret == BAM_ERROR) { bam_error(_("directory cache update failed for %s\n"), file); return (-1); } return (0); } /* * We need an update if file doesn't exist in old archive */ if (walk_arg.old_nvlp == NULL || nvlist_lookup_uint64_array(walk_arg.old_nvlp, file + bam_rootlen, &value, &sz) != 0) { if (bam_smf_check) /* ignore new during smf check */ return (0); if (is_flag_on(IS_SPARC_TARGET)) { set_dir_flag(NEED_UPDATE); } else { ret = update_dircache(file, flags); if (ret == BAM_ERROR) { bam_error(_("directory cache update " "failed for %s\n"), file); return (-1); } } if (bam_verbose) bam_print(_(" new %s\n"), file); return (0); } /* * If we got there, the file is already listed as to be included in the * iso image. We just need to know if we are going to rebuild it or not */ if (is_flag_on(IS_SPARC_TARGET) && is_dir_flag_on(NEED_UPDATE) && !bam_nowrite()) return (0); /* * File exists in old archive. Check if file has changed */ assert(sz == 2); bcopy(value, filestat, sizeof (filestat)); if (flags != FTW_D && (filestat[0] != st->st_size || filestat[1] != st->st_mtime)) { if (bam_smf_check) { safefilep = safefiles; while (safefilep != NULL && safefilep->name[0] != '\0') { if (regcomp(&re, safefilep->name, REG_EXTENDED|REG_NOSUB) == 0) { status = regexec(&re, file + bam_rootlen, 0, NULL, 0); regfree(&re); if (status == 0) { (void) creat( NEED_UPDATE_SAFE_FILE, 0644); return (0); } } safefilep = safefilep->next; } } if (is_flag_on(IS_SPARC_TARGET)) { set_dir_flag(NEED_UPDATE); } else { ret = update_dircache(file, flags); if (ret == BAM_ERROR) { bam_error(_("directory cache update failed " "for %s\n"), file); return (-1); } } /* * Update self-assembly file if there are changes in * /etc/system.d directory */ if (strstr(file, ETC_SYSTEM_DIR)) { ret = update_dircache(self_assembly, flags); if (ret == BAM_ERROR) { bam_error(_("directory cache update failed " "for %s\n"), file); return (-1); } } if (bam_verbose) { if (bam_smf_check) bam_print(" %s\n", file); else bam_print(_(" changed %s\n"), file); } } return (0); } /* * Remove a directory path recursively */ static int rmdir_r(char *path) { struct dirent *d = NULL; DIR *dir = NULL; char tpath[PATH_MAX]; struct stat sb; if ((dir = opendir(path)) == NULL) return (-1); while ((d = readdir(dir)) != NULL) { if ((strcmp(d->d_name, ".") != 0) && (strcmp(d->d_name, "..") != 0)) { (void) snprintf(tpath, sizeof (tpath), "%s/%s", path, d->d_name); if (stat(tpath, &sb) == 0) { if (sb.st_mode & S_IFDIR) (void) rmdir_r(tpath); else (void) remove(tpath); } } } return (remove(path)); } /* * Check if cache directory exists and, if not, create it and update flags * accordingly. If the path exists, but it's not a directory, a best effort * attempt to remove and recreate it is made. * If the user requested a 'purge', always recreate the directory from scratch. */ static int set_cache_dir(char *root) { struct stat sb; int ret = 0; ret = build_path(get_cachedir(), sizeof (get_cachedir()), root, ARCHIVE_PREFIX, CACHEDIR_SUFFIX); if (ret >= sizeof (get_cachedir())) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } if (bam_purge || is_flag_on(INVALIDATE_CACHE)) (void) rmdir_r(get_cachedir()); if (stat(get_cachedir(), &sb) != 0 || !(S_ISDIR(sb.st_mode))) { /* best effort unlink attempt, mkdir will catch errors */ (void) unlink(get_cachedir()); if (bam_verbose) bam_print(_("archive cache directory not found: %s\n"), get_cachedir()); ret = mkdir(get_cachedir(), DIR_PERMS); if (ret < 0) { bam_error(_("mkdir of %s failed: %s\n"), get_cachedir(), strerror(errno)); get_cachedir()[0] = '\0'; return (ret); } set_flag(NEED_CACHE_DIR); set_dir_flag(NO_EXTEND); } return (BAM_SUCCESS); } static int set_update_dir(char *root) { struct stat sb; int ret; if (is_dir_flag_on(NO_EXTEND)) return (BAM_SUCCESS); if (!bam_extend) { set_dir_flag(NO_EXTEND); return (BAM_SUCCESS); } ret = build_path(get_updatedir(), sizeof (get_updatedir()), root, ARCHIVE_PREFIX, UPDATEDIR_SUFFIX); if (ret >= sizeof (get_updatedir())) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } if (stat(get_updatedir(), &sb) == 0) { if (S_ISDIR(sb.st_mode)) ret = rmdir_r(get_updatedir()); else ret = unlink(get_updatedir()); if (ret != 0) set_dir_flag(NO_EXTEND); } if (mkdir(get_updatedir(), DIR_PERMS) < 0) set_dir_flag(NO_EXTEND); return (BAM_SUCCESS); } static int is_valid_archive(char *root) { char archive_path[PATH_MAX]; char timestamp_path[PATH_MAX]; struct stat sb, timestamp; int ret; ret = build_path(archive_path, sizeof (archive_path), root, ARCHIVE_PREFIX, ARCHIVE_SUFFIX); if (ret >= sizeof (archive_path)) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } if (stat(archive_path, &sb) != 0) { if (bam_verbose && !bam_check) bam_print(_("archive not found: %s\n"), archive_path); set_dir_flag(NEED_UPDATE | NO_EXTEND); return (BAM_SUCCESS); } /* * The timestamp file is used to prevent stale files in the archive * cache. * Stale files can happen if the system is booted back and forth across * the transition from bootadm-before-the-cache to * bootadm-after-the-cache, since older versions of bootadm don't know * about the existence of the archive cache. * * Since only bootadm-after-the-cache versions know about about this * file, we require that the boot archive be older than this file. */ ret = snprintf(timestamp_path, sizeof (timestamp_path), "%s%s", root, FILE_STAT_TIMESTAMP); if (ret >= sizeof (timestamp_path)) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } if (stat(timestamp_path, ×tamp) != 0 || sb.st_mtime > timestamp.st_mtime) { if (bam_verbose && !bam_check) bam_print( _("archive cache is out of sync. Rebuilding.\n")); /* * Don't generate a false positive for the boot-archive service * but trigger an update of the archive cache in * boot-archive-update. */ if (bam_smf_check) { (void) creat(NEED_UPDATE_FILE, 0644); return (BAM_SUCCESS); } set_flag(INVALIDATE_CACHE); set_dir_flag(NEED_UPDATE | NO_EXTEND); return (BAM_SUCCESS); } if (is_flag_on(IS_SPARC_TARGET)) return (BAM_SUCCESS); if (bam_extend && sb.st_size > BA_SIZE_MAX) { if (bam_verbose && !bam_check) bam_print(_("archive %s is bigger than %d bytes and " "will be rebuilt\n"), archive_path, BA_SIZE_MAX); set_dir_flag(NO_EXTEND); } return (BAM_SUCCESS); } /* * Check flags and presence of required files and directories. * The force flag and/or absence of files should * trigger an update. * Suppress stdout output if check (-n) option is set * (as -n should only produce parseable output.) */ static int check_flags_and_files(char *root) { struct stat sb; int ret; /* * If archive is missing, create archive */ ret = is_valid_archive(root); if (ret == BAM_ERROR) return (BAM_ERROR); if (bam_nowrite()) return (BAM_SUCCESS); /* * check if cache directories exist on x86. * check (and always open) the cache file on SPARC. */ if (is_sparc()) { ret = snprintf(get_cachedir(), sizeof (get_cachedir()), "%s%s%s/%s", root, ARCHIVE_PREFIX, get_machine(), CACHEDIR_SUFFIX); if (ret >= sizeof (get_cachedir())) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), rootbuf); return (BAM_ERROR); } if (stat(get_cachedir(), &sb) != 0) { set_flag(NEED_CACHE_DIR); set_dir_flag(NEED_UPDATE); } walk_arg.sparcfile = fopen(get_cachedir(), "w"); if (walk_arg.sparcfile == NULL) { bam_error(_("failed to open file: %s: %s\n"), get_cachedir(), strerror(errno)); return (BAM_ERROR); } set_dir_present(); } else { if (set_cache_dir(root) != 0) return (BAM_ERROR); set_dir_present(); if (set_update_dir(root) != 0) return (BAM_ERROR); } /* * if force, create archive unconditionally */ if (bam_force) { set_dir_flag(NEED_UPDATE); if (bam_verbose) bam_print(_("forced update of archive requested\n")); return (BAM_SUCCESS); } return (BAM_SUCCESS); } static error_t read_one_list(char *root, filelist_t *flistp, char *filelist) { char path[PATH_MAX]; FILE *fp; char buf[BAM_MAXLINE]; const char *fcn = "read_one_list()"; (void) snprintf(path, sizeof (path), "%s%s", root, filelist); fp = fopen(path, "r"); if (fp == NULL) { BAM_DPRINTF(("%s: failed to open archive filelist: %s: %s\n", fcn, path, strerror(errno))); return (BAM_ERROR); } while (s_fgets(buf, sizeof (buf), fp) != NULL) { /* skip blank lines */ if (strspn(buf, " \t") == strlen(buf)) continue; append_to_flist(flistp, buf); } if (fclose(fp) != 0) { bam_error(_("failed to close file: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } return (BAM_SUCCESS); } static error_t read_list(char *root, filelist_t *flistp) { char path[PATH_MAX]; char cmd[PATH_MAX]; struct stat sb; int n, rval; const char *fcn = "read_list()"; flistp->head = flistp->tail = NULL; /* * build and check path to extract_boot_filelist.ksh */ n = snprintf(path, sizeof (path), "%s%s", root, EXTRACT_BOOT_FILELIST); if (n >= sizeof (path)) { bam_error(_("archive filelist is empty\n")); return (BAM_ERROR); } if (is_safe_exec(path) == BAM_ERROR) return (BAM_ERROR); /* * If extract_boot_filelist is present, exec it, otherwise read * the filelists directly, for compatibility with older images. */ if (stat(path, &sb) == 0) { /* * build arguments to exec extract_boot_filelist.ksh */ char *rootarg, *platarg; int platarglen = 1, rootarglen = 1; if (strlen(root) > 1) rootarglen += strlen(root) + strlen("-R "); if (bam_alt_platform) platarglen += strlen(bam_platform) + strlen("-p "); platarg = s_calloc(1, platarglen); rootarg = s_calloc(1, rootarglen); *platarg = 0; *rootarg = 0; if (strlen(root) > 1) { (void) snprintf(rootarg, rootarglen, "-R %s", root); } if (bam_alt_platform) { (void) snprintf(platarg, platarglen, "-p %s", bam_platform); } n = snprintf(cmd, sizeof (cmd), "%s %s %s /%s /%s", path, rootarg, platarg, BOOT_FILE_LIST, ETC_FILE_LIST); free(platarg); free(rootarg); if (n >= sizeof (cmd)) { bam_error(_("archive filelist is empty\n")); return (BAM_ERROR); } if (exec_cmd(cmd, flistp) != 0) { BAM_DPRINTF(("%s: failed to open archive " "filelist: %s: %s\n", fcn, path, strerror(errno))); return (BAM_ERROR); } } else { /* * Read current lists of files - only the first is mandatory */ rval = read_one_list(root, flistp, BOOT_FILE_LIST); if (rval != BAM_SUCCESS) return (rval); (void) read_one_list(root, flistp, ETC_FILE_LIST); } if (flistp->head == NULL) { bam_error(_("archive filelist is empty\n")); return (BAM_ERROR); } return (BAM_SUCCESS); } static void getoldstat(char *root) { char path[PATH_MAX]; int fd, error; struct stat sb; char *ostat; (void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT); fd = open(path, O_RDONLY); if (fd == -1) { if (bam_verbose) bam_print(_("failed to open file: %s: %s\n"), path, strerror(errno)); goto out_err; } if (fstat(fd, &sb) != 0) { bam_error(_("stat of file failed: %s: %s\n"), path, strerror(errno)); goto out_err; } ostat = s_calloc(1, sb.st_size); if (read(fd, ostat, sb.st_size) != sb.st_size) { bam_error(_("read failed for file: %s: %s\n"), path, strerror(errno)); free(ostat); goto out_err; } (void) close(fd); fd = -1; walk_arg.old_nvlp = NULL; error = nvlist_unpack(ostat, sb.st_size, &walk_arg.old_nvlp, 0); free(ostat); if (error) { bam_error(_("failed to unpack stat data: %s: %s\n"), path, strerror(error)); walk_arg.old_nvlp = NULL; goto out_err; } else { return; } out_err: if (fd != -1) (void) close(fd); set_dir_flag(NEED_UPDATE); } /* Best effort stale entry removal */ static void delete_stale(char *file) { char path[PATH_MAX]; struct stat sb; (void) snprintf(path, sizeof (path), "%s/%s", get_cachedir(), file); if (!bam_check && stat(path, &sb) == 0) { if (sb.st_mode & S_IFDIR) (void) rmdir_r(path); else (void) unlink(path); set_dir_flag(NEED_UPDATE | NO_EXTEND); } } /* * Checks if a file in the current (old) archive has * been deleted from the root filesystem. This is needed for * software like Trusted Extensions (TX) that switch early * in boot based on presence/absence of a kernel module. */ static void check4stale(char *root) { nvpair_t *nvp; nvlist_t *nvlp; char *file; char path[PATH_MAX]; /* * Skip stale file check during smf check */ if (bam_smf_check) return; /* * If we need to (re)create the cache, there's no need to check for * stale files */ if (is_flag_on(NEED_CACHE_DIR)) return; /* Nothing to do if no old stats */ if ((nvlp = walk_arg.old_nvlp) == NULL) return; for (nvp = nvlist_next_nvpair(nvlp, NULL); nvp; nvp = nvlist_next_nvpair(nvlp, nvp)) { file = nvpair_name(nvp); if (file == NULL) continue; (void) snprintf(path, sizeof (path), "%s/%s", root, file); if (access(path, F_OK) < 0) { if (bam_verbose) bam_print(_(" stale %s\n"), path); if (is_flag_on(IS_SPARC_TARGET)) { set_dir_flag(NEED_UPDATE); } else { if (has_cachedir()) delete_stale(file); } } } } static void create_newstat(void) { int error; error = nvlist_alloc(&walk_arg.new_nvlp, NV_UNIQUE_NAME, 0); if (error) { /* * Not fatal - we can still create archive */ walk_arg.new_nvlp = NULL; bam_error(_("failed to create stat data: %s\n"), strerror(error)); } } static int walk_list(char *root, filelist_t *flistp) { char path[PATH_MAX]; line_t *lp; for (lp = flistp->head; lp; lp = lp->next) { /* * Don't follow symlinks. A symlink must refer to * a file that would appear in the archive through * a direct reference. This matches the archive * construction behavior. */ (void) snprintf(path, sizeof (path), "%s%s", root, lp->line); if (nftw(path, cmpstat, 20, FTW_PHYS) == -1) { if (is_flag_on(UPDATE_ERROR)) return (BAM_ERROR); /* * Some files may not exist. * For example: etc/rtc_config on a x86 diskless system * Emit verbose message only */ if (bam_verbose) bam_print(_("cannot find: %s: %s\n"), path, strerror(errno)); } } return (BAM_SUCCESS); } /* * Update the timestamp file. */ static void update_timestamp(char *root) { char timestamp_path[PATH_MAX]; /* this path length has already been checked in check_flags_and_files */ (void) snprintf(timestamp_path, sizeof (timestamp_path), "%s%s", root, FILE_STAT_TIMESTAMP); /* * recreate the timestamp file. Since an outdated or absent timestamp * file translates in a complete rebuild of the archive cache, notify * the user of the performance issue. */ if (creat(timestamp_path, FILE_STAT_MODE) < 0) { bam_error(_("failed to open file: %s: %s\n"), timestamp_path, strerror(errno)); bam_error(_("failed to update the timestamp file, next" " archive update may experience reduced performance\n")); } } static void savenew(char *root) { char path[PATH_MAX]; char path2[PATH_MAX]; size_t sz; char *nstat; int fd, wrote, error; nstat = NULL; sz = 0; error = nvlist_pack(walk_arg.new_nvlp, &nstat, &sz, NV_ENCODE_XDR, 0); if (error) { bam_error(_("failed to pack stat data: %s\n"), strerror(error)); return; } (void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT_TMP); fd = open(path, O_RDWR|O_CREAT|O_TRUNC, FILE_STAT_MODE); if (fd == -1) { bam_error(_("failed to open file: %s: %s\n"), path, strerror(errno)); free(nstat); return; } wrote = write(fd, nstat, sz); if (wrote != sz) { bam_error(_("write to file failed: %s: %s\n"), path, strerror(errno)); (void) close(fd); free(nstat); return; } (void) close(fd); free(nstat); (void) snprintf(path2, sizeof (path2), "%s%s", root, FILE_STAT); if (rename(path, path2) != 0) { bam_error(_("rename to file failed: %s: %s\n"), path2, strerror(errno)); } } #define init_walk_args() bzero(&walk_arg, sizeof (walk_arg)) static void clear_walk_args(void) { nvlist_free(walk_arg.old_nvlp); nvlist_free(walk_arg.new_nvlp); if (walk_arg.sparcfile) (void) fclose(walk_arg.sparcfile); walk_arg.old_nvlp = NULL; walk_arg.new_nvlp = NULL; walk_arg.sparcfile = NULL; } /* * Returns: * 0 - no update necessary * 1 - update required. * BAM_ERROR (-1) - An error occurred * * Special handling for check (-n): * ================================ * The check (-n) option produces parseable output. * To do this, we suppress all stdout messages unrelated * to out of sync files. * All stderr messages are still printed though. * */ static int update_required(char *root) { struct stat sb; char path[PATH_MAX]; filelist_t flist; filelist_t *flistp = &flist; int ret; flistp->head = flistp->tail = NULL; if (is_sparc()) set_flag(IS_SPARC_TARGET); /* * Check if cache directories and archives are present */ ret = check_flags_and_files(root); if (ret < 0) return (BAM_ERROR); /* * In certain deployment scenarios, filestat may not * exist. Do not stop the boot process, but trigger an update * of the archives (which will recreate filestat.ramdisk). */ if (bam_smf_check) { (void) snprintf(path, sizeof (path), "%s%s", root, FILE_STAT); if (stat(path, &sb) != 0) { (void) creat(NEED_UPDATE_FILE, 0644); return (0); } } getoldstat(root); /* * Check if the archive contains files that are no longer * present on the root filesystem. */ check4stale(root); /* * read list of files */ if (read_list(root, flistp) != BAM_SUCCESS) { clear_walk_args(); return (BAM_ERROR); } assert(flistp->head && flistp->tail); /* * At this point either the update is required * or the decision is pending. In either case * we need to create new stat nvlist */ create_newstat(); /* * This walk does 2 things: * - gets new stat data for every file * - (optional) compare old and new stat data */ ret = walk_list(root, &flist); /* done with the file list */ filelist_free(flistp); /* something went wrong */ if (ret == BAM_ERROR) { bam_error(_("Failed to gather cache files, archives " "generation aborted\n")); return (BAM_ERROR); } if (walk_arg.new_nvlp == NULL) { if (walk_arg.sparcfile != NULL) (void) fclose(walk_arg.sparcfile); bam_error(_("cannot create new stat data\n")); } /* If nothing was updated, discard newstat. */ if (!is_dir_flag_on(NEED_UPDATE)) { clear_walk_args(); return (0); } if (walk_arg.sparcfile != NULL) (void) fclose(walk_arg.sparcfile); return (1); } static int flushfs(char *root) { char cmd[PATH_MAX + 30]; (void) snprintf(cmd, sizeof (cmd), "%s -f \"%s\" 2>/dev/null", LOCKFS_PATH, root); return (exec_cmd(cmd, NULL)); } static int do_archive_copy(char *source, char *dest) { sync(); /* the equivalent of mv archive-new-$pid boot_archive */ if (rename(source, dest) != 0) { (void) unlink(source); return (BAM_ERROR); } if (flushfs(bam_root) != 0) sync(); return (BAM_SUCCESS); } static int check_cmdline(filelist_t flist) { line_t *lp; for (lp = flist.head; lp; lp = lp->next) { if (strstr(lp->line, "Error:") != NULL || strstr(lp->line, "Inode number overflow") != NULL) { (void) fprintf(stderr, "%s\n", lp->line); return (BAM_ERROR); } } return (BAM_SUCCESS); } static void dump_errormsg(filelist_t flist) { line_t *lp; for (lp = flist.head; lp; lp = lp->next) (void) fprintf(stderr, "%s\n", lp->line); } static int check_archive(char *dest) { struct stat sb; if (stat(dest, &sb) != 0 || !S_ISREG(sb.st_mode) || sb.st_size < 10000) { bam_error(_("archive file %s not generated correctly\n"), dest); (void) unlink(dest); return (BAM_ERROR); } return (BAM_SUCCESS); } static boolean_t is_be(char *root) { zfs_handle_t *zhp; libzfs_handle_t *hdl; be_node_list_t *be_nodes = NULL; be_node_list_t *cur_be; boolean_t be_exist = B_FALSE; char ds_path[ZFS_MAX_DATASET_NAME_LEN]; if (!is_zfs(root)) return (B_FALSE); /* * Get dataset for mountpoint */ if ((hdl = libzfs_init()) == NULL) return (B_FALSE); if ((zhp = zfs_path_to_zhandle(hdl, root, ZFS_TYPE_FILESYSTEM)) == NULL) { libzfs_fini(hdl); return (B_FALSE); } (void) strlcpy(ds_path, zfs_get_name(zhp), sizeof (ds_path)); /* * Check if the current dataset is BE */ if (be_list(NULL, &be_nodes, BE_LIST_DEFAULT) == BE_SUCCESS) { for (cur_be = be_nodes; cur_be != NULL; cur_be = cur_be->be_next_node) { /* * Because we guarantee that cur_be->be_root_ds * is null-terminated by internal data structure, * we can safely use strcmp() */ if (strcmp(ds_path, cur_be->be_root_ds) == 0) { be_exist = B_TRUE; break; } } be_free_list(be_nodes); } zfs_close(zhp); libzfs_fini(hdl); return (be_exist); } /* * Returns B_TRUE if mkiso is in the expected PATH and should be used, * B_FALSE otherwise */ static boolean_t use_mkisofs() { scf_simple_prop_t *prop; char *format = NULL; boolean_t ret; /* Check whether the mkisofs binary is in the expected location */ if (access(MKISOFS_PATH, X_OK) != 0) { if (bam_verbose) bam_print("mkisofs not found\n"); return (B_FALSE); } if (bam_format == BAM_FORMAT_HSFS) { if (bam_verbose) bam_print("-F specified HSFS"); return (B_TRUE); } /* If working on an alt-root, do not use HSFS unless asked via -F */ if (bam_alt_root) return (B_FALSE); /* * Then check that the system/boot-archive config/format property * is "hsfs" or empty. */ if ((prop = scf_simple_prop_get(NULL, BOOT_ARCHIVE_FMRI, SCF_PG_CONFIG, SCF_PROPERTY_FORMAT)) == NULL) { /* Could not find property, use mkisofs */ if (bam_verbose) { bam_print( "%s does not have %s/%s property, using mkisofs\n", BOOT_ARCHIVE_FMRI, SCF_PG_CONFIG, SCF_PROPERTY_FORMAT); } return (B_TRUE); } if (scf_simple_prop_numvalues(prop) < 0 || (format = scf_simple_prop_next_astring(prop)) == NULL) ret = B_TRUE; else ret = strcmp(format, "hsfs") == 0 ? B_TRUE : B_FALSE; if (bam_verbose) { if (ret) bam_print("Creating hsfs boot archive\n"); else bam_print("Creating %s boot archive\n", format); } scf_simple_prop_free(prop); return (ret); } #define MKISO_PARAMS " -quiet -graft-points -dlrDJN -relaxed-filenames " static int create_sparc_archive(char *archive, char *tempname, char *bootblk, char *list) { int ret; char cmdline[3 * PATH_MAX + 64]; filelist_t flist = {0}; const char *func = "create_sparc_archive()"; if (access(bootblk, R_OK) == 1) { bam_error(_("unable to access bootblk file : %s\n"), bootblk); return (BAM_ERROR); } /* * Prepare mkisofs command line and execute it */ (void) snprintf(cmdline, sizeof (cmdline), "%s %s -G %s -o \"%s\" " "-path-list \"%s\" 2>&1", MKISOFS_PATH, MKISO_PARAMS, bootblk, tempname, list); BAM_DPRINTF(("%s: executing: %s\n", func, cmdline)); ret = exec_cmd(cmdline, &flist); if (ret != 0 || check_cmdline(flist) == BAM_ERROR) { dump_errormsg(flist); goto out_err; } filelist_free(&flist); /* * Prepare dd command line to copy the bootblk on the new archive and * execute it */ (void) snprintf(cmdline, sizeof (cmdline), "%s if=\"%s\" of=\"%s\"" " bs=1b oseek=1 count=15 conv=notrunc conv=sync 2>&1", DD_PATH_USR, bootblk, tempname); BAM_DPRINTF(("%s: executing: %s\n", func, cmdline)); ret = exec_cmd(cmdline, &flist); if (ret != 0 || check_cmdline(flist) == BAM_ERROR) goto out_err; filelist_free(&flist); /* Did we get a valid archive ? */ if (check_archive(tempname) == BAM_ERROR) return (BAM_ERROR); return (do_archive_copy(tempname, archive)); out_err: filelist_free(&flist); bam_error(_("boot-archive creation FAILED, command: '%s'\n"), cmdline); (void) unlink(tempname); return (BAM_ERROR); } static unsigned int from_733(unsigned char *s) { int i; unsigned int ret = 0; for (i = 0; i < 4; i++) ret |= s[i] << (8 * i); return (ret); } static void to_733(unsigned char *s, unsigned int val) { int i; for (i = 0; i < 4; i++) s[i] = s[7-i] = (val >> (8 * i)) & 0xFF; } /* * creates sha1 hash of archive */ static int digest_archive(const char *archive) { char *archive_hash; char *hash; int ret; FILE *fp; (void) asprintf(&archive_hash, "%s.hash", archive); if (archive_hash == NULL) return (BAM_ERROR); if ((ret = bootadm_digest(archive, &hash)) == BAM_ERROR) { free(archive_hash); return (ret); } fp = fopen(archive_hash, "w"); if (fp == NULL) { free(archive_hash); free(hash); return (BAM_ERROR); } (void) fprintf(fp, "%s\n", hash); (void) fclose(fp); free(hash); free(archive_hash); return (BAM_SUCCESS); } /* * Extends the current boot archive without recreating it from scratch */ static int extend_iso_archive(char *archive, char *tempname, char *update_dir) { int fd = -1, newfd = -1, ret, i; int next_session = 0, new_size = 0; char cmdline[3 * PATH_MAX + 64]; const char *func = "extend_iso_archive()"; filelist_t flist = {0}; struct iso_pdesc saved_desc[MAX_IVDs]; fd = open(archive, O_RDWR); if (fd == -1) { if (bam_verbose) bam_error(_("failed to open file: %s: %s\n"), archive, strerror(errno)); goto out_err; } /* * A partial read is likely due to a corrupted file */ ret = pread64(fd, saved_desc, sizeof (saved_desc), VOLDESC_OFF * CD_BLOCK); if (ret != sizeof (saved_desc)) { if (bam_verbose) bam_error(_("read failed for file: %s: %s\n"), archive, strerror(errno)); goto out_err; } if (memcmp(saved_desc[0].type, "\1CD001", 6)) { if (bam_verbose) bam_error(_("iso descriptor signature for %s is " "invalid\n"), archive); goto out_err; } /* * Read primary descriptor and locate next_session offset (it should * point to the end of the archive) */ next_session = P2ROUNDUP(from_733(saved_desc[0].volume_space_size), 16); (void) snprintf(cmdline, sizeof (cmdline), "%s -C 16,%d -M %s %s -o \"" "%s\" \"%s\" 2>&1", MKISOFS_PATH, next_session, archive, MKISO_PARAMS, tempname, update_dir); BAM_DPRINTF(("%s: executing: %s\n", func, cmdline)); ret = exec_cmd(cmdline, &flist); if (ret != 0 || check_cmdline(flist) == BAM_ERROR) { if (bam_verbose) { bam_error(_("Command '%s' failed while generating " "multisession archive\n"), cmdline); dump_errormsg(flist); } goto out_flist_err; } filelist_free(&flist); newfd = open(tempname, O_RDONLY); if (newfd == -1) { if (bam_verbose) bam_error(_("failed to open file: %s: %s\n"), archive, strerror(errno)); goto out_err; } ret = pread64(newfd, saved_desc, sizeof (saved_desc), VOLDESC_OFF * CD_BLOCK); if (ret != sizeof (saved_desc)) { if (bam_verbose) bam_error(_("read failed for file: %s: %s\n"), archive, strerror(errno)); goto out_err; } if (memcmp(saved_desc[0].type, "\1CD001", 6)) { if (bam_verbose) bam_error(_("iso descriptor signature for %s is " "invalid\n"), archive); goto out_err; } new_size = from_733(saved_desc[0].volume_space_size) + next_session; to_733(saved_desc[0].volume_space_size, new_size); for (i = 1; i < MAX_IVDs; i++) { if (saved_desc[i].type[0] == (unsigned char)255) break; if (memcmp(saved_desc[i].id, "CD001", 5)) break; if (bam_verbose) bam_print("%s: Updating descriptor entry [%d]\n", func, i); to_733(saved_desc[i].volume_space_size, new_size); } ret = pwrite64(fd, saved_desc, DVD_BLOCK, VOLDESC_OFF*CD_BLOCK); if (ret != DVD_BLOCK) { if (bam_verbose) bam_error(_("write to file failed: %s: %s\n"), archive, strerror(errno)); goto out_err; } (void) close(newfd); newfd = -1; ret = fsync(fd); if (ret != 0) sync(); ret = close(fd); if (ret != 0) { if (bam_verbose) bam_error(_("failed to close file: %s: %s\n"), archive, strerror(errno)); return (BAM_ERROR); } fd = -1; (void) snprintf(cmdline, sizeof (cmdline), "%s if=%s of=%s bs=32k " "seek=%d conv=sync 2>&1", DD_PATH_USR, tempname, archive, (next_session/16)); BAM_DPRINTF(("%s: executing: %s\n", func, cmdline)); ret = exec_cmd(cmdline, &flist); if (ret != 0 || check_cmdline(flist) == BAM_ERROR) { if (bam_verbose) bam_error(_("Command '%s' failed while generating " "multisession archive\n"), cmdline); goto out_flist_err; } filelist_free(&flist); (void) unlink(tempname); if (digest_archive(archive) == BAM_ERROR && bam_verbose) bam_print("boot archive hashing failed\n"); if (flushfs(bam_root) != 0) sync(); if (bam_verbose) bam_print("boot archive updated successfully\n"); return (BAM_SUCCESS); out_flist_err: filelist_free(&flist); out_err: if (fd != -1) (void) close(fd); if (newfd != -1) (void) close(newfd); return (BAM_ERROR); } static int create_x86_archive(char *archive, char *tempname, char *update_dir) { int ret; char cmdline[3 * PATH_MAX + 64]; filelist_t flist = {0}; const char *func = "create_x86_archive()"; (void) snprintf(cmdline, sizeof (cmdline), "%s %s -o \"%s\" \"%s\" " "2>&1", MKISOFS_PATH, MKISO_PARAMS, tempname, update_dir); BAM_DPRINTF(("%s: executing: %s\n", func, cmdline)); ret = exec_cmd(cmdline, &flist); if (ret != 0 || check_cmdline(flist) == BAM_ERROR) { bam_error(_("boot-archive creation FAILED, command: '%s'\n"), cmdline); dump_errormsg(flist); filelist_free(&flist); (void) unlink(tempname); return (BAM_ERROR); } filelist_free(&flist); if (check_archive(tempname) == BAM_ERROR) return (BAM_ERROR); return (do_archive_copy(tempname, archive)); } static int mkisofs_archive(char *root) { int ret; char suffix[20]; char temp[PATH_MAX]; char bootblk[PATH_MAX]; char boot_archive[PATH_MAX]; ret = snprintf(suffix, sizeof (suffix), "archive-new-%d", getpid()); if (ret >= sizeof (suffix)) goto out_path_err; ret = build_path(temp, sizeof (temp), root, ARCHIVE_PREFIX, suffix); if (ret >= sizeof (temp)) goto out_path_err; ret = build_path(boot_archive, sizeof (boot_archive), root, ARCHIVE_PREFIX, ARCHIVE_SUFFIX); if (ret >= sizeof (boot_archive)) goto out_path_err; bam_print("updating %s (HSFS)\n", boot_archive[1] == '/' ? boot_archive + 1 : boot_archive); if (is_flag_on(IS_SPARC_TARGET)) { ret = snprintf(bootblk, sizeof (bootblk), "%s/platform/%s/lib/fs/hsfs/bootblk", root, get_machine()); if (ret >= sizeof (bootblk)) goto out_path_err; ret = create_sparc_archive(boot_archive, temp, bootblk, get_cachedir()); } else { if (!is_dir_flag_on(NO_EXTEND)) { if (bam_verbose) bam_print("Attempting to extend x86 archive: " "%s\n", boot_archive); ret = extend_iso_archive(boot_archive, temp, get_updatedir()); if (ret == BAM_SUCCESS) { if (bam_verbose) bam_print("Successfully extended %s\n", boot_archive); (void) rmdir_r(get_updatedir()); return (BAM_SUCCESS); } } /* * The boot archive will be recreated from scratch. We get here * if at least one of these conditions is true: * - bootadm was called without the -e switch * - the archive (or the archive cache) doesn't exist * - archive size is bigger than BA_SIZE_MAX * - more than COUNT_MAX files need to be updated * - an error occourred either populating the /updates directory * or extend_iso_archive() failed */ if (bam_verbose) bam_print("Unable to extend %s... rebuilding archive\n", boot_archive); if (get_updatedir()[0] != '\0') (void) rmdir_r(get_updatedir()); ret = create_x86_archive(boot_archive, temp, get_cachedir()); } if (digest_archive(boot_archive) == BAM_ERROR && bam_verbose) bam_print("boot archive hashing failed\n"); if (ret == BAM_SUCCESS && bam_verbose) bam_print("Successfully created %s\n", boot_archive); return (ret); out_path_err: bam_error(_("unable to create path on mountpoint %s, path too long\n"), root); return (BAM_ERROR); } static int assemble_systemfile(char *infilename, char *outfilename) { char buf[BUFSIZ]; FILE *infile, *outfile; size_t n; if ((infile = fopen(infilename, "r")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), infilename, strerror(errno)); return (BAM_ERROR); } if ((outfile = fopen(outfilename, "a")) == NULL) { bam_error(_("failed to open file: %s: %s\n"), outfilename, strerror(errno)); (void) fclose(infile); return (BAM_ERROR); } while ((n = fread(buf, 1, sizeof (buf), infile)) > 0) { if (fwrite(buf, 1, n, outfile) != n) { bam_error(_("failed to write file: %s: %s\n"), outfilename, strerror(errno)); (void) fclose(infile); (void) fclose(outfile); return (BAM_ERROR); } } (void) fclose(infile); (void) fclose(outfile); return (BAM_SUCCESS); } /* * Concatenate all files (except those starting with a dot) * from /etc/system.d directory into a single /etc/system.d/.self-assembly * file. The kernel reads it before /etc/system file. */ static error_t build_etc_system_dir(char *root) { struct dirent **filelist; char path[PATH_MAX], tmpfile[PATH_MAX]; int i, files, sysfiles = 0; int ret = BAM_SUCCESS; struct stat st; timespec_t times[2]; (void) snprintf(path, sizeof (path), "%s/%s", root, ETC_SYSTEM_DIR); (void) snprintf(self_assembly, sizeof (self_assembly), "%s%s", root, SELF_ASSEMBLY); (void) snprintf(tmpfile, sizeof (tmpfile), "%s.%ld", self_assembly, (long)getpid()); if (stat(self_assembly, &st) >= 0 && (st.st_mode & S_IFMT) == S_IFREG) { times[0] = times[1] = st.st_mtim; } else { times[1].tv_nsec = 0; } if ((files = scandir(path, &filelist, NULL, alphasort)) < 0) { /* Don't fail the update if /etc/system.d doesn't exist */ if (errno == ENOENT) return (BAM_SUCCESS); bam_error(_("can't read %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } (void) unlink(tmpfile); for (i = 0; i < files; i++) { char filepath[PATH_MAX]; char *fname; fname = filelist[i]->d_name; /* skip anything that starts with a dot */ if (strncmp(fname, ".", 1) == 0) { free(filelist[i]); continue; } if (bam_verbose) bam_print(_("/etc/system.d adding %s/%s\n"), path, fname); (void) snprintf(filepath, sizeof (filepath), "%s/%s", path, fname); if ((assemble_systemfile(filepath, tmpfile)) < 0) { bam_error(_("failed to append file: %s: %s\n"), filepath, strerror(errno)); ret = BAM_ERROR; break; } sysfiles++; } if (sysfiles > 0) { if (rename(tmpfile, self_assembly) < 0) { bam_error(_("failed to rename file: %s: %s\n"), tmpfile, strerror(errno)); return (BAM_ERROR); } /* * Use previous attribute times to avoid * boot archive recreation. */ if (times[1].tv_nsec != 0 && utimensat(AT_FDCWD, self_assembly, times, 0) != 0) { bam_error(_("failed to change times: %s\n"), strerror(errno)); return (BAM_ERROR); } } else { (void) unlink(tmpfile); (void) unlink(self_assembly); } return (ret); } static error_t create_ramdisk(char *root) { char *cmdline, path[PATH_MAX]; size_t len; struct stat sb; int ret, status = BAM_SUCCESS; /* If mkisofs should be used, use it to create the required archives */ if (use_mkisofs()) { if (has_cachedir() && is_dir_flag_on(NEED_UPDATE)) { ret = mkisofs_archive(root); if (ret != 0) status = BAM_ERROR; } return (status); } else if (bam_format == BAM_FORMAT_HSFS) { bam_error(_("cannot create hsfs archive\n")); return (BAM_ERROR); } /* * Else setup command args for create_ramdisk.ksh for the archive * Note: we will not create hash here, CREATE_RAMDISK should create it. */ (void) snprintf(path, sizeof (path), "%s/%s", root, CREATE_RAMDISK); if (stat(path, &sb) != 0) { bam_error(_("archive creation file not found: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } if (is_safe_exec(path) == BAM_ERROR) return (BAM_ERROR); len = strlen(path) + strlen(root) + 10; /* room for space + -R */ if (bam_alt_platform) len += strlen(bam_platform) + strlen(" -p "); if (bam_format != BAM_FORMAT_UNSET) len += strlen(bam_formats[bam_format]) + strlen(" -f "); cmdline = s_calloc(1, len); if (bam_alt_platform) { assert(strlen(root) > 1); (void) snprintf(cmdline, len, "%s -p %s -R %s", path, bam_platform, root); /* chop off / at the end */ cmdline[strlen(cmdline) - 1] = '\0'; } else if (strlen(root) > 1) { (void) snprintf(cmdline, len, "%s -R %s", path, root); /* chop off / at the end */ cmdline[strlen(cmdline) - 1] = '\0'; } else (void) snprintf(cmdline, len, "%s", path); if (bam_format != BAM_FORMAT_UNSET) { if (strlcat(cmdline, " -f ", len) >= len || strlcat(cmdline, bam_formats[bam_format], len) >= len) { bam_error(_("boot-archive command line too long\n")); free(cmdline); return (BAM_ERROR); } } if (exec_cmd(cmdline, NULL) != 0) { bam_error(_("boot-archive creation FAILED, command: '%s'\n"), cmdline); free(cmdline); return (BAM_ERROR); } free(cmdline); /* * The existence of the expected archives used to be * verified here. This check is done in create_ramdisk as * it needs to be in sync with the altroot operated upon. */ return (BAM_SUCCESS); } /* * Checks if target filesystem is on a ramdisk * 1 - is miniroot * 0 - is not * When in doubt assume it is not a ramdisk. */ static int is_ramdisk(char *root) { struct extmnttab mnt; FILE *fp; int found; char mntpt[PATH_MAX]; char *cp; /* * There are 3 situations where creating archive is * of dubious value: * - create boot_archive on a lofi-mounted boot_archive * - create it on a ramdisk which is the root filesystem * - create it on a ramdisk mounted somewhere else * The first is not easy to detect and checking for it is not * worth it. * The other two conditions are handled here */ fp = fopen(MNTTAB, "r"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(errno)); return (0); } resetmnttab(fp); /* * Remove any trailing / from the mount point */ (void) strlcpy(mntpt, root, sizeof (mntpt)); if (strcmp(root, "/") != 0) { cp = mntpt + strlen(mntpt) - 1; if (*cp == '/') *cp = '\0'; } found = 0; while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) { if (strcmp(mnt.mnt_mountp, mntpt) == 0) { found = 1; break; } } if (!found) { if (bam_verbose) bam_error(_("alternate root %s not in mnttab\n"), mntpt); (void) fclose(fp); return (0); } if (strncmp(mnt.mnt_special, RAMDISK_SPECIAL, strlen(RAMDISK_SPECIAL)) == 0) { if (bam_verbose) bam_error(_("%s is on a ramdisk device\n"), bam_root); (void) fclose(fp); return (1); } (void) fclose(fp); return (0); } static int is_boot_archive(char *root) { char path[PATH_MAX]; struct stat sb; int error; const char *fcn = "is_boot_archive()"; /* * We can't create an archive without the create_ramdisk script */ (void) snprintf(path, sizeof (path), "%s/%s", root, CREATE_RAMDISK); error = stat(path, &sb); INJECT_ERROR1("NOT_ARCHIVE_BASED", error = -1); if (error == -1) { if (bam_verbose) bam_print(_("file not found: %s\n"), path); BAM_DPRINTF(("%s: not a boot archive based Solaris " "instance: %s\n", fcn, root)); return (0); } BAM_DPRINTF(("%s: *IS* a boot archive based Solaris instance: %s\n", fcn, root)); return (1); } /* * Need to call this for anything that operates on the GRUB menu * In the x86 live upgrade case the directory /boot/grub may be present * even on pre-newboot BEs. The authoritative way to check for a GRUB target * is to check for the presence of the stage2 binary which is present * only on GRUB targets (even on x86 boot partitions). Checking for the * presence of the multiboot binary is not correct as it is not present * on x86 boot partitions. */ int is_grub(const char *root) { char path[PATH_MAX]; struct stat sb; void *defp; boolean_t grub = B_FALSE; const char *res = NULL; const char *fcn = "is_grub()"; /* grub is disabled by default */ if ((defp = defopen_r(BE_DEFAULTS)) == NULL) { return (0); } else { res = defread_r(BE_DFLT_BE_HAS_GRUB, defp); if (res != NULL && res[0] != '\0') { if (strcasecmp(res, "true") == 0) grub = B_TRUE; } defclose_r(defp); } if (grub == B_TRUE) { (void) snprintf(path, sizeof (path), "%s%s", root, GRUB_STAGE2); if (stat(path, &sb) == -1) { BAM_DPRINTF(("%s: Missing GRUB directory: %s\n", fcn, path)); return (0); } else return (1); } return (0); } int is_zfs(char *root) { struct statvfs vfs; int ret; const char *fcn = "is_zfs()"; ret = statvfs(root, &vfs); INJECT_ERROR1("STATVFS_ZFS", ret = 1); if (ret != 0) { bam_error(_("statvfs failed for %s: %s\n"), root, strerror(errno)); return (0); } if (strncmp(vfs.f_basetype, "zfs", strlen("zfs")) == 0) { BAM_DPRINTF(("%s: is a ZFS filesystem: %s\n", fcn, root)); return (1); } else { BAM_DPRINTF(("%s: is *NOT* a ZFS filesystem: %s\n", fcn, root)); return (0); } } int is_pcfs(char *root) { struct statvfs vfs; int ret; const char *fcn = "is_pcfs()"; ret = statvfs(root, &vfs); INJECT_ERROR1("STATVFS_PCFS", ret = 1); if (ret != 0) { bam_error(_("statvfs failed for %s: %s\n"), root, strerror(errno)); return (0); } if (strncmp(vfs.f_basetype, "pcfs", strlen("pcfs")) == 0) { BAM_DPRINTF(("%s: is a PCFS filesystem: %s\n", fcn, root)); return (1); } else { BAM_DPRINTF(("%s: is *NOT* a PCFS filesystem: %s\n", fcn, root)); return (0); } } static int is_readonly(char *root) { int fd; int error; char testfile[PATH_MAX]; const char *fcn = "is_readonly()"; /* * Using statvfs() to check for a read-only filesystem is not * reliable. The only way to reliably test is to attempt to * create a file */ (void) snprintf(testfile, sizeof (testfile), "%s/%s.%d", root, BOOTADM_RDONLY_TEST, getpid()); (void) unlink(testfile); errno = 0; fd = open(testfile, O_RDWR|O_CREAT|O_EXCL, 0644); error = errno; INJECT_ERROR2("RDONLY_TEST_ERROR", fd = -1, error = EACCES); if (fd == -1 && error == EROFS) { BAM_DPRINTF(("%s: is a READONLY filesystem: %s\n", fcn, root)); return (1); } else if (fd == -1) { bam_error(_("error during read-only test on %s: %s\n"), root, strerror(error)); } (void) close(fd); (void) unlink(testfile); BAM_DPRINTF(("%s: is a RDWR filesystem: %s\n", fcn, root)); return (0); } static error_t update_archive(char *root, char *opt) { error_t ret; assert(root); assert(opt == NULL); init_walk_args(); (void) umask(022); /* * Never update non-BE root in update_all */ if (bam_update_all && !is_be(root)) return (BAM_SUCCESS); /* * root must belong to a boot archive based OS, */ if (!is_boot_archive(root)) { /* * Emit message only if not in context of update_all. * If in update_all, emit only if verbose flag is set. */ if (!bam_update_all || bam_verbose) bam_print(_("%s: not a boot archive based Solaris " "instance\n"), root); return (BAM_ERROR); } /* * If smf check is requested when / is writable (can happen * on first reboot following an upgrade because service * dependency is messed up), skip the check. */ if (bam_smf_check && !bam_root_readonly && !is_zfs(root)) return (BAM_SUCCESS); /* * Don't generate archive on ramdisk. */ if (is_ramdisk(root)) return (BAM_SUCCESS); /* * root must be writable. This check applies to alternate * root (-R option); bam_root_readonly applies to '/' only. * The behaviour translates into being the one of a 'check'. */ if (!bam_smf_check && !bam_check && is_readonly(root)) { set_flag(RDONLY_FSCHK); bam_check = 1; } /* * Process the /etc/system.d/.self-assembly file. */ if (build_etc_system_dir(bam_root) == BAM_ERROR) return (BAM_ERROR); /* * Now check if an update is really needed. */ ret = update_required(root); /* * The check command (-n) is *not* a dry run. * It only checks if the archive is in sync. * A readonly filesystem has to be considered an error only if an update * is required. */ if (bam_nowrite()) { if (is_flag_on(RDONLY_FSCHK)) { bam_check = bam_saved_check; if (ret > 0) bam_error(_("%s filesystem is read-only, " "skipping archives update\n"), root); if (bam_update_all) return ((ret != 0) ? BAM_ERROR : BAM_SUCCESS); } bam_exit((ret != 0) ? 1 : 0); } if (ret == 1) { /* create the ramdisk */ ret = create_ramdisk(root); } /* * if the archive is updated, save the new stat data and update the * timestamp file */ if (ret == 0 && walk_arg.new_nvlp != NULL) { savenew(root); update_timestamp(root); } clear_walk_args(); return (ret); } static char * find_root_pool() { char *special = get_special("/"); char *p; if (special == NULL) return (NULL); if (*special == '/') { free(special); return (NULL); } if ((p = strchr(special, '/')) != NULL) *p = '\0'; return (special); } static error_t synchronize_BE_menu(void) { struct stat sb; char cmdline[PATH_MAX]; char cksum_line[PATH_MAX]; filelist_t flist = {0}; char *old_cksum_str; char *old_size_str; char *old_file; char *curr_cksum_str; char *curr_size_str; char *curr_file; char *pool = NULL; char *mntpt = NULL; zfs_mnted_t mnted; FILE *cfp; int found; int ret; const char *fcn = "synchronize_BE_menu()"; BAM_DPRINTF(("%s: entered. No args\n", fcn)); /* Check if findroot enabled LU BE */ if (stat(FINDROOT_INSTALLGRUB, &sb) != 0) { BAM_DPRINTF(("%s: not a Live Upgrade BE\n", fcn)); return (BAM_SUCCESS); } if (stat(LU_MENU_CKSUM, &sb) != 0) { BAM_DPRINTF(("%s: checksum file absent: %s\n", fcn, LU_MENU_CKSUM)); goto menu_sync; } cfp = fopen(LU_MENU_CKSUM, "r"); INJECT_ERROR1("CKSUM_FILE_MISSING", cfp = NULL); if (cfp == NULL) { bam_error(_("failed to read GRUB menu checksum file: %s\n"), LU_MENU_CKSUM); goto menu_sync; } BAM_DPRINTF(("%s: opened checksum file: %s\n", fcn, LU_MENU_CKSUM)); found = 0; while (s_fgets(cksum_line, sizeof (cksum_line), cfp) != NULL) { INJECT_ERROR1("MULTIPLE_CKSUM", found = 1); if (found) { bam_error(_("multiple checksums for GRUB menu in " "checksum file: %s\n"), LU_MENU_CKSUM); (void) fclose(cfp); goto menu_sync; } found = 1; } BAM_DPRINTF(("%s: read checksum file: %s\n", fcn, LU_MENU_CKSUM)); old_cksum_str = strtok(cksum_line, " \t"); old_size_str = strtok(NULL, " \t"); old_file = strtok(NULL, " \t"); INJECT_ERROR1("OLD_CKSUM_NULL", old_cksum_str = NULL); INJECT_ERROR1("OLD_SIZE_NULL", old_size_str = NULL); INJECT_ERROR1("OLD_FILE_NULL", old_file = NULL); if (old_cksum_str == NULL || old_size_str == NULL || old_file == NULL) { bam_error(_("error parsing GRUB menu checksum file: %s\n"), LU_MENU_CKSUM); goto menu_sync; } BAM_DPRINTF(("%s: parsed checksum file: %s\n", fcn, LU_MENU_CKSUM)); /* Get checksum of current menu */ pool = find_root_pool(); if (pool) { mntpt = mount_top_dataset(pool, &mnted); if (mntpt == NULL) { bam_error(_("failed to mount top dataset for %s\n"), pool); free(pool); return (BAM_ERROR); } (void) snprintf(cmdline, sizeof (cmdline), "%s %s%s", CKSUM, mntpt, GRUB_MENU); } else { (void) snprintf(cmdline, sizeof (cmdline), "%s %s", CKSUM, GRUB_MENU); } ret = exec_cmd(cmdline, &flist); if (pool) { (void) umount_top_dataset(pool, mnted, mntpt); free(pool); } INJECT_ERROR1("GET_CURR_CKSUM", ret = 1); if (ret != 0) { bam_error(_("error generating checksum of GRUB menu\n")); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully generated checksum\n", fcn)); INJECT_ERROR1("GET_CURR_CKSUM_OUTPUT", flist.head = NULL); if ((flist.head == NULL) || (flist.head != flist.tail)) { bam_error(_("bad checksum generated for GRUB menu\n")); filelist_free(&flist); return (BAM_ERROR); } BAM_DPRINTF(("%s: generated checksum output valid\n", fcn)); curr_cksum_str = strtok(flist.head->line, " \t"); curr_size_str = strtok(NULL, " \t"); curr_file = strtok(NULL, " \t"); INJECT_ERROR1("CURR_CKSUM_NULL", curr_cksum_str = NULL); INJECT_ERROR1("CURR_SIZE_NULL", curr_size_str = NULL); INJECT_ERROR1("CURR_FILE_NULL", curr_file = NULL); if (curr_cksum_str == NULL || curr_size_str == NULL || curr_file == NULL) { bam_error(_("error parsing checksum generated " "for GRUB menu\n")); filelist_free(&flist); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully parsed generated checksum\n", fcn)); if (strcmp(old_cksum_str, curr_cksum_str) == 0 && strcmp(old_size_str, curr_size_str) == 0 && strcmp(old_file, curr_file) == 0) { filelist_free(&flist); BAM_DPRINTF(("%s: no change in checksum of GRUB menu\n", fcn)); return (BAM_SUCCESS); } filelist_free(&flist); /* cksum doesn't match - the menu has changed */ BAM_DPRINTF(("%s: checksum of GRUB menu has changed\n", fcn)); menu_sync: bam_print(_("propagating updated GRUB menu\n")); (void) snprintf(cmdline, sizeof (cmdline), "/bin/sh -c '. %s > /dev/null; %s %s yes > /dev/null'", LULIB, LULIB_PROPAGATE_FILE, GRUB_MENU); ret = exec_cmd(cmdline, NULL); INJECT_ERROR1("PROPAGATE_MENU", ret = 1); if (ret != 0) { bam_error(_("error propagating updated GRUB menu\n")); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully propagated GRUB menu\n", fcn)); (void) snprintf(cmdline, sizeof (cmdline), "/bin/cp %s %s > /dev/null", GRUB_MENU, GRUB_BACKUP_MENU); ret = exec_cmd(cmdline, NULL); INJECT_ERROR1("CREATE_BACKUP", ret = 1); if (ret != 0) { bam_error(_("failed to create backup for GRUB menu: %s\n"), GRUB_BACKUP_MENU); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully created backup GRUB menu: %s\n", fcn, GRUB_BACKUP_MENU)); (void) snprintf(cmdline, sizeof (cmdline), "/bin/sh -c '. %s > /dev/null; %s %s no > /dev/null'", LULIB, LULIB_PROPAGATE_FILE, GRUB_BACKUP_MENU); ret = exec_cmd(cmdline, NULL); INJECT_ERROR1("PROPAGATE_BACKUP", ret = 1); if (ret != 0) { bam_error(_("error propagating backup GRUB menu: %s\n"), GRUB_BACKUP_MENU); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully propagated backup GRUB menu: %s\n", fcn, GRUB_BACKUP_MENU)); (void) snprintf(cmdline, sizeof (cmdline), "%s %s > %s", CKSUM, GRUB_MENU, LU_MENU_CKSUM); ret = exec_cmd(cmdline, NULL); INJECT_ERROR1("CREATE_CKSUM_FILE", ret = 1); if (ret != 0) { bam_error(_("failed to write GRUB menu checksum file: %s\n"), LU_MENU_CKSUM); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully created checksum file: %s\n", fcn, LU_MENU_CKSUM)); (void) snprintf(cmdline, sizeof (cmdline), "/bin/sh -c '. %s > /dev/null; %s %s no > /dev/null'", LULIB, LULIB_PROPAGATE_FILE, LU_MENU_CKSUM); ret = exec_cmd(cmdline, NULL); INJECT_ERROR1("PROPAGATE_MENU_CKSUM_FILE", ret = 1); if (ret != 0) { bam_error(_("error propagating GRUB menu checksum file: %s\n"), LU_MENU_CKSUM); return (BAM_ERROR); } BAM_DPRINTF(("%s: successfully propagated checksum file: %s\n", fcn, LU_MENU_CKSUM)); return (BAM_SUCCESS); } static error_t update_all(char *root, char *opt) { struct extmnttab mnt; struct stat sb; FILE *fp; char multibt[PATH_MAX]; char creatram[PATH_MAX]; error_t ret = BAM_SUCCESS; assert(root); assert(opt == NULL); if (bam_rootlen != 1 || *root != '/') { elide_trailing_slash(root, multibt, sizeof (multibt)); bam_error(_("an alternate root (%s) cannot be used with this " "sub-command\n"), multibt); return (BAM_ERROR); } /* * First update archive for current root */ if (update_archive(root, opt) != BAM_SUCCESS) ret = BAM_ERROR; if (ret == BAM_ERROR) goto out; /* * Now walk the mount table, performing archive update * for all mounted Newboot root filesystems */ fp = fopen(MNTTAB, "r"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(errno)); ret = BAM_ERROR; goto out; } resetmnttab(fp); while (getextmntent(fp, &mnt, sizeof (mnt)) == 0) { if (mnt.mnt_special == NULL) continue; if ((strcmp(mnt.mnt_fstype, MNTTYPE_ZFS) != 0) && (strncmp(mnt.mnt_special, "/dev/", strlen("/dev/")) != 0)) continue; if (strcmp(mnt.mnt_mountp, "/") == 0) continue; (void) snprintf(creatram, sizeof (creatram), "%s/%s", mnt.mnt_mountp, CREATE_RAMDISK); if (stat(creatram, &sb) == -1) continue; /* * We put a trailing slash to be consistent with root = "/" * case, such that we don't have to print // in some cases. */ (void) snprintf(rootbuf, sizeof (rootbuf), "%s/", mnt.mnt_mountp); bam_rootlen = strlen(rootbuf); /* * It's possible that other mounts may be an alternate boot * architecture, so check it again. */ if ((get_boot_cap(rootbuf) != BAM_SUCCESS) || (update_archive(rootbuf, opt) != BAM_SUCCESS)) ret = BAM_ERROR; } (void) fclose(fp); out: /* * We no longer use biosdev for Live Upgrade. Hence * there is no need to defer (to shutdown time) any fdisk * updates */ if (stat(GRUB_fdisk, &sb) == 0 || stat(GRUB_fdisk_target, &sb) == 0) { bam_error(_("Deferred FDISK update file(s) found: %s, %s. " "Not supported.\n"), GRUB_fdisk, GRUB_fdisk_target); } /* * If user has updated menu in current BE, propagate the * updates to all BEs. */ if (sync_menu && synchronize_BE_menu() != BAM_SUCCESS) ret = BAM_ERROR; return (ret); } static void append_line(menu_t *mp, line_t *lp) { if (mp->start == NULL) { mp->start = lp; } else { mp->end->next = lp; lp->prev = mp->end; } mp->end = lp; } void unlink_line(menu_t *mp, line_t *lp) { /* unlink from list */ if (lp->prev) lp->prev->next = lp->next; else mp->start = lp->next; if (lp->next) lp->next->prev = lp->prev; else mp->end = lp->prev; } static entry_t * boot_entry_new(menu_t *mp, line_t *start, line_t *end) { entry_t *ent, *prev; const char *fcn = "boot_entry_new()"; assert(mp); assert(start); assert(end); ent = s_calloc(1, sizeof (entry_t)); BAM_DPRINTF(("%s: new boot entry alloced\n", fcn)); ent->start = start; ent->end = end; if (mp->entries == NULL) { mp->entries = ent; BAM_DPRINTF(("%s: (first) new boot entry created\n", fcn)); return (ent); } prev = mp->entries; while (prev->next) prev = prev->next; prev->next = ent; ent->prev = prev; BAM_DPRINTF(("%s: new boot entry linked in\n", fcn)); return (ent); } static void boot_entry_addline(entry_t *ent, line_t *lp) { if (ent) ent->end = lp; } /* * Check whether cmd matches the one indexed by which, and whether arg matches * str. which must be either KERNEL_CMD or MODULE_CMD, and a match to the * respective *_DOLLAR_CMD is also acceptable. The arg is searched using * strstr(), so it can be a partial match. */ static int check_cmd(const char *cmd, const int which, const char *arg, const char *str) { int ret; const char *fcn = "check_cmd()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, arg, str)); if (cmd != NULL) { if ((strcmp(cmd, menu_cmds[which]) != 0) && (strcmp(cmd, menu_cmds[which + 1]) != 0)) { BAM_DPRINTF(("%s: command %s does not match %s\n", fcn, cmd, menu_cmds[which])); return (0); } ret = (strstr(arg, str) != NULL); } else ret = 0; if (ret) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (ret); } static error_t kernel_parser(entry_t *entry, char *cmd, char *arg, int linenum) { const char *fcn = "kernel_parser()"; assert(entry); assert(cmd); assert(arg); if (strcmp(cmd, menu_cmds[KERNEL_CMD]) != 0 && strcmp(cmd, menu_cmds[KERNEL_DOLLAR_CMD]) != 0) { BAM_DPRINTF(("%s: not a kernel command: %s\n", fcn, cmd)); return (BAM_ERROR); } if (strncmp(arg, DIRECT_BOOT_32, sizeof (DIRECT_BOOT_32) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT|DBOOT_32 flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_32BIT; } else if (strncmp(arg, DIRECT_BOOT_KERNEL, sizeof (DIRECT_BOOT_KERNEL) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT; } else if (strncmp(arg, DIRECT_BOOT_64, sizeof (DIRECT_BOOT_64) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT|DBOOT_64 flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_64BIT; } else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_KERNEL, sizeof (DIRECT_BOOT_FAILSAFE_KERNEL) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT|DBOOT_FAILSAFE flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE; } else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_32, sizeof (DIRECT_BOOT_FAILSAFE_32) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT|DBOOT_FAILSAFE|DBOOT_32 " "flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE | BAM_ENTRY_32BIT; } else if (strncmp(arg, DIRECT_BOOT_FAILSAFE_64, sizeof (DIRECT_BOOT_FAILSAFE_64) - 1) == 0) { BAM_DPRINTF(("%s: setting DBOOT|DBOOT_FAILSAFE|DBOOT_64 " "flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_FAILSAFE | BAM_ENTRY_64BIT; } else if (strncmp(arg, MULTI_BOOT, sizeof (MULTI_BOOT) - 1) == 0) { BAM_DPRINTF(("%s: setting MULTIBOOT flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_MULTIBOOT; } else if (strncmp(arg, MULTI_BOOT_FAILSAFE, sizeof (MULTI_BOOT_FAILSAFE) - 1) == 0) { BAM_DPRINTF(("%s: setting MULTIBOOT|MULTIBOOT_FAILSAFE " "flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_MULTIBOOT | BAM_ENTRY_FAILSAFE; } else if (strstr(arg, XEN_KERNEL_SUBSTR)) { BAM_DPRINTF(("%s: setting XEN HV flag: %s\n", fcn, arg)); entry->flags |= BAM_ENTRY_HV; } else if (!(entry->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU))) { BAM_DPRINTF(("%s: is HAND kernel flag: %s\n", fcn, arg)); return (BAM_ERROR); } else if (strncmp(arg, KERNEL_PREFIX, strlen(KERNEL_PREFIX)) == 0 && strstr(arg, UNIX_SPACE)) { entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_32BIT; } else if (strncmp(arg, KERNEL_PREFIX, strlen(KERNEL_PREFIX)) == 0 && strstr(arg, AMD_UNIX_SPACE)) { entry->flags |= BAM_ENTRY_DBOOT | BAM_ENTRY_64BIT; } else { BAM_DPRINTF(("%s: is UNKNOWN kernel entry: %s\n", fcn, arg)); bam_error(_("kernel command on line %d not recognized.\n"), linenum); return (BAM_ERROR); } return (BAM_SUCCESS); } static error_t module_parser(entry_t *entry, char *cmd, char *arg, int linenum) { const char *fcn = "module_parser()"; assert(entry); assert(cmd); assert(arg); if (strcmp(cmd, menu_cmds[MODULE_CMD]) != 0 && strcmp(cmd, menu_cmds[MODULE_DOLLAR_CMD]) != 0) { BAM_DPRINTF(("%s: not module cmd: %s\n", fcn, cmd)); return (BAM_ERROR); } if (strcmp(arg, DIRECT_BOOT_ARCHIVE) == 0 || strcmp(arg, DIRECT_BOOT_ARCHIVE_32) == 0 || strcmp(arg, DIRECT_BOOT_ARCHIVE_64) == 0 || strcmp(arg, MULTIBOOT_ARCHIVE) == 0 || strcmp(arg, FAILSAFE_ARCHIVE) == 0 || strcmp(arg, FAILSAFE_ARCHIVE_32) == 0 || strcmp(arg, FAILSAFE_ARCHIVE_64) == 0 || strcmp(arg, XEN_KERNEL_MODULE_LINE) == 0 || strcmp(arg, XEN_KERNEL_MODULE_LINE_ZFS) == 0) { BAM_DPRINTF(("%s: bootadm or LU module cmd: %s\n", fcn, arg)); return (BAM_SUCCESS); } else if (!(entry->flags & BAM_ENTRY_BOOTADM) && !(entry->flags & BAM_ENTRY_LU)) { /* don't emit warning for hand entries */ BAM_DPRINTF(("%s: is HAND module: %s\n", fcn, arg)); return (BAM_ERROR); } else { BAM_DPRINTF(("%s: is UNKNOWN module: %s\n", fcn, arg)); bam_error(_("module command on line %d not recognized.\n"), linenum); return (BAM_ERROR); } } /* * A line in menu.lst looks like * [ ]*[ \t=]** */ static void line_parser(menu_t *mp, char *str, int *lineNum, int *entryNum) { /* * save state across calls. This is so that * header gets the right entry# after title has * been processed */ static line_t *prev = NULL; static entry_t *curr_ent = NULL; static int in_liveupgrade = 0; static int is_libbe_ent = 0; line_t *lp; char *cmd, *sep, *arg; char save, *cp, *line; menu_flag_t flag = BAM_INVALID; const char *fcn = "line_parser()"; cmd = NULL; if (str == NULL) { return; } /* * First save a copy of the entire line. * We use this later to set the line field. */ line = s_strdup(str); /* Eat up leading whitespace */ while (*str == ' ' || *str == '\t') str++; if (*str == '#') { /* comment */ cmd = s_strdup("#"); sep = NULL; arg = s_strdup(str + 1); flag = BAM_COMMENT; if (strstr(arg, BAM_LU_HDR) != NULL) { in_liveupgrade = 1; } else if (strstr(arg, BAM_LU_FTR) != NULL) { in_liveupgrade = 0; } else if (strstr(arg, BAM_LIBBE_FTR) != NULL) { is_libbe_ent = 1; } } else if (*str == '\0') { /* blank line */ cmd = sep = arg = NULL; flag = BAM_EMPTY; } else { /* * '=' is not a documented separator in grub syntax. * However various development bits use '=' as a * separator. In addition, external users also * use = as a separator. So we will allow that usage. */ cp = str; while (*str != ' ' && *str != '\t' && *str != '=') { if (*str == '\0') { cmd = s_strdup(cp); sep = arg = NULL; break; } str++; } if (*str != '\0') { save = *str; *str = '\0'; cmd = s_strdup(cp); *str = save; str++; save = *str; *str = '\0'; sep = s_strdup(str - 1); *str = save; while (*str == ' ' || *str == '\t') str++; if (*str == '\0') arg = NULL; else arg = s_strdup(str); } } lp = s_calloc(1, sizeof (line_t)); lp->cmd = cmd; lp->sep = sep; lp->arg = arg; lp->line = line; lp->lineNum = ++(*lineNum); if (cmd && strcmp(cmd, menu_cmds[TITLE_CMD]) == 0) { lp->entryNum = ++(*entryNum); lp->flags = BAM_TITLE; if (prev && prev->flags == BAM_COMMENT && prev->arg && strcmp(prev->arg, BAM_BOOTADM_HDR) == 0) { prev->entryNum = lp->entryNum; curr_ent = boot_entry_new(mp, prev, lp); curr_ent->flags |= BAM_ENTRY_BOOTADM; BAM_DPRINTF(("%s: is bootadm(8) entry: %s\n", fcn, arg)); } else { curr_ent = boot_entry_new(mp, lp, lp); if (in_liveupgrade) { curr_ent->flags |= BAM_ENTRY_LU; BAM_DPRINTF(("%s: is LU entry: %s\n", fcn, arg)); } } curr_ent->entryNum = *entryNum; } else if (flag != BAM_INVALID) { /* * For header comments, the entry# is "fixed up" * by the subsequent title */ lp->entryNum = *entryNum; lp->flags = flag; } else { lp->entryNum = *entryNum; if (*entryNum == ENTRY_INIT) { lp->flags = BAM_GLOBAL; } else { lp->flags = BAM_ENTRY; if (cmd && arg) { if (strcmp(cmd, menu_cmds[ROOT_CMD]) == 0) { BAM_DPRINTF(("%s: setting ROOT: %s\n", fcn, arg)); curr_ent->flags |= BAM_ENTRY_ROOT; } else if (strcmp(cmd, menu_cmds[FINDROOT_CMD]) == 0) { BAM_DPRINTF(("%s: setting " "FINDROOT: %s\n", fcn, arg)); curr_ent->flags |= BAM_ENTRY_FINDROOT; } else if (strcmp(cmd, menu_cmds[CHAINLOADER_CMD]) == 0) { BAM_DPRINTF(("%s: setting " "CHAINLOADER: %s\n", fcn, arg)); curr_ent->flags |= BAM_ENTRY_CHAINLOADER; } else if (kernel_parser(curr_ent, cmd, arg, lp->lineNum) != BAM_SUCCESS) { (void) module_parser(curr_ent, cmd, arg, lp->lineNum); } } } } /* record default, old default, and entry line ranges */ if (lp->flags == BAM_GLOBAL && lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[DEFAULT_CMD]) == 0) { mp->curdefault = lp; } else if (lp->flags == BAM_COMMENT && strncmp(lp->arg, BAM_OLDDEF, strlen(BAM_OLDDEF)) == 0) { mp->olddefault = lp; } else if (lp->flags == BAM_COMMENT && strncmp(lp->arg, BAM_OLD_RC_DEF, strlen(BAM_OLD_RC_DEF)) == 0) { mp->old_rc_default = lp; } else if (lp->flags == BAM_ENTRY || (lp->flags == BAM_COMMENT && ((strcmp(lp->arg, BAM_BOOTADM_FTR) == 0) || is_libbe_ent))) { if (is_libbe_ent) { curr_ent->flags |= BAM_ENTRY_LIBBE; is_libbe_ent = 0; } boot_entry_addline(curr_ent, lp); } append_line(mp, lp); prev = lp; } void update_numbering(menu_t *mp) { int lineNum; int entryNum; int old_default_value; line_t *lp, *prev, *default_lp, *default_entry; char buf[PATH_MAX]; if (mp->start == NULL) { return; } lineNum = LINE_INIT; entryNum = ENTRY_INIT; old_default_value = ENTRY_INIT; lp = default_lp = default_entry = NULL; prev = NULL; for (lp = mp->start; lp; prev = lp, lp = lp->next) { lp->lineNum = ++lineNum; /* * Get the value of the default command */ if (lp->entryNum == ENTRY_INIT && lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[DEFAULT_CMD]) == 0 && lp->arg) { old_default_value = atoi(lp->arg); default_lp = lp; } /* * If not a booting entry, nothing else to fix for this * entry */ if (lp->entryNum == ENTRY_INIT) continue; /* * Record the position of the default entry. * The following works because global * commands like default and timeout should precede * actual boot entries, so old_default_value * is already known (or default cmd is missing). */ if (default_entry == NULL && old_default_value != ENTRY_INIT && lp->entryNum == old_default_value) { default_entry = lp; } /* * Now fixup the entry number */ if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[TITLE_CMD]) == 0) { lp->entryNum = ++entryNum; /* fixup the bootadm header */ if (prev && prev->flags == BAM_COMMENT && prev->arg && strcmp(prev->arg, BAM_BOOTADM_HDR) == 0) { prev->entryNum = lp->entryNum; } } else { lp->entryNum = entryNum; } } /* * No default command in menu, simply return */ if (default_lp == NULL) { return; } free(default_lp->arg); free(default_lp->line); if (default_entry == NULL) { default_lp->arg = s_strdup("0"); } else { (void) snprintf(buf, sizeof (buf), "%d", default_entry->entryNum); default_lp->arg = s_strdup(buf); } /* * The following is required since only the line field gets * written back to menu.lst */ (void) snprintf(buf, sizeof (buf), "%s%s%s", menu_cmds[DEFAULT_CMD], menu_cmds[SEP_CMD], default_lp->arg); default_lp->line = s_strdup(buf); } static menu_t * menu_read(char *menu_path) { FILE *fp; char buf[BAM_MAXLINE], *cp; menu_t *mp; int line, entry, len, n; mp = s_calloc(1, sizeof (menu_t)); fp = fopen(menu_path, "r"); if (fp == NULL) { /* Let the caller handle this error */ free(mp); return (NULL); } /* Note: GRUB boot entry number starts with 0 */ line = LINE_INIT; entry = ENTRY_INIT; cp = buf; len = sizeof (buf); while (s_fgets(cp, len, fp) != NULL) { n = strlen(cp); if (cp[n - 1] == '\\') { len -= n - 1; assert(len >= 2); cp += n - 1; continue; } line_parser(mp, buf, &line, &entry); cp = buf; len = sizeof (buf); } if (fclose(fp) == EOF) { bam_error(_("failed to close file: %s: %s\n"), menu_path, strerror(errno)); } return (mp); } static error_t selector(menu_t *mp, char *opt, int *entry, char **title) { char *eq; char *opt_dup; int entryNum; assert(mp); assert(mp->start); assert(opt); opt_dup = s_strdup(opt); if (entry) *entry = ENTRY_INIT; if (title) *title = NULL; eq = strchr(opt_dup, '='); if (eq == NULL) { bam_error(_("invalid option: %s\n"), opt); free(opt_dup); return (BAM_ERROR); } *eq = '\0'; if (entry && strcmp(opt_dup, OPT_ENTRY_NUM) == 0) { assert(mp->end); entryNum = s_strtol(eq + 1); if (entryNum < 0 || entryNum > mp->end->entryNum) { bam_error(_("invalid boot entry number: %s\n"), eq + 1); free(opt_dup); return (BAM_ERROR); } *entry = entryNum; } else if (title && strcmp(opt_dup, menu_cmds[TITLE_CMD]) == 0) { *title = opt + (eq - opt_dup) + 1; } else { bam_error(_("invalid option: %s\n"), opt); free(opt_dup); return (BAM_ERROR); } free(opt_dup); return (BAM_SUCCESS); } /* * If invoked with no titles/entries (opt == NULL) * only title lines in file are printed. * * If invoked with a title or entry #, all * lines in *every* matching entry are listed */ static error_t list_entry(menu_t *mp, char *menu_path, char *opt) { line_t *lp; int entry = ENTRY_INIT; int found; char *title = NULL; assert(mp); assert(menu_path); /* opt is optional */ BAM_DPRINTF(("%s: entered. args: %s %s\n", "list_entry", menu_path, opt ? opt : "")); if (mp->start == NULL) { bam_error(_("menu file not found: %s\n"), menu_path); return (BAM_ERROR); } if (opt != NULL) { if (selector(mp, opt, &entry, &title) != BAM_SUCCESS) { return (BAM_ERROR); } assert((entry != ENTRY_INIT) ^ (title != NULL)); } else { (void) read_globals(mp, menu_path, menu_cmds[DEFAULT_CMD], 0); (void) read_globals(mp, menu_path, menu_cmds[TIMEOUT_CMD], 0); } found = 0; for (lp = mp->start; lp; lp = lp->next) { if (lp->flags == BAM_COMMENT || lp->flags == BAM_EMPTY) continue; if (opt == NULL && lp->flags == BAM_TITLE) { bam_print(_("%d %s\n"), lp->entryNum, lp->arg); found = 1; continue; } if (entry != ENTRY_INIT && lp->entryNum == entry) { bam_print(_("%s\n"), lp->line); found = 1; continue; } /* * We set the entry value here so that all lines * in entry get printed. If we subsequently match * title in other entries, all lines in those * entries get printed as well. */ if (title && lp->flags == BAM_TITLE && lp->arg && strncmp(title, lp->arg, strlen(title)) == 0) { bam_print(_("%s\n"), lp->line); entry = lp->entryNum; found = 1; continue; } } if (!found) { bam_error(_("no matching entry found\n")); return (BAM_ERROR); } return (BAM_SUCCESS); } int add_boot_entry(menu_t *mp, char *title, char *findroot, char *kernel, char *mod_kernel, char *module, char *bootfs) { int lineNum; int entryNum; char linebuf[BAM_MAXLINE]; menu_cmd_t k_cmd; menu_cmd_t m_cmd; const char *fcn = "add_boot_entry()"; assert(mp); INJECT_ERROR1("ADD_BOOT_ENTRY_FINDROOT_NULL", findroot = NULL); if (findroot == NULL) { bam_error(_("can't find argument for findroot command\n")); return (BAM_ERROR); } if (title == NULL) { title = "Solaris"; /* default to Solaris */ } if (kernel == NULL) { bam_error(_("missing suboption: %s\n"), menu_cmds[KERNEL_CMD]); return (BAM_ERROR); } if (module == NULL) { if (bam_direct != BAM_DIRECT_DBOOT) { bam_error(_("missing suboption: %s\n"), menu_cmds[MODULE_CMD]); return (BAM_ERROR); } /* Figure the commands out from the kernel line */ if (strstr(kernel, "$ISADIR") != NULL) { module = DIRECT_BOOT_ARCHIVE; } else if (strstr(kernel, "amd64") != NULL) { module = DIRECT_BOOT_ARCHIVE_64; } else { module = DIRECT_BOOT_ARCHIVE_32; } } k_cmd = KERNEL_DOLLAR_CMD; m_cmd = MODULE_DOLLAR_CMD; if (mp->start) { lineNum = mp->end->lineNum; entryNum = mp->end->entryNum; } else { lineNum = LINE_INIT; entryNum = ENTRY_INIT; } /* * No separator for comment (HDR/FTR) commands * The syntax for comments is # */ (void) snprintf(linebuf, sizeof (linebuf), "%s%s", menu_cmds[COMMENT_CMD], BAM_BOOTADM_HDR); line_parser(mp, linebuf, &lineNum, &entryNum); (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[TITLE_CMD], menu_cmds[SEP_CMD], title); line_parser(mp, linebuf, &lineNum, &entryNum); (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[FINDROOT_CMD], menu_cmds[SEP_CMD], findroot); line_parser(mp, linebuf, &lineNum, &entryNum); BAM_DPRINTF(("%s: findroot added: line#: %d: entry#: %d\n", fcn, lineNum, entryNum)); if (bootfs != NULL) { (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[BOOTFS_CMD], menu_cmds[SEP_CMD], bootfs); line_parser(mp, linebuf, &lineNum, &entryNum); } (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[k_cmd], menu_cmds[SEP_CMD], kernel); line_parser(mp, linebuf, &lineNum, &entryNum); if (mod_kernel != NULL) { (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[m_cmd], menu_cmds[SEP_CMD], mod_kernel); line_parser(mp, linebuf, &lineNum, &entryNum); } (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[m_cmd], menu_cmds[SEP_CMD], module); line_parser(mp, linebuf, &lineNum, &entryNum); (void) snprintf(linebuf, sizeof (linebuf), "%s%s", menu_cmds[COMMENT_CMD], BAM_BOOTADM_FTR); line_parser(mp, linebuf, &lineNum, &entryNum); return (entryNum); } error_t delete_boot_entry(menu_t *mp, int entryNum, int quiet) { line_t *lp; line_t *freed; entry_t *ent; entry_t *tmp; int deleted = 0; const char *fcn = "delete_boot_entry()"; assert(entryNum != ENTRY_INIT); tmp = NULL; ent = mp->entries; while (ent) { lp = ent->start; /* * Check entry number and make sure it's a modifiable entry. * * Guidelines: * + We can modify a bootadm-created entry * + We can modify a libbe-created entry */ if ((lp->flags != BAM_COMMENT && (((ent->flags & BAM_ENTRY_LIBBE) == 0) && strcmp(lp->arg, BAM_BOOTADM_HDR) != 0)) || (entryNum != ALL_ENTRIES && lp->entryNum != entryNum)) { ent = ent->next; continue; } /* free the entry content */ do { freed = lp; lp = lp->next; /* prev stays the same */ BAM_DPRINTF(("%s: freeing line: %d\n", fcn, freed->lineNum)); unlink_line(mp, freed); line_free(freed); } while (freed != ent->end); /* free the entry_t structure */ assert(tmp == NULL); tmp = ent; ent = ent->next; if (tmp->prev) tmp->prev->next = ent; else mp->entries = ent; if (ent) ent->prev = tmp->prev; BAM_DPRINTF(("%s: freeing entry: %d\n", fcn, tmp->entryNum)); free(tmp); tmp = NULL; deleted = 1; } assert(tmp == NULL); if (!deleted && entryNum != ALL_ENTRIES) { if (quiet == DBE_PRINTERR) bam_error(_("no matching bootadm entry found\n")); return (BAM_ERROR); } /* * Now that we have deleted an entry, update * the entry numbering and the default cmd. */ update_numbering(mp); return (BAM_SUCCESS); } static error_t delete_all_entries(menu_t *mp, char *dummy, char *opt) { assert(mp); assert(dummy == NULL); assert(opt == NULL); BAM_DPRINTF(("%s: entered. No args\n", "delete_all_entries")); if (mp->start == NULL) { bam_print(_("the GRUB menu is empty\n")); return (BAM_SUCCESS); } if (delete_boot_entry(mp, ALL_ENTRIES, DBE_PRINTERR) != BAM_SUCCESS) { return (BAM_ERROR); } return (BAM_WRITE); } static FILE * create_diskmap(char *osroot) { FILE *fp; char cmd[PATH_MAX + 16]; char path[PATH_MAX]; const char *fcn = "create_diskmap()"; /* make sure we have a map file */ fp = fopen(GRUBDISK_MAP, "r"); if (fp == NULL) { int ret; ret = snprintf(path, sizeof (path), "%s/%s", osroot, CREATE_DISKMAP); if (ret >= sizeof (path)) { bam_error(_("unable to create path on mountpoint %s, " "path too long\n"), osroot); return (NULL); } if (is_safe_exec(path) == BAM_ERROR) return (NULL); (void) snprintf(cmd, sizeof (cmd), "%s/%s > /dev/null", osroot, CREATE_DISKMAP); if (exec_cmd(cmd, NULL) != 0) return (NULL); fp = fopen(GRUBDISK_MAP, "r"); INJECT_ERROR1("DISKMAP_CREATE_FAIL", fp = NULL); if (fp) { BAM_DPRINTF(("%s: created diskmap file: %s\n", fcn, GRUBDISK_MAP)); } else { BAM_DPRINTF(("%s: FAILED to create diskmap file: %s\n", fcn, GRUBDISK_MAP)); } } return (fp); } #define SECTOR_SIZE 512 static int get_partition(char *device) { int i, fd, is_pcfs, partno = PARTNO_NOTFOUND; struct mboot *mboot; char boot_sect[SECTOR_SIZE]; char *wholedisk, *slice; #ifdef i386 ext_part_t *epp; uint32_t secnum, numsec; int rval, pno, ext_partno = PARTNO_NOTFOUND; #endif /* form whole disk (p0) */ slice = device + strlen(device) - 2; is_pcfs = (*slice != 's'); if (!is_pcfs) *slice = '\0'; wholedisk = s_calloc(1, strlen(device) + 3); (void) snprintf(wholedisk, strlen(device) + 3, "%sp0", device); if (!is_pcfs) *slice = 's'; /* read boot sector */ fd = open(wholedisk, O_RDONLY); if (fd == -1 || read(fd, boot_sect, SECTOR_SIZE) != SECTOR_SIZE) { return (partno); } (void) close(fd); #ifdef i386 /* Read/Initialize extended partition information */ if ((rval = libfdisk_init(&epp, wholedisk, NULL, FDISK_READ_DISK)) != FDISK_SUCCESS) { switch (rval) { /* * FDISK_EBADLOGDRIVE and FDISK_ENOLOGDRIVE can * be considered as soft errors and hence * we do not return */ case FDISK_EBADLOGDRIVE: break; case FDISK_ENOLOGDRIVE: break; case FDISK_EBADMAGIC: /*FALLTHROUGH*/ default: free(wholedisk); libfdisk_fini(&epp); return (partno); } } #endif free(wholedisk); /* parse fdisk table */ mboot = (struct mboot *)((void *)boot_sect); for (i = 0; i < FD_NUMPART; i++) { struct ipart *part = (struct ipart *)(uintptr_t)mboot->parts + i; if (is_pcfs) { /* looking for solaris boot part */ if (part->systid == 0xbe) { partno = i; break; } } else { /* look for solaris partition, old and new */ if (part->systid == EFI_PMBR) { partno = PARTNO_EFI; break; } #ifdef i386 if ((part->systid == SUNIXOS && (fdisk_is_linux_swap(epp, part->relsect, NULL) != 0)) || part->systid == SUNIXOS2) { #else if (part->systid == SUNIXOS || part->systid == SUNIXOS2) { #endif partno = i; break; } #ifdef i386 if (fdisk_is_dos_extended(part->systid)) ext_partno = i; #endif } } #ifdef i386 /* If no primary solaris partition, check extended partition */ if ((partno == PARTNO_NOTFOUND) && (ext_partno != PARTNO_NOTFOUND)) { rval = fdisk_get_solaris_part(epp, &pno, &secnum, &numsec); if (rval == FDISK_SUCCESS) { partno = pno - 1; } } libfdisk_fini(&epp); #endif return (partno); } char * get_grubroot(char *osroot, char *osdev, char *menu_root) { char *grubroot; /* (hd#,#,#) */ char *slice; char *grubhd = NULL; int fdiskpart; int found = 0; char *devname; char *ctdname = strstr(osdev, "dsk/"); char linebuf[PATH_MAX]; FILE *fp; INJECT_ERROR1("GRUBROOT_INVALID_OSDEV", ctdname = NULL); if (ctdname == NULL) { bam_error(_("not a /dev/[r]dsk name: %s\n"), osdev); return (NULL); } if (menu_root && !menu_on_bootdisk(osroot, menu_root)) { /* menu bears no resemblance to our reality */ bam_error(_("cannot get (hd?,?,?) for menu. menu not on " "bootdisk: %s\n"), osdev); return (NULL); } ctdname += strlen("dsk/"); slice = strrchr(ctdname, 's'); if (slice) *slice = '\0'; fp = create_diskmap(osroot); if (fp == NULL) { bam_error(_("create_diskmap command failed for OS root: %s.\n"), osroot); return (NULL); } rewind(fp); while (s_fgets(linebuf, sizeof (linebuf), fp) != NULL) { grubhd = strtok(linebuf, " \t\n"); if (grubhd) devname = strtok(NULL, " \t\n"); else devname = NULL; if (devname && strcmp(devname, ctdname) == 0) { found = 1; break; } } if (slice) *slice = 's'; (void) fclose(fp); fp = NULL; INJECT_ERROR1("GRUBROOT_BIOSDEV_FAIL", found = 0); if (found == 0) { bam_error(_("not using biosdev command for disk: %s.\n"), osdev); return (NULL); } fdiskpart = get_partition(osdev); INJECT_ERROR1("GRUBROOT_FDISK_FAIL", fdiskpart = PARTNO_NOTFOUND); if (fdiskpart == PARTNO_NOTFOUND) { bam_error(_("failed to determine fdisk partition: %s\n"), osdev); return (NULL); } grubroot = s_calloc(1, 10); if (fdiskpart == PARTNO_EFI) { fdiskpart = atoi(&slice[1]); slice = NULL; } if (slice) { (void) snprintf(grubroot, 10, "(hd%s,%d,%c)", grubhd, fdiskpart, slice[1] + 'a' - '0'); } else (void) snprintf(grubroot, 10, "(hd%s,%d)", grubhd, fdiskpart); assert(fp == NULL); assert(strncmp(grubroot, "(hd", strlen("(hd")) == 0); return (grubroot); } static char * find_primary_common(char *mntpt, char *fstype) { char signdir[PATH_MAX]; char tmpsign[MAXNAMELEN + 1]; char *lu; char *ufs; char *zfs; DIR *dirp = NULL; struct dirent *entp; struct stat sb; const char *fcn = "find_primary_common()"; (void) snprintf(signdir, sizeof (signdir), "%s/%s", mntpt, GRUBSIGN_DIR); if (stat(signdir, &sb) == -1) { BAM_DPRINTF(("%s: no sign dir: %s\n", fcn, signdir)); return (NULL); } dirp = opendir(signdir); INJECT_ERROR1("SIGNDIR_OPENDIR_FAIL", dirp = NULL); if (dirp == NULL) { bam_error(_("opendir of %s failed: %s\n"), signdir, strerror(errno)); return (NULL); } ufs = zfs = lu = NULL; while ((entp = readdir(dirp)) != NULL) { if (strcmp(entp->d_name, ".") == 0 || strcmp(entp->d_name, "..") == 0) continue; (void) snprintf(tmpsign, sizeof (tmpsign), "%s", entp->d_name); if (lu == NULL && strncmp(tmpsign, GRUBSIGN_LU_PREFIX, strlen(GRUBSIGN_LU_PREFIX)) == 0) { lu = s_strdup(tmpsign); } if (ufs == NULL && strncmp(tmpsign, GRUBSIGN_UFS_PREFIX, strlen(GRUBSIGN_UFS_PREFIX)) == 0) { ufs = s_strdup(tmpsign); } if (zfs == NULL && strncmp(tmpsign, GRUBSIGN_ZFS_PREFIX, strlen(GRUBSIGN_ZFS_PREFIX)) == 0) { zfs = s_strdup(tmpsign); } } BAM_DPRINTF(("%s: existing primary signs: zfs=%s ufs=%s lu=%s\n", fcn, zfs ? zfs : "NULL", ufs ? ufs : "NULL", lu ? lu : "NULL")); if (dirp) { (void) closedir(dirp); dirp = NULL; } if (strcmp(fstype, "ufs") == 0 && zfs) { bam_error(_("found mismatched boot signature %s for " "filesystem type: %s.\n"), zfs, "ufs"); free(zfs); zfs = NULL; } else if (strcmp(fstype, "zfs") == 0 && ufs) { bam_error(_("found mismatched boot signature %s for " "filesystem type: %s.\n"), ufs, "zfs"); free(ufs); ufs = NULL; } assert(dirp == NULL); /* For now, we let Live Upgrade take care of its signature itself */ if (lu) { BAM_DPRINTF(("%s: feeing LU sign: %s\n", fcn, lu)); free(lu); lu = NULL; } return (zfs ? zfs : ufs); } static char * find_backup_common(char *mntpt, char *fstype) { FILE *bfp = NULL; char tmpsign[MAXNAMELEN + 1]; char backup[PATH_MAX]; char *ufs; char *zfs; char *lu; int error; const char *fcn = "find_backup_common()"; /* * We didn't find it in the primary directory. * Look at the backup */ (void) snprintf(backup, sizeof (backup), "%s%s", mntpt, GRUBSIGN_BACKUP); bfp = fopen(backup, "r"); if (bfp == NULL) { error = errno; if (bam_verbose) { bam_error(_("failed to open file: %s: %s\n"), backup, strerror(error)); } BAM_DPRINTF(("%s: failed to open %s: %s\n", fcn, backup, strerror(error))); return (NULL); } ufs = zfs = lu = NULL; while (s_fgets(tmpsign, sizeof (tmpsign), bfp) != NULL) { if (lu == NULL && strncmp(tmpsign, GRUBSIGN_LU_PREFIX, strlen(GRUBSIGN_LU_PREFIX)) == 0) { lu = s_strdup(tmpsign); } if (ufs == NULL && strncmp(tmpsign, GRUBSIGN_UFS_PREFIX, strlen(GRUBSIGN_UFS_PREFIX)) == 0) { ufs = s_strdup(tmpsign); } if (zfs == NULL && strncmp(tmpsign, GRUBSIGN_ZFS_PREFIX, strlen(GRUBSIGN_ZFS_PREFIX)) == 0) { zfs = s_strdup(tmpsign); } } BAM_DPRINTF(("%s: existing backup signs: zfs=%s ufs=%s lu=%s\n", fcn, zfs ? zfs : "NULL", ufs ? ufs : "NULL", lu ? lu : "NULL")); if (bfp) { (void) fclose(bfp); bfp = NULL; } if (strcmp(fstype, "ufs") == 0 && zfs) { bam_error(_("found mismatched boot signature %s for " "filesystem type: %s.\n"), zfs, "ufs"); free(zfs); zfs = NULL; } else if (strcmp(fstype, "zfs") == 0 && ufs) { bam_error(_("found mismatched boot signature %s for " "filesystem type: %s.\n"), ufs, "zfs"); free(ufs); ufs = NULL; } assert(bfp == NULL); /* For now, we let Live Upgrade take care of its signature itself */ if (lu) { BAM_DPRINTF(("%s: feeing LU sign: %s\n", fcn, lu)); free(lu); lu = NULL; } return (zfs ? zfs : ufs); } static char * find_ufs_existing(char *osroot) { char *sign; const char *fcn = "find_ufs_existing()"; sign = find_primary_common(osroot, "ufs"); if (sign == NULL) { sign = find_backup_common(osroot, "ufs"); BAM_DPRINTF(("%s: existing backup sign: %s\n", fcn, sign ? sign : "NULL")); } else { BAM_DPRINTF(("%s: existing primary sign: %s\n", fcn, sign)); } return (sign); } char * get_mountpoint(char *special, char *fstype) { FILE *mntfp; struct mnttab mp = {0}; struct mnttab mpref = {0}; int error; int ret; const char *fcn = "get_mountpoint()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, special, fstype)); mntfp = fopen(MNTTAB, "r"); error = errno; INJECT_ERROR1("MNTTAB_ERR_GET_MNTPT", mntfp = NULL); if (mntfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(error)); return (NULL); } mpref.mnt_special = special; mpref.mnt_fstype = fstype; ret = getmntany(mntfp, &mp, &mpref); INJECT_ERROR1("GET_MOUNTPOINT_MNTANY", ret = 1); if (ret != 0) { (void) fclose(mntfp); BAM_DPRINTF(("%s: no mount-point for special=%s and " "fstype=%s\n", fcn, special, fstype)); return (NULL); } (void) fclose(mntfp); assert(mp.mnt_mountp); BAM_DPRINTF(("%s: returning mount-point for special %s: %s\n", fcn, special, mp.mnt_mountp)); return (s_strdup(mp.mnt_mountp)); } /* * Mounts a "legacy" top dataset (if needed) * Returns: The mountpoint of the legacy top dataset or NULL on error * mnted returns one of the above values defined for zfs_mnted_t */ static char * mount_legacy_dataset(char *pool, zfs_mnted_t *mnted) { char cmd[PATH_MAX]; char tmpmnt[PATH_MAX]; filelist_t flist = {0}; char *is_mounted; struct stat sb; int ret; const char *fcn = "mount_legacy_dataset()"; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, pool)); *mnted = ZFS_MNT_ERROR; (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs get -Ho value mounted %s", pool); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_CMD", ret = 1); if (ret != 0) { bam_error(_("failed to determine mount status of ZFS " "pool %s\n"), pool); return (NULL); } INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_OUT", flist.head = NULL); if ((flist.head == NULL) || (flist.head != flist.tail)) { bam_error(_("ZFS pool %s has bad mount status\n"), pool); filelist_free(&flist); return (NULL); } is_mounted = strtok(flist.head->line, " \t\n"); INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_STRTOK_YES", is_mounted = "yes"); INJECT_ERROR1("Z_MOUNT_LEG_GET_MOUNTED_STRTOK_NO", is_mounted = "no"); if (strcmp(is_mounted, "no") != 0) { filelist_free(&flist); *mnted = LEGACY_ALREADY; /* get_mountpoint returns a strdup'ed string */ BAM_DPRINTF(("%s: legacy pool %s already mounted\n", fcn, pool)); return (get_mountpoint(pool, "zfs")); } filelist_free(&flist); /* * legacy top dataset is not mounted. Mount it now * First create a mountpoint. */ (void) snprintf(tmpmnt, sizeof (tmpmnt), "%s.%d", ZFS_LEGACY_MNTPT, getpid()); ret = stat(tmpmnt, &sb); if (ret == -1) { BAM_DPRINTF(("%s: legacy pool %s mount-point %s absent\n", fcn, pool, tmpmnt)); ret = mkdirp(tmpmnt, DIR_PERMS); INJECT_ERROR1("Z_MOUNT_TOP_LEG_MNTPT_MKDIRP", ret = -1); if (ret == -1) { bam_error(_("mkdir of %s failed: %s\n"), tmpmnt, strerror(errno)); return (NULL); } } else { BAM_DPRINTF(("%s: legacy pool %s mount-point %s is already " "present\n", fcn, pool, tmpmnt)); } (void) snprintf(cmd, sizeof (cmd), "/sbin/mount -F zfs %s %s", pool, tmpmnt); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("Z_MOUNT_TOP_LEG_MOUNT_CMD", ret = 1); if (ret != 0) { bam_error(_("mount of ZFS pool %s failed\n"), pool); (void) rmdir(tmpmnt); return (NULL); } *mnted = LEGACY_MOUNTED; BAM_DPRINTF(("%s: legacy pool %s successfully mounted at %s\n", fcn, pool, tmpmnt)); return (s_strdup(tmpmnt)); } /* * Mounts the top dataset (if needed) * Returns: The mountpoint of the top dataset or NULL on error * mnted returns one of the above values defined for zfs_mnted_t */ char * mount_top_dataset(char *pool, zfs_mnted_t *mnted) { char cmd[PATH_MAX]; filelist_t flist = {0}; char *is_mounted; char *mntpt; char *zmntpt; int ret; const char *fcn = "mount_top_dataset()"; *mnted = ZFS_MNT_ERROR; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, pool)); /* * First check if the top dataset is a "legacy" dataset */ (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs get -Ho value mountpoint %s", pool); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("Z_MOUNT_TOP_GET_MNTPT", ret = 1); if (ret != 0) { bam_error(_("failed to determine mount point of ZFS pool %s\n"), pool); return (NULL); } if (flist.head && (flist.head == flist.tail)) { char *legacy = strtok(flist.head->line, " \t\n"); if (legacy && strcmp(legacy, "legacy") == 0) { filelist_free(&flist); BAM_DPRINTF(("%s: is legacy, pool=%s\n", fcn, pool)); return (mount_legacy_dataset(pool, mnted)); } } filelist_free(&flist); BAM_DPRINTF(("%s: is *NOT* legacy, pool=%s\n", fcn, pool)); (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs get -Ho value mounted %s", pool); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED", ret = 1); if (ret != 0) { bam_error(_("failed to determine mount status of ZFS " "pool %s\n"), pool); return (NULL); } INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_VAL", flist.head = NULL); if ((flist.head == NULL) || (flist.head != flist.tail)) { bam_error(_("ZFS pool %s has bad mount status\n"), pool); filelist_free(&flist); return (NULL); } is_mounted = strtok(flist.head->line, " \t\n"); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_YES", is_mounted = "yes"); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MOUNTED_NO", is_mounted = "no"); if (strcmp(is_mounted, "no") != 0) { filelist_free(&flist); *mnted = ZFS_ALREADY; BAM_DPRINTF(("%s: non-legacy pool %s mounted already\n", fcn, pool)); goto mounted; } filelist_free(&flist); BAM_DPRINTF(("%s: non-legacy pool %s *NOT* already mounted\n", fcn, pool)); /* top dataset is not mounted. Mount it now */ (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs mount %s", pool); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_MOUNT_CMD", ret = 1); if (ret != 0) { bam_error(_("mount of ZFS pool %s failed\n"), pool); return (NULL); } *mnted = ZFS_MOUNTED; BAM_DPRINTF(("%s: non-legacy pool %s mounted now\n", fcn, pool)); /*FALLTHRU*/ mounted: /* * Now get the mountpoint */ (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs get -Ho value mountpoint %s", pool); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_CMD", ret = 1); if (ret != 0) { bam_error(_("failed to determine mount point of ZFS pool %s\n"), pool); goto error; } INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_OUT", flist.head = NULL); if ((flist.head == NULL) || (flist.head != flist.tail)) { bam_error(_("ZFS pool %s has no mount-point\n"), pool); goto error; } mntpt = strtok(flist.head->line, " \t\n"); INJECT_ERROR1("Z_MOUNT_TOP_NONLEG_GET_MNTPT_STRTOK", mntpt = "foo"); if (*mntpt != '/') { bam_error(_("ZFS pool %s has bad mount-point %s\n"), pool, mntpt); goto error; } zmntpt = s_strdup(mntpt); filelist_free(&flist); BAM_DPRINTF(("%s: non-legacy pool %s is mounted at %s\n", fcn, pool, zmntpt)); return (zmntpt); error: filelist_free(&flist); (void) umount_top_dataset(pool, *mnted, NULL); BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); return (NULL); } int umount_top_dataset(char *pool, zfs_mnted_t mnted, char *mntpt) { char cmd[PATH_MAX]; int ret; const char *fcn = "umount_top_dataset()"; INJECT_ERROR1("Z_UMOUNT_TOP_INVALID_STATE", mnted = ZFS_MNT_ERROR); switch (mnted) { case LEGACY_ALREADY: case ZFS_ALREADY: /* nothing to do */ BAM_DPRINTF(("%s: pool %s was already mounted at %s, Nothing " "to umount\n", fcn, pool, mntpt ? mntpt : "NULL")); free(mntpt); return (BAM_SUCCESS); case LEGACY_MOUNTED: (void) snprintf(cmd, sizeof (cmd), "/sbin/umount %s", pool); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("Z_UMOUNT_TOP_LEGACY_UMOUNT_FAIL", ret = 1); if (ret != 0) { bam_error(_("umount of %s failed\n"), pool); free(mntpt); return (BAM_ERROR); } if (mntpt) (void) rmdir(mntpt); free(mntpt); BAM_DPRINTF(("%s: legacy pool %s was mounted by us, " "successfully unmounted\n", fcn, pool)); return (BAM_SUCCESS); case ZFS_MOUNTED: free(mntpt); (void) snprintf(cmd, sizeof (cmd), "/sbin/zfs unmount %s", pool); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("Z_UMOUNT_TOP_NONLEG_UMOUNT_FAIL", ret = 1); if (ret != 0) { bam_error(_("umount of %s failed\n"), pool); return (BAM_ERROR); } BAM_DPRINTF(("%s: nonleg pool %s was mounted by us, " "successfully unmounted\n", fcn, pool)); return (BAM_SUCCESS); default: bam_error(_("Internal error: bad saved mount state for " "pool %s\n"), pool); return (BAM_ERROR); } /*NOTREACHED*/ } /* * For ZFS, osdev can be one of two forms * It can be a "special" file as seen in mnttab: rpool/ROOT/szboot_0402 * It can be a /dev/[r]dsk special file. We handle both instances */ static char * get_pool(char *osdev) { char cmd[PATH_MAX]; char buf[PATH_MAX]; filelist_t flist = {0}; char *pool; char *cp; char *slash; int ret; const char *fcn = "get_pool()"; INJECT_ERROR1("GET_POOL_OSDEV", osdev = NULL); if (osdev == NULL) { bam_error(_("NULL device: cannot determine pool name\n")); return (NULL); } BAM_DPRINTF(("%s: osdev arg = %s\n", fcn, osdev)); if (osdev[0] != '/') { (void) strlcpy(buf, osdev, sizeof (buf)); slash = strchr(buf, '/'); if (slash) *slash = '\0'; pool = s_strdup(buf); BAM_DPRINTF(("%s: got pool. pool = %s\n", fcn, pool)); return (pool); } else if (strncmp(osdev, "/dev/dsk/", strlen("/dev/dsk/")) != 0 && strncmp(osdev, "/dev/rdsk/", strlen("/dev/rdsk/")) != 0) { bam_error(_("invalid device %s: cannot determine pool name\n"), osdev); return (NULL); } /* * Call the zfs fstyp directly since this is a zpool. This avoids * potential pcfs conflicts if the first block wasn't cleared. */ (void) snprintf(cmd, sizeof (cmd), "/usr/lib/fs/zfs/fstyp -a %s 2>/dev/null | /bin/grep '^name:'", osdev); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("GET_POOL_FSTYP", ret = 1); if (ret != 0) { bam_error(_("fstyp -a on device %s failed\n"), osdev); return (NULL); } INJECT_ERROR1("GET_POOL_FSTYP_OUT", flist.head = NULL); if ((flist.head == NULL) || (flist.head != flist.tail)) { bam_error(_("NULL fstyp -a output for device %s\n"), osdev); filelist_free(&flist); return (NULL); } (void) strtok(flist.head->line, "'"); cp = strtok(NULL, "'"); INJECT_ERROR1("GET_POOL_FSTYP_STRTOK", cp = NULL); if (cp == NULL) { bam_error(_("bad fstyp -a output for device %s\n"), osdev); filelist_free(&flist); return (NULL); } pool = s_strdup(cp); filelist_free(&flist); BAM_DPRINTF(("%s: got pool. pool = %s\n", fcn, pool)); return (pool); } static char * find_zfs_existing(char *osdev) { char *pool; zfs_mnted_t mnted; char *mntpt; char *sign; const char *fcn = "find_zfs_existing()"; pool = get_pool(osdev); INJECT_ERROR1("ZFS_FIND_EXIST_POOL", pool = NULL); if (pool == NULL) { bam_error(_("failed to get pool for device: %s\n"), osdev); return (NULL); } mntpt = mount_top_dataset(pool, &mnted); INJECT_ERROR1("ZFS_FIND_EXIST_MOUNT_TOP", mntpt = NULL); if (mntpt == NULL) { bam_error(_("failed to mount top dataset for pool: %s\n"), pool); free(pool); return (NULL); } sign = find_primary_common(mntpt, "zfs"); if (sign == NULL) { sign = find_backup_common(mntpt, "zfs"); BAM_DPRINTF(("%s: existing backup sign: %s\n", fcn, sign ? sign : "NULL")); } else { BAM_DPRINTF(("%s: existing primary sign: %s\n", fcn, sign)); } (void) umount_top_dataset(pool, mnted, mntpt); free(pool); return (sign); } static char * find_existing_sign(char *osroot, char *osdev, char *fstype) { const char *fcn = "find_existing_sign()"; INJECT_ERROR1("FIND_EXIST_NOTSUP_FS", fstype = "foofs"); if (strcmp(fstype, "ufs") == 0) { BAM_DPRINTF(("%s: checking for existing UFS sign\n", fcn)); return (find_ufs_existing(osroot)); } else if (strcmp(fstype, "zfs") == 0) { BAM_DPRINTF(("%s: checking for existing ZFS sign\n", fcn)); return (find_zfs_existing(osdev)); } else { bam_error(_("boot signature not supported for fstype: %s\n"), fstype); return (NULL); } } #define MH_HASH_SZ 16 typedef enum { MH_ERROR = -1, MH_NOMATCH, MH_MATCH } mh_search_t; typedef struct mcache { char *mc_special; char *mc_mntpt; char *mc_fstype; struct mcache *mc_next; } mcache_t; typedef struct mhash { mcache_t *mh_hash[MH_HASH_SZ]; } mhash_t; static int mhash_fcn(char *key) { int i; uint64_t sum = 0; for (i = 0; key[i] != '\0'; i++) { sum += (uchar_t)key[i]; } sum %= MH_HASH_SZ; assert(sum < MH_HASH_SZ); return (sum); } static mhash_t * cache_mnttab(void) { FILE *mfp; struct extmnttab mnt; mcache_t *mcp; mhash_t *mhp; char *ctds; int idx; int error; char *special_dup; const char *fcn = "cache_mnttab()"; mfp = fopen(MNTTAB, "r"); error = errno; INJECT_ERROR1("CACHE_MNTTAB_MNTTAB_ERR", mfp = NULL); if (mfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(error)); return (NULL); } mhp = s_calloc(1, sizeof (mhash_t)); resetmnttab(mfp); while (getextmntent(mfp, &mnt, sizeof (mnt)) == 0) { /* only cache ufs */ if (strcmp(mnt.mnt_fstype, "ufs") != 0) continue; /* basename() modifies its arg, so dup it */ special_dup = s_strdup(mnt.mnt_special); ctds = basename(special_dup); mcp = s_calloc(1, sizeof (mcache_t)); mcp->mc_special = s_strdup(ctds); mcp->mc_mntpt = s_strdup(mnt.mnt_mountp); mcp->mc_fstype = s_strdup(mnt.mnt_fstype); BAM_DPRINTF(("%s: caching mount: special=%s, mntpt=%s, " "fstype=%s\n", fcn, ctds, mnt.mnt_mountp, mnt.mnt_fstype)); idx = mhash_fcn(ctds); mcp->mc_next = mhp->mh_hash[idx]; mhp->mh_hash[idx] = mcp; free(special_dup); } (void) fclose(mfp); return (mhp); } static void free_mnttab(mhash_t *mhp) { mcache_t *mcp; int i; for (i = 0; i < MH_HASH_SZ; i++) { while ((mcp = mhp->mh_hash[i]) != NULL) { mhp->mh_hash[i] = mcp->mc_next; free(mcp->mc_special); free(mcp->mc_mntpt); free(mcp->mc_fstype); free(mcp); } } for (i = 0; i < MH_HASH_SZ; i++) { assert(mhp->mh_hash[i] == NULL); } free(mhp); } static mh_search_t search_hash(mhash_t *mhp, char *special, char **mntpt) { int idx; mcache_t *mcp; const char *fcn = "search_hash()"; assert(mntpt); *mntpt = NULL; INJECT_ERROR1("SEARCH_HASH_FULL_PATH", special = "/foo"); if (strchr(special, '/')) { bam_error(_("invalid key for mnttab hash: %s\n"), special); return (MH_ERROR); } idx = mhash_fcn(special); for (mcp = mhp->mh_hash[idx]; mcp; mcp = mcp->mc_next) { if (strcmp(mcp->mc_special, special) == 0) break; } if (mcp == NULL) { BAM_DPRINTF(("%s: no match in cache for: %s\n", fcn, special)); return (MH_NOMATCH); } assert(strcmp(mcp->mc_fstype, "ufs") == 0); *mntpt = mcp->mc_mntpt; BAM_DPRINTF(("%s: *MATCH* in cache for: %s\n", fcn, special)); return (MH_MATCH); } static int check_add_ufs_sign_to_list(FILE *tfp, char *mntpt) { char *sign; char *signline; char signbuf[MAXNAMELEN]; int len; int error; const char *fcn = "check_add_ufs_sign_to_list()"; /* safe to specify NULL as "osdev" arg for UFS */ sign = find_existing_sign(mntpt, NULL, "ufs"); if (sign == NULL) { /* No existing signature, nothing to add to list */ BAM_DPRINTF(("%s: no sign on %s to add to signlist\n", fcn, mntpt)); return (0); } (void) snprintf(signbuf, sizeof (signbuf), "%s\n", sign); signline = signbuf; INJECT_ERROR1("UFS_MNTPT_SIGN_NOTUFS", signline = "pool_rpool10\n"); if (strncmp(signline, GRUBSIGN_UFS_PREFIX, strlen(GRUBSIGN_UFS_PREFIX))) { bam_error(_("invalid UFS boot signature %s\n"), sign); free(sign); /* ignore invalid signatures */ return (0); } len = fputs(signline, tfp); error = errno; INJECT_ERROR1("SIGN_LIST_PUTS_ERROR", len = 0); if (len != strlen(signline)) { bam_error(_("failed to write signature %s to signature " "list: %s\n"), sign, strerror(error)); free(sign); return (-1); } free(sign); BAM_DPRINTF(("%s: successfully added sign on %s to signlist\n", fcn, mntpt)); return (0); } /* * slice is a basename not a full pathname */ static int process_slice_common(char *slice, FILE *tfp, mhash_t *mhp, char *tmpmnt) { int ret; char cmd[PATH_MAX]; char path[PATH_MAX]; struct stat sbuf; char *mntpt; filelist_t flist = {0}; char *fstype; char blkslice[PATH_MAX]; const char *fcn = "process_slice_common()"; ret = search_hash(mhp, slice, &mntpt); switch (ret) { case MH_MATCH: if (check_add_ufs_sign_to_list(tfp, mntpt) == -1) return (-1); else return (0); case MH_NOMATCH: break; case MH_ERROR: default: return (-1); } (void) snprintf(path, sizeof (path), "/dev/rdsk/%s", slice); if (stat(path, &sbuf) == -1) { BAM_DPRINTF(("%s: slice does not exist: %s\n", fcn, path)); return (0); } /* Check if ufs. Call ufs fstyp directly to avoid pcfs conflicts. */ (void) snprintf(cmd, sizeof (cmd), "/usr/lib/fs/ufs/fstyp /dev/rdsk/%s 2>/dev/null", slice); if (exec_cmd(cmd, &flist) != 0) { if (bam_verbose) bam_print(_("fstyp failed for slice: %s\n"), slice); return (0); } if ((flist.head == NULL) || (flist.head != flist.tail)) { if (bam_verbose) bam_print(_("bad output from fstyp for slice: %s\n"), slice); filelist_free(&flist); return (0); } fstype = strtok(flist.head->line, " \t\n"); if (fstype == NULL || strcmp(fstype, "ufs") != 0) { if (bam_verbose) bam_print(_("%s is not a ufs slice: %s\n"), slice, fstype); filelist_free(&flist); return (0); } filelist_free(&flist); /* * Since we are mounting the filesystem read-only, the * the last mount field of the superblock is unchanged * and does not need to be fixed up post-mount; */ (void) snprintf(blkslice, sizeof (blkslice), "/dev/dsk/%s", slice); (void) snprintf(cmd, sizeof (cmd), "/sbin/mount -F ufs -o ro %s %s " "> /dev/null 2>&1", blkslice, tmpmnt); if (exec_cmd(cmd, NULL) != 0) { if (bam_verbose) bam_print(_("mount of %s (fstype %s) failed\n"), blkslice, "ufs"); return (0); } ret = check_add_ufs_sign_to_list(tfp, tmpmnt); (void) snprintf(cmd, sizeof (cmd), "/sbin/umount -f %s > /dev/null 2>&1", tmpmnt); if (exec_cmd(cmd, NULL) != 0) { bam_print(_("umount of %s failed\n"), slice); return (0); } return (ret); } static int process_vtoc_slices( char *s0, struct vtoc *vtoc, FILE *tfp, mhash_t *mhp, char *tmpmnt) { int idx; char slice[PATH_MAX]; size_t len; char *cp; const char *fcn = "process_vtoc_slices()"; len = strlen(s0); assert(s0[len - 2] == 's' && s0[len - 1] == '0'); s0[len - 1] = '\0'; (void) strlcpy(slice, s0, sizeof (slice)); s0[len - 1] = '0'; cp = slice + len - 1; for (idx = 0; idx < vtoc->v_nparts; idx++) { (void) snprintf(cp, sizeof (slice) - (len - 1), "%u", idx); if (vtoc->v_part[idx].p_size == 0) { BAM_DPRINTF(("%s: VTOC: skipping 0-length slice: %s\n", fcn, slice)); continue; } /* Skip "SWAP", "USR", "BACKUP", "VAR", "HOME", "ALTSCTR" */ switch (vtoc->v_part[idx].p_tag) { case V_SWAP: case V_USR: case V_BACKUP: case V_VAR: case V_HOME: case V_ALTSCTR: BAM_DPRINTF(("%s: VTOC: unsupported tag, " "skipping: %s\n", fcn, slice)); continue; default: BAM_DPRINTF(("%s: VTOC: supported tag, checking: %s\n", fcn, slice)); break; } /* skip unmountable and readonly slices */ switch (vtoc->v_part[idx].p_flag) { case V_UNMNT: case V_RONLY: BAM_DPRINTF(("%s: VTOC: non-RDWR flag, skipping: %s\n", fcn, slice)); continue; default: BAM_DPRINTF(("%s: VTOC: RDWR flag, checking: %s\n", fcn, slice)); break; } if (process_slice_common(slice, tfp, mhp, tmpmnt) == -1) { return (-1); } } return (0); } static int process_efi_slices( char *s0, struct dk_gpt *efi, FILE *tfp, mhash_t *mhp, char *tmpmnt) { int idx; char slice[PATH_MAX]; size_t len; char *cp; const char *fcn = "process_efi_slices()"; len = strlen(s0); assert(s0[len - 2] == 's' && s0[len - 1] == '0'); s0[len - 1] = '\0'; (void) strlcpy(slice, s0, sizeof (slice)); s0[len - 1] = '0'; cp = slice + len - 1; for (idx = 0; idx < efi->efi_nparts; idx++) { (void) snprintf(cp, sizeof (slice) - (len - 1), "%u", idx); if (efi->efi_parts[idx].p_size == 0) { BAM_DPRINTF(("%s: EFI: skipping 0-length slice: %s\n", fcn, slice)); continue; } /* Skip "SWAP", "USR", "BACKUP", "VAR", "HOME", "ALTSCTR" */ switch (efi->efi_parts[idx].p_tag) { case V_SWAP: case V_USR: case V_BACKUP: case V_VAR: case V_HOME: case V_ALTSCTR: BAM_DPRINTF(("%s: EFI: unsupported tag, skipping: %s\n", fcn, slice)); continue; default: BAM_DPRINTF(("%s: EFI: supported tag, checking: %s\n", fcn, slice)); break; } /* skip unmountable and readonly slices */ switch (efi->efi_parts[idx].p_flag) { case V_UNMNT: case V_RONLY: BAM_DPRINTF(("%s: EFI: non-RDWR flag, skipping: %s\n", fcn, slice)); continue; default: BAM_DPRINTF(("%s: EFI: RDWR flag, checking: %s\n", fcn, slice)); break; } if (process_slice_common(slice, tfp, mhp, tmpmnt) == -1) { return (-1); } } return (0); } /* * s0 is a basename not a full path */ static int process_slice0(char *s0, FILE *tfp, mhash_t *mhp, char *tmpmnt) { struct vtoc vtoc; struct dk_gpt *efi; char s0path[PATH_MAX]; struct stat sbuf; int e_flag; int v_flag; int retval; int err; int fd; const char *fcn = "process_slice0()"; (void) snprintf(s0path, sizeof (s0path), "/dev/rdsk/%s", s0); if (stat(s0path, &sbuf) == -1) { BAM_DPRINTF(("%s: slice 0 does not exist: %s\n", fcn, s0path)); return (0); } fd = open(s0path, O_NONBLOCK|O_RDONLY); if (fd == -1) { bam_error(_("failed to open file: %s: %s\n"), s0path, strerror(errno)); return (0); } e_flag = v_flag = 0; retval = ((err = read_vtoc(fd, &vtoc)) >= 0) ? 0 : err; switch (retval) { case VT_EIO: BAM_DPRINTF(("%s: VTOC: failed to read: %s\n", fcn, s0path)); break; case VT_EINVAL: BAM_DPRINTF(("%s: VTOC: is INVALID: %s\n", fcn, s0path)); break; case VT_ERROR: BAM_DPRINTF(("%s: VTOC: unknown error while " "reading: %s\n", fcn, s0path)); break; case VT_ENOTSUP: e_flag = 1; BAM_DPRINTF(("%s: VTOC: not supported: %s\n", fcn, s0path)); break; case 0: v_flag = 1; BAM_DPRINTF(("%s: VTOC: SUCCESS reading: %s\n", fcn, s0path)); break; default: BAM_DPRINTF(("%s: VTOC: READ: unknown return " "code: %s\n", fcn, s0path)); break; } if (e_flag) { e_flag = 0; retval = ((err = efi_alloc_and_read(fd, &efi)) >= 0) ? 0 : err; switch (retval) { case VT_EIO: BAM_DPRINTF(("%s: EFI: failed to read: %s\n", fcn, s0path)); break; case VT_EINVAL: BAM_DPRINTF(("%s: EFI: is INVALID: %s\n", fcn, s0path)); break; case VT_ERROR: BAM_DPRINTF(("%s: EFI: unknown error while " "reading: %s\n", fcn, s0path)); break; case VT_ENOTSUP: BAM_DPRINTF(("%s: EFI: not supported: %s\n", fcn, s0path)); break; case 0: e_flag = 1; BAM_DPRINTF(("%s: EFI: SUCCESS reading: %s\n", fcn, s0path)); break; default: BAM_DPRINTF(("%s: EFI: READ: unknown return code: %s\n", fcn, s0path)); break; } } (void) close(fd); if (v_flag) { retval = process_vtoc_slices(s0, &vtoc, tfp, mhp, tmpmnt); } else if (e_flag) { retval = process_efi_slices(s0, efi, tfp, mhp, tmpmnt); } else { BAM_DPRINTF(("%s: disk has neither VTOC nor EFI: %s\n", fcn, s0path)); return (0); } return (retval); } /* * Find and create a list of all existing UFS boot signatures */ static int FindAllUfsSignatures(void) { mhash_t *mnttab_hash; DIR *dirp = NULL; struct dirent *dp; char tmpmnt[PATH_MAX]; char cmd[PATH_MAX]; struct stat sb; int fd; FILE *tfp; size_t len; int ret; int error; const char *fcn = "FindAllUfsSignatures()"; if (stat(UFS_SIGNATURE_LIST, &sb) != -1) { bam_print(_(" - signature list %s exists\n"), UFS_SIGNATURE_LIST); return (0); } fd = open(UFS_SIGNATURE_LIST".tmp", O_RDWR|O_CREAT|O_TRUNC, 0644); error = errno; INJECT_ERROR1("SIGN_LIST_TMP_TRUNC", fd = -1); if (fd == -1) { bam_error(_("failed to open file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); return (-1); } ret = close(fd); error = errno; INJECT_ERROR1("SIGN_LIST_TMP_CLOSE", ret = -1); if (ret == -1) { bam_error(_("failed to close file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (-1); } tfp = fopen(UFS_SIGNATURE_LIST".tmp", "a"); error = errno; INJECT_ERROR1("SIGN_LIST_APPEND_FOPEN", tfp = NULL); if (tfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (-1); } mnttab_hash = cache_mnttab(); INJECT_ERROR1("CACHE_MNTTAB_ERROR", mnttab_hash = NULL); if (mnttab_hash == NULL) { (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST".tmp"); bam_error(_("%s: failed to cache /etc/mnttab\n"), fcn); return (-1); } (void) snprintf(tmpmnt, sizeof (tmpmnt), "/tmp/bootadm_ufs_sign_mnt.%d", getpid()); (void) unlink(tmpmnt); ret = mkdirp(tmpmnt, DIR_PERMS); error = errno; INJECT_ERROR1("MKDIRP_SIGN_MNT", ret = -1); if (ret == -1) { bam_error(_("mkdir of %s failed: %s\n"), tmpmnt, strerror(error)); free_mnttab(mnttab_hash); (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (-1); } dirp = opendir("/dev/rdsk"); error = errno; INJECT_ERROR1("OPENDIR_DEV_RDSK", dirp = NULL); if (dirp == NULL) { bam_error(_("opendir of %s failed: %s\n"), "/dev/rdsk", strerror(error)); goto fail; } while ((dp = readdir(dirp)) != NULL) { if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0) continue; /* * we only look for the s0 slice. This is guranteed to * have 's' at len - 2. */ len = strlen(dp->d_name); if (dp->d_name[len - 2 ] != 's' || dp->d_name[len - 1] != '0') { BAM_DPRINTF(("%s: skipping non-s0 slice: %s\n", fcn, dp->d_name)); continue; } ret = process_slice0(dp->d_name, tfp, mnttab_hash, tmpmnt); INJECT_ERROR1("PROCESS_S0_FAIL", ret = -1); if (ret == -1) goto fail; } (void) closedir(dirp); free_mnttab(mnttab_hash); (void) rmdir(tmpmnt); ret = fclose(tfp); error = errno; INJECT_ERROR1("FCLOSE_SIGNLIST_TMP", ret = EOF); if (ret == EOF) { bam_error(_("failed to close file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (-1); } /* We have a list of existing GRUB signatures. Sort it first */ (void) snprintf(cmd, sizeof (cmd), "/bin/sort -u %s.tmp > %s.sorted", UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("SORT_SIGN_LIST", ret = 1); if (ret != 0) { bam_error(_("error sorting GRUB UFS boot signatures\n")); (void) unlink(UFS_SIGNATURE_LIST".sorted"); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (-1); } (void) unlink(UFS_SIGNATURE_LIST".tmp"); ret = rename(UFS_SIGNATURE_LIST".sorted", UFS_SIGNATURE_LIST); error = errno; INJECT_ERROR1("RENAME_TMP_SIGNLIST", ret = -1); if (ret == -1) { bam_error(_("rename to file failed: %s: %s\n"), UFS_SIGNATURE_LIST, strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".sorted"); return (-1); } if (stat(UFS_SIGNATURE_LIST, &sb) == 0 && sb.st_size == 0) { BAM_DPRINTF(("%s: generated zero length signlist: %s.\n", fcn, UFS_SIGNATURE_LIST)); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (0); fail: if (dirp) (void) closedir(dirp); free_mnttab(mnttab_hash); (void) rmdir(tmpmnt); (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST".tmp"); BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); return (-1); } static char * create_ufs_sign(void) { struct stat sb; int signnum = -1; char tmpsign[MAXNAMELEN + 1]; char *numstr; int i; FILE *tfp; int ret; int error; const char *fcn = "create_ufs_sign()"; bam_print(_(" - searching for UFS boot signatures\n")); ret = FindAllUfsSignatures(); INJECT_ERROR1("FIND_ALL_UFS", ret = -1); if (ret == -1) { bam_error(_("search for UFS boot signatures failed\n")); return (NULL); } /* Make sure the list exists and is owned by root */ INJECT_ERROR1("SIGNLIST_NOT_CREATED", (void) unlink(UFS_SIGNATURE_LIST)); if (stat(UFS_SIGNATURE_LIST, &sb) == -1 || sb.st_uid != 0) { (void) unlink(UFS_SIGNATURE_LIST); bam_error(_("missing UFS signature list file: %s\n"), UFS_SIGNATURE_LIST); return (NULL); } if (sb.st_size == 0) { bam_print(_(" - no existing UFS boot signatures\n")); i = 0; goto found; } /* The signature list was sorted when it was created */ tfp = fopen(UFS_SIGNATURE_LIST, "r"); error = errno; INJECT_ERROR1("FOPEN_SIGN_LIST", tfp = NULL); if (tfp == NULL) { bam_error(_("error opening UFS boot signature list " "file %s: %s\n"), UFS_SIGNATURE_LIST, strerror(error)); (void) unlink(UFS_SIGNATURE_LIST); return (NULL); } for (i = 0; s_fgets(tmpsign, sizeof (tmpsign), tfp); i++) { if (strncmp(tmpsign, GRUBSIGN_UFS_PREFIX, strlen(GRUBSIGN_UFS_PREFIX)) != 0) { (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST); bam_error(_("bad UFS boot signature: %s\n"), tmpsign); return (NULL); } numstr = tmpsign + strlen(GRUBSIGN_UFS_PREFIX); if (numstr[0] == '\0' || !isdigit(numstr[0])) { (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST); bam_error(_("bad UFS boot signature: %s\n"), tmpsign); return (NULL); } signnum = atoi(numstr); INJECT_ERROR1("NEGATIVE_SIGN", signnum = -1); if (signnum < 0) { (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST); bam_error(_("bad UFS boot signature: %s\n"), tmpsign); return (NULL); } if (i != signnum) { BAM_DPRINTF(("%s: found hole %d in sign list.\n", fcn, i)); break; } } (void) fclose(tfp); found: (void) snprintf(tmpsign, sizeof (tmpsign), "rootfs%d", i); /* add the ufs signature to the /var/run list of signatures */ ret = ufs_add_to_sign_list(tmpsign); INJECT_ERROR1("UFS_ADD_TO_SIGN_LIST", ret = -1); if (ret == -1) { (void) unlink(UFS_SIGNATURE_LIST); bam_error(_("failed to add sign %s to signlist.\n"), tmpsign); return (NULL); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (s_strdup(tmpsign)); } static char * get_fstype(char *osroot) { FILE *mntfp; struct mnttab mp = {0}; struct mnttab mpref = {0}; int error; int ret; const char *fcn = "get_fstype()"; INJECT_ERROR1("GET_FSTYPE_OSROOT", osroot = NULL); if (osroot == NULL) { bam_error(_("no OS mountpoint. Cannot determine fstype\n")); return (NULL); } mntfp = fopen(MNTTAB, "r"); error = errno; INJECT_ERROR1("GET_FSTYPE_FOPEN", mntfp = NULL); if (mntfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(error)); return (NULL); } if (*osroot == '\0') mpref.mnt_mountp = "/"; else mpref.mnt_mountp = osroot; ret = getmntany(mntfp, &mp, &mpref); INJECT_ERROR1("GET_FSTYPE_GETMNTANY", ret = 1); if (ret != 0) { bam_error(_("failed to find OS mountpoint %s in %s\n"), osroot, MNTTAB); (void) fclose(mntfp); return (NULL); } (void) fclose(mntfp); INJECT_ERROR1("GET_FSTYPE_NULL", mp.mnt_fstype = NULL); if (mp.mnt_fstype == NULL) { bam_error(_("NULL fstype found for OS root %s\n"), osroot); return (NULL); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (s_strdup(mp.mnt_fstype)); } static char * create_zfs_sign(char *osdev) { char tmpsign[PATH_MAX]; char *pool; const char *fcn = "create_zfs_sign()"; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, osdev)); /* * First find the pool name */ pool = get_pool(osdev); INJECT_ERROR1("CREATE_ZFS_SIGN_GET_POOL", pool = NULL); if (pool == NULL) { bam_error(_("failed to get pool name from %s\n"), osdev); return (NULL); } (void) snprintf(tmpsign, sizeof (tmpsign), "pool_%s", pool); BAM_DPRINTF(("%s: created ZFS sign: %s\n", fcn, tmpsign)); free(pool); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (s_strdup(tmpsign)); } static char * create_new_sign(char *osdev, char *fstype) { char *sign; const char *fcn = "create_new_sign()"; INJECT_ERROR1("NEW_SIGN_FSTYPE", fstype = "foofs"); if (strcmp(fstype, "zfs") == 0) { BAM_DPRINTF(("%s: created new ZFS sign\n", fcn)); sign = create_zfs_sign(osdev); } else if (strcmp(fstype, "ufs") == 0) { BAM_DPRINTF(("%s: created new UFS sign\n", fcn)); sign = create_ufs_sign(); } else { bam_error(_("boot signature not supported for fstype: %s\n"), fstype); sign = NULL; } BAM_DPRINTF(("%s: created new sign: %s\n", fcn, sign ? sign : "")); return (sign); } static int set_backup_common(char *mntpt, char *sign) { FILE *bfp; char backup[PATH_MAX]; char tmpsign[PATH_MAX]; int error; char *bdir; char *backup_dup; struct stat sb; int ret; const char *fcn = "set_backup_common()"; (void) snprintf(backup, sizeof (backup), "%s%s", mntpt, GRUBSIGN_BACKUP); /* First read the backup */ bfp = fopen(backup, "r"); if (bfp != NULL) { while (s_fgets(tmpsign, sizeof (tmpsign), bfp)) { if (strcmp(tmpsign, sign) == 0) { BAM_DPRINTF(("%s: found sign (%s) in backup.\n", fcn, sign)); (void) fclose(bfp); return (0); } } (void) fclose(bfp); BAM_DPRINTF(("%s: backup exists but sign %s not found\n", fcn, sign)); } else { BAM_DPRINTF(("%s: no backup file (%s) found.\n", fcn, backup)); } /* * Didn't find the correct signature. First create * the directory if necessary. */ /* dirname() modifies its argument so dup it */ backup_dup = s_strdup(backup); bdir = dirname(backup_dup); assert(bdir); ret = stat(bdir, &sb); INJECT_ERROR1("SET_BACKUP_STAT", ret = -1); if (ret == -1) { BAM_DPRINTF(("%s: backup dir (%s) does not exist.\n", fcn, bdir)); ret = mkdirp(bdir, DIR_PERMS); error = errno; INJECT_ERROR1("SET_BACKUP_MKDIRP", ret = -1); if (ret == -1) { bam_error(_("mkdirp() of backup dir failed: %s: %s\n"), GRUBSIGN_BACKUP, strerror(error)); free(backup_dup); return (-1); } } free(backup_dup); /* * Open the backup in append mode to add the correct * signature; */ bfp = fopen(backup, "a"); error = errno; INJECT_ERROR1("SET_BACKUP_FOPEN_A", bfp = NULL); if (bfp == NULL) { bam_error(_("error opening boot signature backup " "file %s: %s\n"), GRUBSIGN_BACKUP, strerror(error)); return (-1); } (void) snprintf(tmpsign, sizeof (tmpsign), "%s\n", sign); ret = fputs(tmpsign, bfp); error = errno; INJECT_ERROR1("SET_BACKUP_FPUTS", ret = 0); if (ret != strlen(tmpsign)) { bam_error(_("error writing boot signature backup " "file %s: %s\n"), GRUBSIGN_BACKUP, strerror(error)); (void) fclose(bfp); return (-1); } (void) fclose(bfp); if (bam_verbose) bam_print(_("updated boot signature backup file %s\n"), GRUBSIGN_BACKUP); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (0); } static int set_backup_ufs(char *osroot, char *sign) { const char *fcn = "set_backup_ufs()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, sign)); return (set_backup_common(osroot, sign)); } static int set_backup_zfs(char *osdev, char *sign) { char *pool; char *mntpt; zfs_mnted_t mnted; int ret; const char *fcn = "set_backup_zfs()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osdev, sign)); pool = get_pool(osdev); INJECT_ERROR1("SET_BACKUP_GET_POOL", pool = NULL); if (pool == NULL) { bam_error(_("failed to get pool name from %s\n"), osdev); return (-1); } mntpt = mount_top_dataset(pool, &mnted); INJECT_ERROR1("SET_BACKUP_MOUNT_DATASET", mntpt = NULL); if (mntpt == NULL) { bam_error(_("failed to mount top dataset for %s\n"), pool); free(pool); return (-1); } ret = set_backup_common(mntpt, sign); (void) umount_top_dataset(pool, mnted, mntpt); free(pool); INJECT_ERROR1("SET_BACKUP_ZFS_FAIL", ret = 1); if (ret == 0) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (ret); } static int set_backup(char *osroot, char *osdev, char *sign, char *fstype) { const char *fcn = "set_backup()"; int ret; INJECT_ERROR1("SET_BACKUP_FSTYPE", fstype = "foofs"); if (strcmp(fstype, "ufs") == 0) { BAM_DPRINTF(("%s: setting UFS backup sign\n", fcn)); ret = set_backup_ufs(osroot, sign); } else if (strcmp(fstype, "zfs") == 0) { BAM_DPRINTF(("%s: setting ZFS backup sign\n", fcn)); ret = set_backup_zfs(osdev, sign); } else { bam_error(_("boot signature not supported for fstype: %s\n"), fstype); ret = -1; } if (ret == 0) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (ret); } static int set_primary_common(char *mntpt, char *sign) { char signfile[PATH_MAX]; char signdir[PATH_MAX]; struct stat sb; int fd; int error; int ret; const char *fcn = "set_primary_common()"; (void) snprintf(signfile, sizeof (signfile), "%s/%s/%s", mntpt, GRUBSIGN_DIR, sign); if (stat(signfile, &sb) != -1) { if (bam_verbose) bam_print(_("primary sign %s exists\n"), sign); return (0); } else { BAM_DPRINTF(("%s: primary sign (%s) does not exist\n", fcn, signfile)); } (void) snprintf(signdir, sizeof (signdir), "%s/%s", mntpt, GRUBSIGN_DIR); if (stat(signdir, &sb) == -1) { BAM_DPRINTF(("%s: primary signdir (%s) does not exist\n", fcn, signdir)); ret = mkdirp(signdir, DIR_PERMS); error = errno; INJECT_ERROR1("SET_PRIMARY_MKDIRP", ret = -1); if (ret == -1) { bam_error(_("error creating boot signature " "directory %s: %s\n"), signdir, strerror(errno)); return (-1); } } fd = open(signfile, O_RDWR|O_CREAT|O_TRUNC, 0444); error = errno; INJECT_ERROR1("PRIMARY_SIGN_CREAT", fd = -1); if (fd == -1) { bam_error(_("error creating primary boot signature %s: %s\n"), signfile, strerror(error)); return (-1); } ret = fsync(fd); error = errno; INJECT_ERROR1("PRIMARY_FSYNC", ret = -1); if (ret != 0) { bam_error(_("error syncing primary boot signature %s: %s\n"), signfile, strerror(error)); } (void) close(fd); if (bam_verbose) bam_print(_("created primary GRUB boot signature: %s\n"), signfile); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (0); } static int set_primary_ufs(char *osroot, char *sign) { const char *fcn = "set_primary_ufs()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, sign)); return (set_primary_common(osroot, sign)); } static int set_primary_zfs(char *osdev, char *sign) { char *pool; char *mntpt; zfs_mnted_t mnted; int ret; const char *fcn = "set_primary_zfs()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osdev, sign)); pool = get_pool(osdev); INJECT_ERROR1("SET_PRIMARY_ZFS_GET_POOL", pool = NULL); if (pool == NULL) { bam_error(_("failed to get pool name from %s\n"), osdev); return (-1); } /* Pool name must exist in the sign */ ret = (strstr(sign, pool) != NULL); INJECT_ERROR1("SET_PRIMARY_ZFS_POOL_SIGN_INCOMPAT", ret = 0); if (ret == 0) { bam_error(_("pool name %s not present in signature %s\n"), pool, sign); free(pool); return (-1); } mntpt = mount_top_dataset(pool, &mnted); INJECT_ERROR1("SET_PRIMARY_ZFS_MOUNT_DATASET", mntpt = NULL); if (mntpt == NULL) { bam_error(_("failed to mount top dataset for %s\n"), pool); free(pool); return (-1); } ret = set_primary_common(mntpt, sign); (void) umount_top_dataset(pool, mnted, mntpt); free(pool); INJECT_ERROR1("SET_PRIMARY_ZFS_FAIL", ret = 1); if (ret == 0) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (ret); } static int set_primary(char *osroot, char *osdev, char *sign, char *fstype) { const char *fcn = "set_primary()"; int ret; INJECT_ERROR1("SET_PRIMARY_FSTYPE", fstype = "foofs"); if (strcmp(fstype, "ufs") == 0) { BAM_DPRINTF(("%s: setting UFS primary sign\n", fcn)); ret = set_primary_ufs(osroot, sign); } else if (strcmp(fstype, "zfs") == 0) { BAM_DPRINTF(("%s: setting ZFS primary sign\n", fcn)); ret = set_primary_zfs(osdev, sign); } else { bam_error(_("boot signature not supported for fstype: %s\n"), fstype); ret = -1; } if (ret == 0) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (ret); } static int ufs_add_to_sign_list(char *sign) { FILE *tfp; char signline[MAXNAMELEN]; char cmd[PATH_MAX]; int ret; int error; const char *fcn = "ufs_add_to_sign_list()"; INJECT_ERROR1("ADD_TO_SIGN_LIST_NOT_UFS", sign = "pool_rpool5"); if (strncmp(sign, GRUBSIGN_UFS_PREFIX, strlen(GRUBSIGN_UFS_PREFIX)) != 0) { bam_error(_("invalid UFS boot signature %s\n"), sign); (void) unlink(UFS_SIGNATURE_LIST); return (-1); } /* * most failures in this routine are not a fatal error * We simply unlink the /var/run file and continue */ ret = rename(UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST".tmp"); error = errno; INJECT_ERROR1("ADD_TO_SIGN_LIST_RENAME", ret = -1); if (ret == -1) { bam_error(_("rename to file failed: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST); return (0); } tfp = fopen(UFS_SIGNATURE_LIST".tmp", "a"); error = errno; INJECT_ERROR1("ADD_TO_SIGN_LIST_FOPEN", tfp = NULL); if (tfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (0); } (void) snprintf(signline, sizeof (signline), "%s\n", sign); ret = fputs(signline, tfp); error = errno; INJECT_ERROR1("ADD_TO_SIGN_LIST_FPUTS", ret = 0); if (ret != strlen(signline)) { bam_error(_("failed to write signature %s to signature " "list: %s\n"), sign, strerror(error)); (void) fclose(tfp); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (0); } ret = fclose(tfp); error = errno; INJECT_ERROR1("ADD_TO_SIGN_LIST_FCLOSE", ret = EOF); if (ret == EOF) { bam_error(_("failed to close file: %s: %s\n"), UFS_SIGNATURE_LIST".tmp", strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (0); } /* Sort the list again */ (void) snprintf(cmd, sizeof (cmd), "/bin/sort -u %s.tmp > %s.sorted", UFS_SIGNATURE_LIST, UFS_SIGNATURE_LIST); ret = exec_cmd(cmd, NULL); INJECT_ERROR1("ADD_TO_SIGN_LIST_SORT", ret = 1); if (ret != 0) { bam_error(_("error sorting GRUB UFS boot signatures\n")); (void) unlink(UFS_SIGNATURE_LIST".sorted"); (void) unlink(UFS_SIGNATURE_LIST".tmp"); return (0); } (void) unlink(UFS_SIGNATURE_LIST".tmp"); ret = rename(UFS_SIGNATURE_LIST".sorted", UFS_SIGNATURE_LIST); error = errno; INJECT_ERROR1("ADD_TO_SIGN_LIST_RENAME2", ret = -1); if (ret == -1) { bam_error(_("rename to file failed: %s: %s\n"), UFS_SIGNATURE_LIST, strerror(error)); (void) unlink(UFS_SIGNATURE_LIST".sorted"); return (0); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (0); } static int set_signature(char *osroot, char *osdev, char *sign, char *fstype) { int ret; const char *fcn = "set_signature()"; BAM_DPRINTF(("%s: entered. args: %s %s %s %s\n", fcn, osroot, osdev, sign, fstype)); ret = set_backup(osroot, osdev, sign, fstype); INJECT_ERROR1("SET_SIGNATURE_BACKUP", ret = -1); if (ret == -1) { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); bam_error(_("failed to set backup sign (%s) for %s: %s\n"), sign, osroot, osdev); return (-1); } ret = set_primary(osroot, osdev, sign, fstype); INJECT_ERROR1("SET_SIGNATURE_PRIMARY", ret = -1); if (ret == 0) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); bam_error(_("failed to set primary sign (%s) for %s: %s\n"), sign, osroot, osdev); } return (ret); } char * get_grubsign(char *osroot, char *osdev) { char *grubsign; /* (,#,#) */ char *slice; int fdiskpart; char *sign; char *fstype; int ret; const char *fcn = "get_grubsign()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, osdev)); fstype = get_fstype(osroot); INJECT_ERROR1("GET_GRUBSIGN_FSTYPE", fstype = NULL); if (fstype == NULL) { bam_error(_("failed to get fstype for %s\n"), osroot); return (NULL); } sign = find_existing_sign(osroot, osdev, fstype); INJECT_ERROR1("FIND_EXISTING_SIGN", sign = NULL); if (sign == NULL) { BAM_DPRINTF(("%s: no existing grubsign for %s: %s\n", fcn, osroot, osdev)); sign = create_new_sign(osdev, fstype); INJECT_ERROR1("CREATE_NEW_SIGN", sign = NULL); if (sign == NULL) { bam_error(_("failed to create GRUB boot signature for " "device: %s\n"), osdev); free(fstype); return (NULL); } } ret = set_signature(osroot, osdev, sign, fstype); INJECT_ERROR1("SET_SIGNATURE_FAIL", ret = -1); if (ret == -1) { bam_error(_("failed to write GRUB boot signature for " "device: %s\n"), osdev); free(sign); free(fstype); (void) unlink(UFS_SIGNATURE_LIST); return (NULL); } free(fstype); if (bam_verbose) bam_print(_("found or created GRUB signature %s for %s\n"), sign, osdev); fdiskpart = get_partition(osdev); INJECT_ERROR1("GET_GRUBSIGN_FDISK", fdiskpart = PARTNO_NOTFOUND); if (fdiskpart == PARTNO_NOTFOUND) { bam_error(_("failed to determine fdisk partition: %s\n"), osdev); free(sign); return (NULL); } slice = strrchr(osdev, 's'); if (fdiskpart == PARTNO_EFI) { fdiskpart = atoi(&slice[1]); slice = NULL; } grubsign = s_calloc(1, MAXNAMELEN + 10); if (slice) { (void) snprintf(grubsign, MAXNAMELEN + 10, "(%s,%d,%c)", sign, fdiskpart, slice[1] + 'a' - '0'); } else (void) snprintf(grubsign, MAXNAMELEN + 10, "(%s,%d)", sign, fdiskpart); free(sign); BAM_DPRINTF(("%s: successfully created grubsign %s\n", fcn, grubsign)); return (grubsign); } static char * get_title(char *rootdir) { static char title[80]; char *cp = NULL; char release[PATH_MAX]; FILE *fp; const char *fcn = "get_title()"; /* open the /etc/release file */ (void) snprintf(release, sizeof (release), "%s/etc/release", rootdir); fp = fopen(release, "r"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), release, strerror(errno)); cp = NULL; goto out; } /* grab first line of /etc/release */ cp = s_fgets(title, sizeof (title), fp); if (cp) { while (isspace(*cp)) /* remove leading spaces */ cp++; } (void) fclose(fp); out: cp = cp ? cp : "Oracle Solaris"; BAM_DPRINTF(("%s: got title: %s\n", fcn, cp)); return (cp); } char * get_special(char *mountp) { FILE *mntfp; struct mnttab mp = {0}; struct mnttab mpref = {0}; int error; int ret; const char *fcn = "get_special()"; INJECT_ERROR1("GET_SPECIAL_MNTPT", mountp = NULL); if (mountp == NULL) { bam_error(_("cannot get special file: NULL mount-point\n")); return (NULL); } mntfp = fopen(MNTTAB, "r"); error = errno; INJECT_ERROR1("GET_SPECIAL_MNTTAB_OPEN", mntfp = NULL); if (mntfp == NULL) { bam_error(_("failed to open file: %s: %s\n"), MNTTAB, strerror(error)); return (NULL); } if (*mountp == '\0') mpref.mnt_mountp = "/"; else mpref.mnt_mountp = mountp; ret = getmntany(mntfp, &mp, &mpref); INJECT_ERROR1("GET_SPECIAL_MNTTAB_SEARCH", ret = 1); if (ret != 0) { (void) fclose(mntfp); BAM_DPRINTF(("%s: Cannot get special file: mount-point %s " "not in mnttab\n", fcn, mountp)); return (NULL); } (void) fclose(mntfp); BAM_DPRINTF(("%s: returning special: %s\n", fcn, mp.mnt_special)); return (s_strdup(mp.mnt_special)); } static void free_physarray(char **physarray, int n) { int i; const char *fcn = "free_physarray()"; assert(physarray); assert(n); BAM_DPRINTF(("%s: entering args: %d\n", fcn, n)); for (i = 0; i < n; i++) { free(physarray[i]); } free(physarray); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } static int zfs_get_physical(char *special, char ***physarray, int *n) { char sdup[PATH_MAX]; char cmd[PATH_MAX]; char dsk[PATH_MAX]; char *pool; filelist_t flist = {0}; line_t *lp; line_t *startlp; char *comp1; int i; int ret; const char *fcn = "zfs_get_physical()"; assert(special); BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, special)); INJECT_ERROR1("INVALID_ZFS_SPECIAL", special = "/foo"); if (special[0] == '/') { bam_error(_("invalid device for ZFS filesystem: %s\n"), special); return (-1); } (void) strlcpy(sdup, special, sizeof (sdup)); pool = strtok(sdup, "/"); INJECT_ERROR1("ZFS_GET_PHYS_POOL", pool = NULL); if (pool == NULL) { bam_error(_("cannot derive ZFS pool from special: %s\n"), special); return (-1); } (void) snprintf(cmd, sizeof (cmd), "/sbin/zpool status %s", pool); ret = exec_cmd(cmd, &flist); INJECT_ERROR1("ZFS_GET_PHYS_STATUS", ret = 1); if (ret != 0) { bam_error(_("cannot get zpool status for pool: %s\n"), pool); return (-1); } INJECT_ERROR1("ZFS_GET_PHYS_STATUS_OUT", flist.head = NULL); if (flist.head == NULL) { bam_error(_("bad zpool status for pool=%s\n"), pool); filelist_free(&flist); return (-1); } for (lp = flist.head; lp; lp = lp->next) { BAM_DPRINTF(("%s: strtok() zpool status line=%s\n", fcn, lp->line)); comp1 = strtok(lp->line, " \t"); if (comp1 == NULL) { free(lp->line); lp->line = NULL; } else { comp1 = s_strdup(comp1); free(lp->line); lp->line = comp1; } } for (lp = flist.head; lp; lp = lp->next) { if (lp->line == NULL) continue; if (strcmp(lp->line, pool) == 0) { BAM_DPRINTF(("%s: found pool name: %s in zpool " "status\n", fcn, pool)); break; } } if (lp == NULL) { bam_error(_("no pool name %s in zpool status\n"), pool); filelist_free(&flist); return (-1); } startlp = lp->next; for (i = 0, lp = startlp; lp; lp = lp->next) { if (lp->line == NULL) continue; if (strcmp(lp->line, "mirror") == 0) continue; if (lp->line[0] == '\0' || strcmp(lp->line, "errors:") == 0) break; i++; BAM_DPRINTF(("%s: counting phys slices in zpool status: %d\n", fcn, i)); } if (i == 0) { bam_error(_("no physical device in zpool status for pool=%s\n"), pool); filelist_free(&flist); return (-1); } *n = i; *physarray = s_calloc(*n, sizeof (char *)); for (i = 0, lp = startlp; lp; lp = lp->next) { if (lp->line == NULL) continue; if (strcmp(lp->line, "mirror") == 0) continue; if (strcmp(lp->line, "errors:") == 0) break; if (strncmp(lp->line, "/dev/dsk/", strlen("/dev/dsk/")) != 0 && strncmp(lp->line, "/dev/rdsk/", strlen("/dev/rdsk/")) != 0) { (void) snprintf(dsk, sizeof (dsk), "/dev/rdsk/%s", lp->line); } else { (void) strlcpy(dsk, lp->line, sizeof (dsk)); } BAM_DPRINTF(("%s: adding phys slice=%s from pool %s status\n", fcn, dsk, pool)); (*physarray)[i++] = s_strdup(dsk); } assert(i == *n); filelist_free(&flist); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (0); } static int get_physical(char *menu_root, char ***physarray, int *n) { char *special; int ret; const char *fcn = "get_physical()"; assert(menu_root); assert(physarray); assert(n); *physarray = NULL; *n = 0; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, menu_root)); /* First get the device special file from /etc/mnttab */ special = get_special(menu_root); INJECT_ERROR1("GET_PHYSICAL_SPECIAL", special = NULL); if (special == NULL) { bam_error(_("cannot get special file for mount-point: %s\n"), menu_root); return (-1); } /* If already a physical device nothing to do */ if (strncmp(special, "/dev/dsk/", strlen("/dev/dsk/")) == 0 || strncmp(special, "/dev/rdsk/", strlen("/dev/rdsk/")) == 0) { BAM_DPRINTF(("%s: got physical device already directly for " "menu_root=%s special=%s\n", fcn, menu_root, special)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); *physarray = s_calloc(1, sizeof (char *)); (*physarray)[0] = special; *n = 1; return (0); } if (is_zfs(menu_root)) { ret = zfs_get_physical(special, physarray, n); } else { bam_error(_("cannot derive physical device for %s (%s), " "unsupported filesystem\n"), menu_root, special); ret = -1; } free(special); INJECT_ERROR1("GET_PHYSICAL_RET", ret = -1); if (ret == -1) { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } else { int i; assert (*n > 0); for (i = 0; i < *n; i++) { BAM_DPRINTF(("%s: returning physical=%s\n", fcn, (*physarray)[i])); } } return (ret); } static int is_bootdisk(char *osroot, char *physical) { int ret; char *grubroot; char *bootp; const char *fcn = "is_bootdisk()"; assert(osroot); assert(physical); BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, physical)); bootp = strstr(physical, "p0:boot"); if (bootp) *bootp = '\0'; /* * We just want the BIOS mapping for menu disk. * Don't pass menu_root to get_grubroot() as the * check that it is used for is not relevant here. * The osroot is immaterial as well - it is only used to * to find create_diskmap script. Everything hinges on * "physical" */ grubroot = get_grubroot(osroot, physical, NULL); INJECT_ERROR1("IS_BOOTDISK_GRUBROOT", grubroot = NULL); if (grubroot == NULL) { if (bam_verbose) bam_error(_("cannot determine BIOS disk ID 'hd?' for " "disk: %s\n"), physical); return (0); } ret = grubroot[3] == '0'; free(grubroot); BAM_DPRINTF(("%s: returning ret = %d\n", fcn, ret)); return (ret); } /* * Check if menu is on the boot device * Return 0 (false) on error */ static int menu_on_bootdisk(char *osroot, char *menu_root) { char **physarray; int ret; int n; int i; int on_bootdisk; const char *fcn = "menu_on_bootdisk()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, menu_root)); ret = get_physical(menu_root, &physarray, &n); INJECT_ERROR1("MENU_ON_BOOTDISK_PHYSICAL", ret = -1); if (ret != 0) { bam_error(_("cannot get physical device special file for menu " "root: %s\n"), menu_root); return (0); } assert(physarray); assert(n > 0); on_bootdisk = 0; for (i = 0; i < n; i++) { assert(strncmp(physarray[i], "/dev/dsk/", strlen("/dev/dsk/")) == 0 || strncmp(physarray[i], "/dev/rdsk/", strlen("/dev/rdsk/")) == 0); BAM_DPRINTF(("%s: checking if phys-device=%s is on bootdisk\n", fcn, physarray[i])); if (is_bootdisk(osroot, physarray[i])) { on_bootdisk = 1; BAM_DPRINTF(("%s: phys-device=%s *IS* on bootdisk\n", fcn, physarray[i])); } } free_physarray(physarray, n); INJECT_ERROR1("ON_BOOTDISK_YES", on_bootdisk = 1); INJECT_ERROR1("ON_BOOTDISK_NO", on_bootdisk = 0); if (on_bootdisk) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (on_bootdisk); } void bam_add_line(menu_t *mp, entry_t *entry, line_t *prev, line_t *lp) { const char *fcn = "bam_add_line()"; assert(mp); assert(entry); assert(prev); assert(lp); lp->next = prev->next; if (prev->next) { BAM_DPRINTF(("%s: previous next exists\n", fcn)); prev->next->prev = lp; } else { BAM_DPRINTF(("%s: previous next does not exist\n", fcn)); } prev->next = lp; lp->prev = prev; if (entry->end == prev) { BAM_DPRINTF(("%s: last line in entry\n", fcn)); entry->end = lp; } if (mp->end == prev) { assert(lp->next == NULL); mp->end = lp; BAM_DPRINTF(("%s: last line in menu\n", fcn)); } } /* * look for matching bootadm entry with specified parameters * Here are the rules (based on existing usage): * - If title is specified, match on title only * - Else, match on root/findroot, kernel, and module. * Note that, if root_opt is non-zero, the absence of * root line is considered a match. */ static entry_t * find_boot_entry( menu_t *mp, char *title, char *kernel, char *findroot, char *root, char *module, int root_opt, int *entry_num) { int i; line_t *lp; entry_t *ent; const char *fcn = "find_boot_entry()"; if (entry_num) *entry_num = BAM_ERROR; /* find matching entry */ for (i = 0, ent = mp->entries; ent; i++, ent = ent->next) { lp = ent->start; /* first line of entry must be bootadm comment */ lp = ent->start; if (lp->flags != BAM_COMMENT || strcmp(lp->arg, BAM_BOOTADM_HDR) != 0) { continue; } /* advance to title line */ lp = lp->next; if (title) { if (lp->flags == BAM_TITLE && lp->arg && strcmp(lp->arg, title) == 0) { BAM_DPRINTF(("%s: matched title: %s\n", fcn, title)); break; } BAM_DPRINTF(("%s: no match title: %s, %s\n", fcn, title, lp->arg)); continue; /* check title only */ } lp = lp->next; /* advance to root line */ if (lp == NULL) { continue; } else if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[FINDROOT_CMD]) == 0) { INJECT_ERROR1("FIND_BOOT_ENTRY_NULL_FINDROOT", findroot = NULL); if (findroot == NULL) { BAM_DPRINTF(("%s: no match line has findroot, " "we don't: %s\n", fcn, lp->arg)); continue; } /* findroot command found, try match */ if (strcmp(lp->arg, findroot) != 0) { BAM_DPRINTF(("%s: no match findroot: %s, %s\n", fcn, findroot, lp->arg)); continue; } BAM_DPRINTF(("%s: matched findroot: %s\n", fcn, findroot)); lp = lp->next; /* advance to kernel line */ } else if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[ROOT_CMD]) == 0) { INJECT_ERROR1("FIND_BOOT_ENTRY_NULL_ROOT", root = NULL); if (root == NULL) { BAM_DPRINTF(("%s: no match, line has root, we " "don't: %s\n", fcn, lp->arg)); continue; } /* root cmd found, try match */ if (strcmp(lp->arg, root) != 0) { BAM_DPRINTF(("%s: no match root: %s, %s\n", fcn, root, lp->arg)); continue; } BAM_DPRINTF(("%s: matched root: %s\n", fcn, root)); lp = lp->next; /* advance to kernel line */ } else { INJECT_ERROR1("FIND_BOOT_ENTRY_ROOT_OPT_NO", root_opt = 0); INJECT_ERROR1("FIND_BOOT_ENTRY_ROOT_OPT_YES", root_opt = 1); /* no root command, see if root is optional */ if (root_opt == 0) { BAM_DPRINTF(("%s: root NOT optional\n", fcn)); continue; } BAM_DPRINTF(("%s: root IS optional\n", fcn)); } if (lp == NULL || lp->next == NULL) { continue; } if (kernel && (!check_cmd(lp->cmd, KERNEL_CMD, lp->arg, kernel))) { if (!(ent->flags & BAM_ENTRY_FAILSAFE) || !(ent->flags & BAM_ENTRY_DBOOT) || strcmp(kernel, DIRECT_BOOT_FAILSAFE_LINE) != 0) continue; ent->flags |= BAM_ENTRY_UPGFSKERNEL; } BAM_DPRINTF(("%s: kernel match: %s, %s\n", fcn, kernel, lp->arg)); /* * Check for matching module entry (failsafe or normal). * If it fails to match, we go around the loop again. * For xpv entries, there are two module lines, so we * do the check twice. */ lp = lp->next; /* advance to module line */ if (check_cmd(lp->cmd, MODULE_CMD, lp->arg, module) || (((lp = lp->next) != NULL) && check_cmd(lp->cmd, MODULE_CMD, lp->arg, module))) { /* match found */ BAM_DPRINTF(("%s: module match: %s, %s\n", fcn, module, lp->arg)); break; } if (strcmp(module, FAILSAFE_ARCHIVE) == 0 && (strcmp(lp->prev->arg, FAILSAFE_ARCHIVE_32) == 0 || strcmp(lp->prev->arg, FAILSAFE_ARCHIVE_64) == 0)) { ent->flags |= BAM_ENTRY_UPGFSMODULE; break; } } if (ent && entry_num) { *entry_num = i; } if (ent) { BAM_DPRINTF(("%s: returning ret = %d\n", fcn, i)); } else { BAM_DPRINTF(("%s: returning ret = %d\n", fcn, BAM_ERROR)); } return (ent); } static int update_boot_entry(menu_t *mp, char *title, char *findroot, char *root, char *kernel, char *mod_kernel, char *module, int root_opt) { int i; int change_kernel = 0; entry_t *ent; line_t *lp; line_t *tlp; char linebuf[BAM_MAXLINE]; const char *fcn = "update_boot_entry()"; /* note: don't match on title, it's updated on upgrade */ ent = find_boot_entry(mp, NULL, kernel, findroot, root, module, root_opt, &i); if ((ent == NULL) && (bam_direct == BAM_DIRECT_DBOOT)) { /* * We may be upgrading a kernel from multiboot to * directboot. Look for a multiboot entry. A multiboot * entry will not have a findroot line. */ ent = find_boot_entry(mp, NULL, "multiboot", NULL, root, MULTIBOOT_ARCHIVE, root_opt, &i); if (ent != NULL) { BAM_DPRINTF(("%s: upgrading entry from dboot to " "multiboot: root = %s\n", fcn, root)); change_kernel = 1; } } else if (ent) { BAM_DPRINTF(("%s: found entry with matching findroot: %s\n", fcn, findroot)); } if (ent == NULL) { BAM_DPRINTF(("%s: boot entry not found in menu. Creating " "new entry, findroot = %s\n", fcn, findroot)); return (add_boot_entry(mp, title, findroot, kernel, mod_kernel, module, NULL)); } /* replace title of existing entry and update findroot line */ lp = ent->start; lp = lp->next; /* title line */ (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[TITLE_CMD], menu_cmds[SEP_CMD], title); free(lp->arg); free(lp->line); lp->arg = s_strdup(title); lp->line = s_strdup(linebuf); BAM_DPRINTF(("%s: changing title to: %s\n", fcn, title)); tlp = lp; /* title line */ lp = lp->next; /* root line */ /* if no root or findroot command, create a new line_t */ if ((lp->cmd != NULL) && (strcmp(lp->cmd, menu_cmds[ROOT_CMD]) != 0 && strcmp(lp->cmd, menu_cmds[FINDROOT_CMD]) != 0)) { lp = s_calloc(1, sizeof (line_t)); bam_add_line(mp, ent, tlp, lp); } else { if (lp->cmd != NULL) free(lp->cmd); free(lp->sep); free(lp->arg); free(lp->line); } lp->cmd = s_strdup(menu_cmds[FINDROOT_CMD]); lp->sep = s_strdup(menu_cmds[SEP_CMD]); lp->arg = s_strdup(findroot); (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[FINDROOT_CMD], menu_cmds[SEP_CMD], findroot); lp->line = s_strdup(linebuf); BAM_DPRINTF(("%s: adding findroot line: %s\n", fcn, findroot)); /* kernel line */ lp = lp->next; if (ent->flags & BAM_ENTRY_UPGFSKERNEL) { char *params = NULL; params = strstr(lp->line, "-s"); if (params != NULL) (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s%s", menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD], kernel, params+2); else (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD], kernel); if (lp->cmd != NULL) free(lp->cmd); free(lp->arg); free(lp->line); lp->cmd = s_strdup(menu_cmds[KERNEL_DOLLAR_CMD]); lp->arg = s_strdup(strstr(linebuf, "/")); lp->line = s_strdup(linebuf); ent->flags &= ~BAM_ENTRY_UPGFSKERNEL; BAM_DPRINTF(("%s: adding new kernel$ line: %s\n", fcn, lp->prev->cmd)); } if (change_kernel) { /* * We're upgrading from multiboot to directboot. */ if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[KERNEL_CMD]) == 0) { (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[KERNEL_DOLLAR_CMD], menu_cmds[SEP_CMD], kernel); free(lp->cmd); free(lp->arg); free(lp->line); lp->cmd = s_strdup(menu_cmds[KERNEL_DOLLAR_CMD]); lp->arg = s_strdup(kernel); lp->line = s_strdup(linebuf); lp = lp->next; BAM_DPRINTF(("%s: adding new kernel$ line: %s\n", fcn, kernel)); } if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[MODULE_CMD]) == 0) { (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[MODULE_DOLLAR_CMD], menu_cmds[SEP_CMD], module); free(lp->cmd); free(lp->arg); free(lp->line); lp->cmd = s_strdup(menu_cmds[MODULE_DOLLAR_CMD]); lp->arg = s_strdup(module); lp->line = s_strdup(linebuf); lp = lp->next; BAM_DPRINTF(("%s: adding new module$ line: %s\n", fcn, module)); } } /* module line */ lp = lp->next; if (ent->flags & BAM_ENTRY_UPGFSMODULE) { if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[MODULE_CMD]) == 0) { (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", menu_cmds[MODULE_DOLLAR_CMD], menu_cmds[SEP_CMD], module); free(lp->cmd); free(lp->arg); free(lp->line); lp->cmd = s_strdup(menu_cmds[MODULE_DOLLAR_CMD]); lp->arg = s_strdup(module); lp->line = s_strdup(linebuf); lp = lp->next; ent->flags &= ~BAM_ENTRY_UPGFSMODULE; BAM_DPRINTF(("%s: adding new module$ line: %s\n", fcn, module)); } } BAM_DPRINTF(("%s: returning ret = %d\n", fcn, i)); return (i); } int root_optional(char *osroot, char *menu_root) { char *ospecial; char *mspecial; char *slash; int root_opt; int ret1; int ret2; const char *fcn = "root_optional()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, menu_root)); /* * For all filesystems except ZFS, a straight compare of osroot * and menu_root will tell us if root is optional. * For ZFS, the situation is complicated by the fact that * menu_root and osroot are always different */ ret1 = is_zfs(osroot); ret2 = is_zfs(menu_root); INJECT_ERROR1("ROOT_OPT_NOT_ZFS", ret1 = 0); if (!ret1 || !ret2) { BAM_DPRINTF(("%s: one or more non-ZFS filesystems (%s, %s)\n", fcn, osroot, menu_root)); root_opt = (strcmp(osroot, menu_root) == 0); goto out; } ospecial = get_special(osroot); INJECT_ERROR1("ROOT_OPTIONAL_OSPECIAL", ospecial = NULL); if (ospecial == NULL) { bam_error(_("failed to get special file for osroot: %s\n"), osroot); return (0); } BAM_DPRINTF(("%s: ospecial=%s for osroot=%s\n", fcn, ospecial, osroot)); mspecial = get_special(menu_root); INJECT_ERROR1("ROOT_OPTIONAL_MSPECIAL", mspecial = NULL); if (mspecial == NULL) { bam_error(_("failed to get special file for menu_root: %s\n"), menu_root); free(ospecial); return (0); } BAM_DPRINTF(("%s: mspecial=%s for menu_root=%s\n", fcn, mspecial, menu_root)); slash = strchr(ospecial, '/'); if (slash) *slash = '\0'; BAM_DPRINTF(("%s: FIXED ospecial=%s for osroot=%s\n", fcn, ospecial, osroot)); root_opt = (strcmp(ospecial, mspecial) == 0); free(ospecial); free(mspecial); out: INJECT_ERROR1("ROOT_OPTIONAL_NO", root_opt = 0); INJECT_ERROR1("ROOT_OPTIONAL_YES", root_opt = 1); if (root_opt) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (root_opt); } /*ARGSUSED*/ static error_t update_entry(menu_t *mp, char *menu_root, char *osdev) { int entry; char *grubsign; char *grubroot; char *title; char osroot[PATH_MAX]; char *failsafe_kernel = NULL; struct stat sbuf; char failsafe[256]; char failsafe_64[256]; int ret; const char *fcn = "update_entry()"; assert(mp); assert(menu_root); assert(osdev); assert(bam_root); BAM_DPRINTF(("%s: entered. args: %s %s %s\n", fcn, menu_root, osdev, bam_root)); (void) strlcpy(osroot, bam_root, sizeof (osroot)); title = get_title(osroot); assert(title); grubsign = get_grubsign(osroot, osdev); INJECT_ERROR1("GET_GRUBSIGN_FAIL", grubsign = NULL); if (grubsign == NULL) { bam_error(_("failed to get grubsign for root: %s, device %s\n"), osroot, osdev); return (BAM_ERROR); } /* * It is not a fatal error if get_grubroot() fails * We no longer rely on biosdev to populate the * menu */ grubroot = get_grubroot(osroot, osdev, menu_root); INJECT_ERROR1("GET_GRUBROOT_FAIL", grubroot = NULL); if (grubroot) { BAM_DPRINTF(("%s: get_grubroot success. osroot=%s, osdev=%s, " "menu_root=%s\n", fcn, osroot, osdev, menu_root)); } else { BAM_DPRINTF(("%s: get_grubroot failed. osroot=%s, osdev=%s, " "menu_root=%s\n", fcn, osroot, osdev, menu_root)); } /* add the entry for normal Solaris */ INJECT_ERROR1("UPDATE_ENTRY_MULTIBOOT", bam_direct = BAM_DIRECT_MULTIBOOT); if (bam_direct == BAM_DIRECT_DBOOT) { entry = update_boot_entry(mp, title, grubsign, grubroot, (bam_zfs ? DIRECT_BOOT_KERNEL_ZFS : DIRECT_BOOT_KERNEL), NULL, DIRECT_BOOT_ARCHIVE, root_optional(osroot, menu_root)); BAM_DPRINTF(("%s: updated boot entry bam_zfs=%d, " "grubsign = %s\n", fcn, bam_zfs, grubsign)); if ((entry != BAM_ERROR) && (bam_is_hv == BAM_HV_PRESENT)) { (void) update_boot_entry(mp, NEW_HV_ENTRY, grubsign, grubroot, XEN_MENU, bam_zfs ? XEN_KERNEL_MODULE_LINE_ZFS : XEN_KERNEL_MODULE_LINE, DIRECT_BOOT_ARCHIVE, root_optional(osroot, menu_root)); BAM_DPRINTF(("%s: updated HV entry bam_zfs=%d, " "grubsign = %s\n", fcn, bam_zfs, grubsign)); } } else { entry = update_boot_entry(mp, title, grubsign, grubroot, MULTI_BOOT, NULL, MULTIBOOT_ARCHIVE, root_optional(osroot, menu_root)); BAM_DPRINTF(("%s: updated MULTIBOOT entry grubsign = %s\n", fcn, grubsign)); } /* * Add the entry for failsafe archive. On a bfu'd system, the * failsafe may be different than the installed kernel. */ (void) snprintf(failsafe, sizeof (failsafe), "%s%s", osroot, FAILSAFE_ARCHIVE_32); (void) snprintf(failsafe_64, sizeof (failsafe_64), "%s%s", osroot, FAILSAFE_ARCHIVE_64); /* * Check if at least one of the two archives exists * Using $ISADIR as the default line, we have an entry which works * for both the cases. */ if (stat(failsafe, &sbuf) == 0 || stat(failsafe_64, &sbuf) == 0) { /* Figure out where the kernel line should point */ (void) snprintf(failsafe, sizeof (failsafe), "%s%s", osroot, DIRECT_BOOT_FAILSAFE_32); (void) snprintf(failsafe_64, sizeof (failsafe_64), "%s%s", osroot, DIRECT_BOOT_FAILSAFE_64); if (stat(failsafe, &sbuf) == 0 || stat(failsafe_64, &sbuf) == 0) { failsafe_kernel = DIRECT_BOOT_FAILSAFE_LINE; } else { (void) snprintf(failsafe, sizeof (failsafe), "%s%s", osroot, MULTI_BOOT_FAILSAFE); if (stat(failsafe, &sbuf) == 0) { failsafe_kernel = MULTI_BOOT_FAILSAFE_LINE; } } if (failsafe_kernel != NULL) { (void) update_boot_entry(mp, FAILSAFE_TITLE, grubsign, grubroot, failsafe_kernel, NULL, FAILSAFE_ARCHIVE, root_optional(osroot, menu_root)); BAM_DPRINTF(("%s: updated FAILSAFE entry " "failsafe_kernel = %s\n", fcn, failsafe_kernel)); } } free(grubroot); INJECT_ERROR1("UPDATE_ENTRY_ERROR", entry = BAM_ERROR); if (entry == BAM_ERROR) { bam_error(_("failed to add boot entry with title=%s, grub " "signature=%s\n"), title, grubsign); free(grubsign); return (BAM_ERROR); } free(grubsign); update_numbering(mp); ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry); INJECT_ERROR1("SET_DEFAULT_ERROR", ret = BAM_ERROR); if (ret == BAM_ERROR) { bam_error(_("failed to set GRUB menu default to %d\n"), entry); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_WRITE); } static void save_default_entry(menu_t *mp, const char *which) { int lineNum; int entryNum; int entry = 0; /* default is 0 */ char linebuf[BAM_MAXLINE]; line_t *lp = mp->curdefault; const char *fcn = "save_default_entry()"; if (mp->start) { lineNum = mp->end->lineNum; entryNum = mp->end->entryNum; } else { lineNum = LINE_INIT; entryNum = ENTRY_INIT; } if (lp) entry = s_strtol(lp->arg); (void) snprintf(linebuf, sizeof (linebuf), "#%s%d", which, entry); BAM_DPRINTF(("%s: saving default to: %s\n", fcn, linebuf)); line_parser(mp, linebuf, &lineNum, &entryNum); BAM_DPRINTF(("%s: saved default to lineNum=%d, entryNum=%d\n", fcn, lineNum, entryNum)); } static void restore_default_entry(menu_t *mp, const char *which, line_t *lp) { int entry; char *str; const char *fcn = "restore_default_entry()"; if (lp == NULL) { BAM_DPRINTF(("%s: NULL saved default\n", fcn)); return; /* nothing to restore */ } BAM_DPRINTF(("%s: saved default string: %s\n", fcn, which)); str = lp->arg + strlen(which); entry = s_strtol(str); (void) set_global(mp, menu_cmds[DEFAULT_CMD], entry); BAM_DPRINTF(("%s: restored default to entryNum: %d\n", fcn, entry)); /* delete saved old default line */ unlink_line(mp, lp); line_free(lp); } /* * This function is for supporting reboot with args. * The opt value can be: * NULL delete temp entry, if present * entry= switches default entry to * else treated as boot-args and setup a temperary menu entry * and make it the default * Note that we are always rebooting the current OS instance * so osroot == / always. */ #define REBOOT_TITLE "Solaris_reboot_transient" /*ARGSUSED*/ static error_t update_temp(menu_t *mp, char *dummy, char *opt) { int entry; char *osdev; char *fstype; char *sign; char *opt_ptr; char *path; char kernbuf[BUFSIZ]; char args_buf[BUFSIZ]; char signbuf[PATH_MAX]; int ret; const char *fcn = "update_temp()"; assert(mp); assert(dummy == NULL); /* opt can be NULL */ BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, opt ? opt : "")); BAM_DPRINTF(("%s: bam_alt_root: %d, bam_root: %s\n", fcn, bam_alt_root, bam_root)); if (bam_alt_root || bam_rootlen != 1 || strcmp(bam_root, "/") != 0 || strcmp(rootbuf, "/") != 0) { bam_error(_("an alternate root (%s) cannot be used with this " "sub-command\n"), bam_root); return (BAM_ERROR); } /* If no option, delete exiting reboot menu entry */ if (opt == NULL) { entry_t *ent; BAM_DPRINTF(("%s: opt is NULL\n", fcn)); ent = find_boot_entry(mp, REBOOT_TITLE, NULL, NULL, NULL, NULL, 0, &entry); if (ent == NULL) { /* not found is ok */ BAM_DPRINTF(("%s: transient entry not found\n", fcn)); return (BAM_SUCCESS); } (void) delete_boot_entry(mp, entry, DBE_PRINTERR); restore_default_entry(mp, BAM_OLDDEF, mp->olddefault); mp->olddefault = NULL; BAM_DPRINTF(("%s: restored old default\n", fcn)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_WRITE); } /* if entry= is specified, set the default entry */ if (strncmp(opt, "entry=", strlen("entry=")) == 0) { int entryNum = s_strtol(opt + strlen("entry=")); BAM_DPRINTF(("%s: opt has entry=: %s\n", fcn, opt)); if (selector(mp, opt, &entry, NULL) == BAM_SUCCESS) { /* this is entry=# option */ ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry); BAM_DPRINTF(("%s: default set to %d, " "set_default ret=%d\n", fcn, entry, ret)); return (ret); } else { bam_error(_("failed to set GRUB menu default to %d\n"), entryNum); return (BAM_ERROR); } } /* * add a new menu entry based on opt and make it the default */ fstype = get_fstype("/"); INJECT_ERROR1("REBOOT_FSTYPE_NULL", fstype = NULL); if (fstype == NULL) { bam_error(_("failed to determine filesystem type for \"/\". " "Reboot with \narguments failed.\n")); return (BAM_ERROR); } osdev = get_special("/"); INJECT_ERROR1("REBOOT_SPECIAL_NULL", osdev = NULL); if (osdev == NULL) { free(fstype); bam_error(_("failed to find device special file for \"/\". " "Reboot with \narguments failed.\n")); return (BAM_ERROR); } sign = find_existing_sign("/", osdev, fstype); INJECT_ERROR1("REBOOT_SIGN_NULL", sign = NULL); if (sign == NULL) { free(fstype); free(osdev); bam_error(_("failed to find boot signature. Reboot with " "arguments failed.\n")); return (BAM_ERROR); } free(osdev); (void) strlcpy(signbuf, sign, sizeof (signbuf)); free(sign); assert(strchr(signbuf, '(') == NULL && strchr(signbuf, ',') == NULL && strchr(signbuf, ')') == NULL); /* * There is no alternate root while doing reboot with args * This version of bootadm is only delivered with a DBOOT * version of Solaris. */ INJECT_ERROR1("REBOOT_NOT_DBOOT", bam_direct = BAM_DIRECT_MULTIBOOT); if (bam_direct != BAM_DIRECT_DBOOT) { free(fstype); bam_error(_("the root filesystem is not a dboot Solaris " "instance. \nThis version of bootadm is not supported " "on this version of Solaris.\n")); return (BAM_ERROR); } /* add an entry for Solaris reboot */ if (opt[0] == '-') { /* It's an option - first see if boot-file is set */ ret = get_kernel(mp, KERNEL_CMD, kernbuf, sizeof (kernbuf)); INJECT_ERROR1("REBOOT_GET_KERNEL", ret = BAM_ERROR); if (ret != BAM_SUCCESS) { free(fstype); bam_error(_("reboot with arguments: error querying " "current boot-file settings\n")); return (BAM_ERROR); } if (kernbuf[0] == '\0') (void) strlcpy(kernbuf, DIRECT_BOOT_KERNEL, sizeof (kernbuf)); /* * If this is a zfs file system and kernbuf does not * have "-B $ZFS-BOOTFS" string yet, add it. */ if (strcmp(fstype, "zfs") == 0 && !strstr(kernbuf, ZFS_BOOT)) { (void) strlcat(kernbuf, " ", sizeof (kernbuf)); (void) strlcat(kernbuf, ZFS_BOOT, sizeof (kernbuf)); } (void) strlcat(kernbuf, " ", sizeof (kernbuf)); (void) strlcat(kernbuf, opt, sizeof (kernbuf)); BAM_DPRINTF(("%s: reboot with args, option specified: " "kern=%s\n", fcn, kernbuf)); } else if (opt[0] == '/') { /* It's a full path, so write it out. */ (void) strlcpy(kernbuf, opt, sizeof (kernbuf)); /* * If someone runs: * * # eeprom boot-args='-kd' * # reboot /platform/i86pc/kernel/unix * * we want to use the boot-args as part of the boot * line. On the other hand, if someone runs: * * # reboot "/platform/i86pc/kernel/unix -kd" * * we don't need to mess with boot-args. If there's * no space in the options string, assume we're in the * first case. */ if (strchr(opt, ' ') == NULL) { ret = get_kernel(mp, ARGS_CMD, args_buf, sizeof (args_buf)); INJECT_ERROR1("REBOOT_GET_ARGS", ret = BAM_ERROR); if (ret != BAM_SUCCESS) { free(fstype); bam_error(_("reboot with arguments: error " "querying current boot-args settings\n")); return (BAM_ERROR); } if (args_buf[0] != '\0') { (void) strlcat(kernbuf, " ", sizeof (kernbuf)); (void) strlcat(kernbuf, args_buf, sizeof (kernbuf)); } } BAM_DPRINTF(("%s: reboot with args, abspath specified: " "kern=%s\n", fcn, kernbuf)); } else { /* * It may be a partial path, or it may be a partial * path followed by options. Assume that only options * follow a space. If someone sends us a kernel path * that includes a space, they deserve to be broken. */ opt_ptr = strchr(opt, ' '); if (opt_ptr != NULL) { *opt_ptr = '\0'; } path = expand_path(opt); if (path != NULL) { (void) strlcpy(kernbuf, path, sizeof (kernbuf)); free(path); /* * If there were options given, use those. * Otherwise, copy over the default options. */ if (opt_ptr != NULL) { /* Restore the space in opt string */ *opt_ptr = ' '; (void) strlcat(kernbuf, opt_ptr, sizeof (kernbuf)); } else { ret = get_kernel(mp, ARGS_CMD, args_buf, sizeof (args_buf)); INJECT_ERROR1("UPDATE_TEMP_PARTIAL_ARGS", ret = BAM_ERROR); if (ret != BAM_SUCCESS) { free(fstype); bam_error(_("reboot with arguments: " "error querying current boot-args " "settings\n")); return (BAM_ERROR); } if (args_buf[0] != '\0') { (void) strlcat(kernbuf, " ", sizeof (kernbuf)); (void) strlcat(kernbuf, args_buf, sizeof (kernbuf)); } } BAM_DPRINTF(("%s: resolved partial path: %s\n", fcn, kernbuf)); } else { free(fstype); bam_error(_("unable to expand %s to a full file" " path.\n"), opt); bam_print_stderr(_("Rebooting with default kernel " "and options.\n")); return (BAM_ERROR); } } free(fstype); entry = add_boot_entry(mp, REBOOT_TITLE, signbuf, kernbuf, NULL, NULL, NULL); INJECT_ERROR1("REBOOT_ADD_BOOT_ENTRY", entry = BAM_ERROR); if (entry == BAM_ERROR) { bam_error(_("Cannot update menu. Cannot reboot with " "requested arguments\n")); return (BAM_ERROR); } save_default_entry(mp, BAM_OLDDEF); ret = set_global(mp, menu_cmds[DEFAULT_CMD], entry); INJECT_ERROR1("REBOOT_SET_GLOBAL", ret = BAM_ERROR); if (ret == BAM_ERROR) { bam_error(_("reboot with arguments: setting GRUB menu default " "to %d failed\n"), entry); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_WRITE); } error_t set_global(menu_t *mp, char *globalcmd, int val) { line_t *lp; line_t *found; line_t *last; char *cp; char *str; char prefix[BAM_MAXLINE]; size_t len; const char *fcn = "set_global()"; assert(mp); assert(globalcmd); if (strcmp(globalcmd, menu_cmds[DEFAULT_CMD]) == 0) { INJECT_ERROR1("SET_GLOBAL_VAL_NEG", val = -1); INJECT_ERROR1("SET_GLOBAL_MENU_EMPTY", mp->end = NULL); INJECT_ERROR1("SET_GLOBAL_VAL_TOO_BIG", val = 100); if (val < 0 || mp->end == NULL || val > mp->end->entryNum) { (void) snprintf(prefix, sizeof (prefix), "%d", val); bam_error(_("invalid boot entry number: %s\n"), prefix); return (BAM_ERROR); } } found = last = NULL; for (lp = mp->start; lp; lp = lp->next) { if (lp->flags != BAM_GLOBAL) continue; last = lp; /* track the last global found */ INJECT_ERROR1("SET_GLOBAL_NULL_CMD", lp->cmd = NULL); if (lp->cmd == NULL) { bam_error(_("no command at line %d\n"), lp->lineNum); continue; } if (strcmp(globalcmd, lp->cmd) != 0) continue; BAM_DPRINTF(("%s: found matching global command: %s\n", fcn, globalcmd)); if (found) { bam_error(_("duplicate command %s at line %d of " "%sboot/grub/menu.lst\n"), globalcmd, lp->lineNum, bam_root); } found = lp; } if (found == NULL) { lp = s_calloc(1, sizeof (line_t)); if (last == NULL) { lp->next = mp->start; mp->start = lp; mp->end = (mp->end) ? mp->end : lp; } else { lp->next = last->next; last->next = lp; if (lp->next == NULL) mp->end = lp; } lp->flags = BAM_GLOBAL; /* other fields not needed for writes */ len = strlen(globalcmd) + strlen(menu_cmds[SEP_CMD]); len += 10; /* val < 10 digits */ lp->line = s_calloc(1, len); (void) snprintf(lp->line, len, "%s%s%d", globalcmd, menu_cmds[SEP_CMD], val); BAM_DPRINTF(("%s: wrote new global line: %s\n", fcn, lp->line)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_WRITE); } /* * We are changing an existing entry. Retain any prefix whitespace, * but overwrite everything else. This preserves tabs added for * readability. */ str = found->line; cp = prefix; while (*str == ' ' || *str == '\t') *(cp++) = *(str++); *cp = '\0'; /* Terminate prefix */ len = strlen(prefix) + strlen(globalcmd); len += strlen(menu_cmds[SEP_CMD]) + 10; free(found->line); found->line = s_calloc(1, len); (void) snprintf(found->line, len, "%s%s%s%d", prefix, globalcmd, menu_cmds[SEP_CMD], val); BAM_DPRINTF(("%s: replaced global line with: %s\n", fcn, found->line)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_WRITE); /* need a write to menu */ } /* * partial_path may be anything like "kernel/unix" or "kmdb". Try to * expand it to a full unix path. The calling function is expected to * output a message if an error occurs and NULL is returned. */ static char * expand_path(const char *partial_path) { int new_path_len; char *new_path; struct stat sb; const char *fcn = "expand_path()"; new_path_len = strlen(partial_path) + 64; new_path = s_calloc(1, new_path_len); /* First, try the simplest case - something like "kernel/unix" */ (void) snprintf(new_path, new_path_len, "/kernel/%s", partial_path); if (stat(new_path, &sb) == 0) { BAM_DPRINTF(("%s: expanded path: %s\n", fcn, new_path)); return (new_path); } if (strcmp(partial_path, "kmdb") == 0) { (void) snprintf(new_path, new_path_len, "%s -k", DIRECT_BOOT_KERNEL); BAM_DPRINTF(("%s: expanded path: %s\n", fcn, new_path)); return (new_path); } /* * We've quickly reached unsupported usage. Try once more to * see if we were just given a glom name. */ (void) snprintf(new_path, new_path_len, "/kernel/%s/unix", partial_path); if (stat(new_path, &sb) == 0) { BAM_DPRINTF(("%s: expanded path: %s\n", fcn, new_path)); return (new_path); } free(new_path); BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); return (NULL); } /* * The kernel cmd and arg have been changed, so * check whether the archive line needs to change. */ static void set_archive_line(entry_t *entryp, line_t *kernelp) { line_t *lp = entryp->start; char *new_archive; menu_cmd_t m_cmd; const char *fcn = "set_archive_line()"; for (; lp != NULL; lp = lp->next) { if (lp->cmd != NULL && strncmp(lp->cmd, menu_cmds[MODULE_CMD], sizeof (menu_cmds[MODULE_CMD]) - 1) == 0) { break; } INJECT_ERROR1("SET_ARCHIVE_LINE_END_ENTRY", lp = entryp->end); if (lp == entryp->end) { BAM_DPRINTF(("%s: no module/archive line for entry: " "%d\n", fcn, entryp->entryNum)); return; } } INJECT_ERROR1("SET_ARCHIVE_LINE_END_MENU", lp = NULL); if (lp == NULL) { BAM_DPRINTF(("%s: no module/archive line for entry: %d\n", fcn, entryp->entryNum)); return; } if (strstr(kernelp->arg, "$ISADIR") != NULL) { new_archive = DIRECT_BOOT_ARCHIVE; m_cmd = MODULE_DOLLAR_CMD; } else if (strstr(kernelp->arg, "amd64") != NULL) { new_archive = DIRECT_BOOT_ARCHIVE_64; m_cmd = MODULE_CMD; } else { new_archive = DIRECT_BOOT_ARCHIVE_32; m_cmd = MODULE_CMD; } if (strcmp(lp->arg, new_archive) == 0) { BAM_DPRINTF(("%s: no change for line: %s\n", fcn, lp->arg)); return; } if (lp->cmd != NULL && strcmp(lp->cmd, menu_cmds[m_cmd]) != 0) { free(lp->cmd); lp->cmd = s_strdup(menu_cmds[m_cmd]); } free(lp->arg); lp->arg = s_strdup(new_archive); update_line(lp); BAM_DPRINTF(("%s: replaced for line: %s\n", fcn, lp->line)); } /* * Title for an entry to set properties that once went in bootenv.rc. */ #define BOOTENV_RC_TITLE "Solaris bootenv rc" /* * If path is NULL, return the kernel (optnum == KERNEL_CMD) or arguments * (optnum == ARGS_CMD) in the argument buf. If path is a zero-length * string, reset the value to the default. If path is a non-zero-length * string, set the kernel or arguments. */ static error_t get_set_kernel( menu_t *mp, menu_cmd_t optnum, char *path, char *buf, size_t bufsize) { int entryNum; int rv = BAM_SUCCESS; int free_new_path = 0; entry_t *entryp; line_t *ptr; line_t *kernelp; char *new_arg; char *old_args; char *space; char *new_path; char old_space; size_t old_kernel_len = 0; size_t new_str_len; char *fstype; char *osdev; char *sign; char signbuf[PATH_MAX]; int ret; const char *fcn = "get_set_kernel()"; assert(bufsize > 0); ptr = kernelp = NULL; new_arg = old_args = space = NULL; new_path = NULL; buf[0] = '\0'; INJECT_ERROR1("GET_SET_KERNEL_NOT_DBOOT", bam_direct = BAM_DIRECT_MULTIBOOT); if (bam_direct != BAM_DIRECT_DBOOT) { bam_error(_("bootadm set-menu %s may only be run on " "directboot kernels.\n"), optnum == KERNEL_CMD ? "kernel" : "args"); return (BAM_ERROR); } /* * If a user changed the default entry to a non-bootadm controlled * one, we don't want to mess with it. Just print an error and * return. */ if (mp->curdefault) { entryNum = s_strtol(mp->curdefault->arg); for (entryp = mp->entries; entryp; entryp = entryp->next) { if (entryp->entryNum == entryNum) break; } if ((entryp != NULL) && ((entryp->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU)) == 0)) { bam_error(_("Default /boot/grub/menu.lst entry is not " "controlled by bootadm. Exiting\n")); return (BAM_ERROR); } } entryp = find_boot_entry(mp, BOOTENV_RC_TITLE, NULL, NULL, NULL, NULL, 0, &entryNum); if (entryp != NULL) { for (ptr = entryp->start; ptr && ptr != entryp->end; ptr = ptr->next) { if (strncmp(ptr->cmd, menu_cmds[KERNEL_CMD], sizeof (menu_cmds[KERNEL_CMD]) - 1) == 0) { kernelp = ptr; break; } } if (kernelp == NULL) { bam_error(_("no kernel line found in entry %d\n"), entryNum); return (BAM_ERROR); } old_kernel_len = strcspn(kernelp->arg, " \t"); space = old_args = kernelp->arg + old_kernel_len; while ((*old_args == ' ') || (*old_args == '\t')) old_args++; } if (path == NULL) { if (entryp == NULL) { BAM_DPRINTF(("%s: no RC entry, nothing to report\n", fcn)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } assert(kernelp); if (optnum == ARGS_CMD) { if (old_args[0] != '\0') { (void) strlcpy(buf, old_args, bufsize); BAM_DPRINTF(("%s: read menu boot-args: %s\n", fcn, buf)); } } else { /* * We need to print the kernel, so we just turn the * first space into a '\0' and print the beginning. * We don't print anything if it's the default kernel. */ old_space = *space; *space = '\0'; if (strcmp(kernelp->arg, DIRECT_BOOT_KERNEL) != 0) { (void) strlcpy(buf, kernelp->arg, bufsize); BAM_DPRINTF(("%s: read menu boot-file: %s\n", fcn, buf)); } *space = old_space; } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } /* * First, check if we're resetting an entry to the default. */ if ((path[0] == '\0') || ((optnum == KERNEL_CMD) && (strcmp(path, DIRECT_BOOT_KERNEL) == 0))) { if ((entryp == NULL) || (kernelp == NULL)) { /* No previous entry, it's already the default */ BAM_DPRINTF(("%s: no reset, already has default\n", fcn)); return (BAM_SUCCESS); } /* * Check if we can delete the entry. If we're resetting the * kernel command, and the args is already empty, or if we're * resetting the args command, and the kernel is already the * default, we can restore the old default and delete the entry. */ if (((optnum == KERNEL_CMD) && ((old_args == NULL) || (old_args[0] == '\0'))) || ((optnum == ARGS_CMD) && (strncmp(kernelp->arg, DIRECT_BOOT_KERNEL, sizeof (DIRECT_BOOT_KERNEL) - 1) == 0))) { kernelp = NULL; (void) delete_boot_entry(mp, entryNum, DBE_PRINTERR); restore_default_entry(mp, BAM_OLD_RC_DEF, mp->old_rc_default); mp->old_rc_default = NULL; rv = BAM_WRITE; BAM_DPRINTF(("%s: resetting to default\n", fcn)); goto done; } if (optnum == KERNEL_CMD) { /* * At this point, we've already checked that old_args * and entryp are valid pointers. The "+ 2" is for * a space a the string termination character. */ new_str_len = (sizeof (DIRECT_BOOT_KERNEL) - 1) + strlen(old_args) + 2; new_arg = s_calloc(1, new_str_len); (void) snprintf(new_arg, new_str_len, "%s %s", DIRECT_BOOT_KERNEL, old_args); free(kernelp->arg); kernelp->arg = new_arg; /* * We have changed the kernel line, so we may need * to update the archive line as well. */ set_archive_line(entryp, kernelp); BAM_DPRINTF(("%s: reset kernel to default, but " "retained old args: %s\n", fcn, kernelp->arg)); } else { /* * We're resetting the boot args to nothing, so * we only need to copy the kernel. We've already * checked that the kernel is not the default. */ new_arg = s_calloc(1, old_kernel_len + 1); (void) snprintf(new_arg, old_kernel_len + 1, "%s", kernelp->arg); free(kernelp->arg); kernelp->arg = new_arg; BAM_DPRINTF(("%s: reset args to default, but retained " "old kernel: %s\n", fcn, kernelp->arg)); } rv = BAM_WRITE; goto done; } /* * Expand the kernel file to a full path, if necessary */ if ((optnum == KERNEL_CMD) && (path[0] != '/')) { new_path = expand_path(path); if (new_path == NULL) { bam_error(_("unable to expand %s to a full file " "path.\n"), path); BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); return (BAM_ERROR); } free_new_path = 1; } else { new_path = path; free_new_path = 0; } /* * At this point, we know we're setting a new value. First, take care * of the case where there was no previous entry. */ if (entryp == NULL) { /* Similar to code in update_temp */ fstype = get_fstype("/"); INJECT_ERROR1("GET_SET_KERNEL_FSTYPE", fstype = NULL); if (fstype == NULL) { bam_error(_("cannot determine filesystem type for " "\"/\".\nCannot generate GRUB menu entry with " "EEPROM arguments.\n")); rv = BAM_ERROR; goto done; } osdev = get_special("/"); INJECT_ERROR1("GET_SET_KERNEL_SPECIAL", osdev = NULL); if (osdev == NULL) { free(fstype); bam_error(_("cannot determine device special file for " "\"/\".\nCannot generate GRUB menu entry with " "EEPROM arguments.\n")); rv = BAM_ERROR; goto done; } sign = find_existing_sign("/", osdev, fstype); INJECT_ERROR1("GET_SET_KERNEL_SIGN", sign = NULL); if (sign == NULL) { free(fstype); free(osdev); bam_error(_("cannot determine boot signature for " "\"/\".\nCannot generate GRUB menu entry with " "EEPROM arguments.\n")); rv = BAM_ERROR; goto done; } free(osdev); (void) strlcpy(signbuf, sign, sizeof (signbuf)); free(sign); assert(strchr(signbuf, '(') == NULL && strchr(signbuf, ',') == NULL && strchr(signbuf, ')') == NULL); if (optnum == KERNEL_CMD) { if (strcmp(fstype, "zfs") == 0) { new_str_len = strlen(new_path) + strlen(ZFS_BOOT) + 8; new_arg = s_calloc(1, new_str_len); (void) snprintf(new_arg, new_str_len, "%s %s", new_path, ZFS_BOOT); BAM_DPRINTF(("%s: new kernel=%s\n", fcn, new_arg)); entryNum = add_boot_entry(mp, BOOTENV_RC_TITLE, signbuf, new_arg, NULL, NULL, NULL); free(new_arg); } else { BAM_DPRINTF(("%s: new kernel=%s\n", fcn, new_path)); entryNum = add_boot_entry(mp, BOOTENV_RC_TITLE, signbuf, new_path, NULL, NULL, NULL); } } else { new_str_len = strlen(path) + 8; if (strcmp(fstype, "zfs") == 0) { new_str_len += strlen(DIRECT_BOOT_KERNEL_ZFS); new_arg = s_calloc(1, new_str_len); (void) snprintf(new_arg, new_str_len, "%s %s", DIRECT_BOOT_KERNEL_ZFS, path); } else { new_str_len += strlen(DIRECT_BOOT_KERNEL); new_arg = s_calloc(1, new_str_len); (void) snprintf(new_arg, new_str_len, "%s %s", DIRECT_BOOT_KERNEL, path); } BAM_DPRINTF(("%s: new args=%s\n", fcn, new_arg)); entryNum = add_boot_entry(mp, BOOTENV_RC_TITLE, signbuf, new_arg, NULL, DIRECT_BOOT_ARCHIVE, NULL); free(new_arg); } free(fstype); INJECT_ERROR1("GET_SET_KERNEL_ADD_BOOT_ENTRY", entryNum = BAM_ERROR); if (entryNum == BAM_ERROR) { bam_error(_("failed to add boot entry: %s\n"), BOOTENV_RC_TITLE); rv = BAM_ERROR; goto done; } save_default_entry(mp, BAM_OLD_RC_DEF); ret = set_global(mp, menu_cmds[DEFAULT_CMD], entryNum); INJECT_ERROR1("GET_SET_KERNEL_SET_GLOBAL", ret = BAM_ERROR); if (ret == BAM_ERROR) { bam_error(_("failed to set default to: %d\n"), entryNum); } rv = BAM_WRITE; goto done; } /* * There was already an bootenv entry which we need to edit. */ if (optnum == KERNEL_CMD) { new_str_len = strlen(new_path) + strlen(old_args) + 2; new_arg = s_calloc(1, new_str_len); (void) snprintf(new_arg, new_str_len, "%s %s", new_path, old_args); free(kernelp->arg); kernelp->arg = new_arg; /* * If we have changed the kernel line, we may need to update * the archive line as well. */ set_archive_line(entryp, kernelp); BAM_DPRINTF(("%s: rc line exists, replaced kernel, same " "args: %s\n", fcn, kernelp->arg)); } else { new_str_len = old_kernel_len + strlen(path) + 8; new_arg = s_calloc(1, new_str_len); (void) strncpy(new_arg, kernelp->arg, old_kernel_len); (void) strlcat(new_arg, " ", new_str_len); (void) strlcat(new_arg, path, new_str_len); free(kernelp->arg); kernelp->arg = new_arg; BAM_DPRINTF(("%s: rc line exists, same kernel, but new " "args: %s\n", fcn, kernelp->arg)); } rv = BAM_WRITE; done: if ((rv == BAM_WRITE) && kernelp) update_line(kernelp); if (free_new_path) free(new_path); if (rv == BAM_WRITE) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (rv); } static error_t get_kernel(menu_t *mp, menu_cmd_t optnum, char *buf, size_t bufsize) { const char *fcn = "get_kernel()"; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, menu_cmds[optnum])); return (get_set_kernel(mp, optnum, NULL, buf, bufsize)); } static error_t set_kernel(menu_t *mp, menu_cmd_t optnum, char *path, char *buf, size_t bufsize) { const char *fcn = "set_kernel()"; assert(path != NULL); BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, menu_cmds[optnum], path)); return (get_set_kernel(mp, optnum, path, buf, bufsize)); } /*ARGSUSED*/ static error_t set_option(menu_t *mp, char *dummy, char *opt) { int optnum; int optval; char *val; char buf[BUFSIZ] = ""; error_t rv; const char *fcn = "set_option()"; assert(mp); assert(opt); assert(dummy == NULL); /* opt is set from bam_argv[0] and is always non-NULL */ BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, opt)); val = strchr(opt, '='); if (val != NULL) { *val = '\0'; } if (strcmp(opt, "default") == 0) { optnum = DEFAULT_CMD; } else if (strcmp(opt, "timeout") == 0) { optnum = TIMEOUT_CMD; } else if (strcmp(opt, menu_cmds[KERNEL_CMD]) == 0) { optnum = KERNEL_CMD; } else if (strcmp(opt, menu_cmds[ARGS_CMD]) == 0) { optnum = ARGS_CMD; } else { bam_error(_("invalid option: %s\n"), opt); return (BAM_ERROR); } /* * kernel and args are allowed without "=new_value" strings. All * others cause errors */ if ((val == NULL) && (optnum != KERNEL_CMD) && (optnum != ARGS_CMD)) { bam_error(_("option has no argument: %s\n"), opt); return (BAM_ERROR); } else if (val != NULL) { *val = '='; } if ((optnum == KERNEL_CMD) || (optnum == ARGS_CMD)) { BAM_DPRINTF(("%s: setting %s option to %s\n", fcn, menu_cmds[optnum], val ? val + 1 : "NULL")); if (val) rv = set_kernel(mp, optnum, val + 1, buf, sizeof (buf)); else rv = get_kernel(mp, optnum, buf, sizeof (buf)); if ((rv == BAM_SUCCESS) && (buf[0] != '\0')) (void) printf("%s\n", buf); } else { optval = s_strtol(val + 1); BAM_DPRINTF(("%s: setting %s option to %s\n", fcn, menu_cmds[optnum], val + 1)); rv = set_global(mp, menu_cmds[optnum], optval); } if (rv == BAM_WRITE || rv == BAM_SUCCESS) { BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (rv); } /* * The quiet argument suppresses messages. This is used * when invoked in the context of other commands (e.g. list_entry) */ static error_t read_globals(menu_t *mp, char *menu_path, char *globalcmd, int quiet) { line_t *lp; char *arg; int done, ret = BAM_SUCCESS; assert(mp); assert(menu_path); assert(globalcmd); if (mp->start == NULL) { if (!quiet) bam_error(_("menu file not found: %s\n"), menu_path); return (BAM_ERROR); } done = 0; for (lp = mp->start; lp; lp = lp->next) { if (lp->flags != BAM_GLOBAL) continue; if (lp->cmd == NULL) { if (!quiet) bam_error(_("no command at line %d\n"), lp->lineNum); continue; } if (strcmp(globalcmd, lp->cmd) != 0) continue; /* Found global. Check for duplicates */ if (done && !quiet) { bam_error(_("duplicate command %s at line %d of " "%sboot/grub/menu.lst\n"), globalcmd, lp->lineNum, bam_root); ret = BAM_ERROR; } arg = lp->arg ? lp->arg : ""; bam_print(_("%s %s\n"), globalcmd, arg); done = 1; } if (!done && bam_verbose) bam_print(_("no %s entry found\n"), globalcmd); return (ret); } static error_t menu_write(char *root, menu_t *mp) { const char *fcn = "menu_write()"; BAM_DPRINTF(("%s: entered menu_write() for root: <%s>\n", fcn, root)); return (list2file(root, MENU_TMP, GRUB_MENU, mp->start)); } void line_free(line_t *lp) { if (lp == NULL) return; if (lp->cmd != NULL) free(lp->cmd); if (lp->sep) free(lp->sep); if (lp->arg) free(lp->arg); if (lp->line) free(lp->line); free(lp); } static void linelist_free(line_t *start) { line_t *lp; while (start) { lp = start; start = start->next; line_free(lp); } } static void filelist_free(filelist_t *flistp) { linelist_free(flistp->head); flistp->head = NULL; flistp->tail = NULL; } static void menu_free(menu_t *mp) { entry_t *ent, *tmp; assert(mp); if (mp->start) linelist_free(mp->start); ent = mp->entries; while (ent) { tmp = ent; ent = tmp->next; free(tmp); } free(mp); } /* * Utility routines */ /* * Returns 0 on success * Any other value indicates an error */ static int exec_cmd(char *cmdline, filelist_t *flistp) { char buf[BUFSIZ]; int ret; FILE *ptr; sigset_t set; void (*disp)(int); /* * For security * - only absolute paths are allowed * - set IFS to space and tab */ if (*cmdline != '/') { bam_error(_("path is not absolute: %s\n"), cmdline); return (-1); } (void) putenv("IFS= \t"); /* * We may have been exec'ed with SIGCHLD blocked * unblock it here */ (void) sigemptyset(&set); (void) sigaddset(&set, SIGCHLD); if (sigprocmask(SIG_UNBLOCK, &set, NULL) != 0) { bam_error(_("cannot unblock SIGCHLD: %s\n"), strerror(errno)); return (-1); } /* * Set SIGCHLD disposition to SIG_DFL for popen/pclose */ disp = sigset(SIGCHLD, SIG_DFL); if (disp == SIG_ERR) { bam_error(_("cannot set SIGCHLD disposition: %s\n"), strerror(errno)); return (-1); } if (disp == SIG_HOLD) { bam_error(_("SIGCHLD signal blocked. Cannot exec: %s\n"), cmdline); return (-1); } ptr = popen(cmdline, "r"); if (ptr == NULL) { bam_error(_("popen failed: %s: %s\n"), cmdline, strerror(errno)); return (-1); } /* * If we simply do a pclose() following a popen(), pclose() * will close the reader end of the pipe immediately even * if the child process has not started/exited. pclose() * does wait for cmd to terminate before returning though. * When the executed command writes its output to the pipe * there is no reader process and the command dies with * SIGPIPE. To avoid this we read repeatedly until read * terminates with EOF. This indicates that the command * (writer) has closed the pipe and we can safely do a * pclose(). * * Since pclose() does wait for the command to exit, * we can safely reap the exit status of the command * from the value returned by pclose() */ while (s_fgets(buf, sizeof (buf), ptr) != NULL) { if (flistp == NULL) { /* s_fgets strips newlines, so insert them at the end */ bam_print(_("%s\n"), buf); } else { append_to_flist(flistp, buf); } } ret = pclose(ptr); if (ret == -1) { bam_error(_("pclose failed: %s: %s\n"), cmdline, strerror(errno)); return (-1); } if (WIFEXITED(ret)) { return (WEXITSTATUS(ret)); } else { bam_error(_("command terminated abnormally: %s: %d\n"), cmdline, ret); return (-1); } } /* * Since this function returns -1 on error * it cannot be used to convert -1. However, * that is sufficient for what we need. */ static long s_strtol(char *str) { long l; char *res = NULL; if (str == NULL) { return (-1); } errno = 0; l = strtol(str, &res, 10); if (errno || *res != '\0') { return (-1); } return (l); } /* * Wrapper around fputs, that adds a newline (since fputs doesn't) */ static int s_fputs(char *str, FILE *fp) { char linebuf[BAM_MAXLINE]; (void) snprintf(linebuf, sizeof (linebuf), "%s\n", str); return (fputs(linebuf, fp)); } /* * Wrapper around fgets, that strips newlines returned by fgets */ char * s_fgets(char *buf, int buflen, FILE *fp) { int n; buf = fgets(buf, buflen, fp); if (buf) { n = strlen(buf); if (n == buflen - 1 && buf[n-1] != '\n') bam_error(_("the following line is too long " "(> %d chars)\n\t%s\n"), buflen - 1, buf); buf[n-1] = (buf[n-1] == '\n') ? '\0' : buf[n-1]; } return (buf); } void * s_calloc(size_t nelem, size_t sz) { void *ptr; ptr = calloc(nelem, sz); if (ptr == NULL) { bam_error(_("could not allocate memory: size = %u\n"), nelem*sz); bam_exit(1); } return (ptr); } void * s_realloc(void *ptr, size_t sz) { ptr = realloc(ptr, sz); if (ptr == NULL) { bam_error(_("could not allocate memory: size = %u\n"), sz); bam_exit(1); } return (ptr); } char * s_strdup(char *str) { char *ptr; if (str == NULL) return (NULL); ptr = strdup(str); if (ptr == NULL) { bam_error(_("could not allocate memory: size = %u\n"), strlen(str) + 1); bam_exit(1); } return (ptr); } /* * Returns 1 if amd64 (or sparc, for syncing x86 diskless clients) * Returns 0 otherwise */ static int is_amd64(void) { static int amd64 = -1; char isabuf[257]; /* from sysinfo(2) manpage */ if (amd64 != -1) return (amd64); if (bam_alt_platform) { if (strcmp(bam_platform, "i86pc") == 0 || strcmp(bam_platform, "amd64") == 0) { amd64 = 1; /* diskless server */ } } else { if (sysinfo(SI_ISALIST, isabuf, sizeof (isabuf)) > 0 && strncmp(isabuf, "amd64 ", strlen("amd64 ")) == 0) { amd64 = 1; } else if (strstr(isabuf, "i386") == NULL) { amd64 = 1; /* diskless server */ } } if (amd64 == -1) amd64 = 0; return (amd64); } static char * get_machine(void) { static int cached = -1; static char mbuf[257]; /* from sysinfo(2) manpage */ if (cached == 0) return (mbuf); if (bam_alt_platform) { return (bam_platform); } else { if (sysinfo(SI_MACHINE, mbuf, sizeof (mbuf)) > 0) { cached = 1; } } if (cached == -1) { mbuf[0] = '\0'; cached = 0; } return (mbuf); } int is_sparc(void) { static int issparc = -1; char mbuf[257]; /* from sysinfo(2) manpage */ if (issparc != -1) return (issparc); if (bam_alt_platform) { if (strncmp(bam_platform, "sun4", 4) == 0) { issparc = 1; } } else { if (sysinfo(SI_ARCHITECTURE, mbuf, sizeof (mbuf)) > 0 && strcmp(mbuf, "sparc") == 0) { issparc = 1; } } if (issparc == -1) issparc = 0; return (issparc); } static void append_to_flist(filelist_t *flistp, char *s) { line_t *lp; lp = s_calloc(1, sizeof (line_t)); lp->line = s_strdup(s); if (flistp->head == NULL) flistp->head = lp; else flistp->tail->next = lp; flistp->tail = lp; } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Copyright 2016 Toomas Soome . */ #ifndef _BOOTADM_H #define _BOOTADM_H #ifdef __cplusplus extern "C" { #endif #include #include #include #include #ifndef TEXT_DOMAIN #define TEXT_DOMAIN "SUNW_OST_OSCMD" #endif /* TEXT_DOMAIN */ #ifndef lint #define _(x) gettext(x) #else #define _(x) (x) #endif /* Type definitions */ /* GRUB menu per-line classification */ typedef enum { BAM_INVALID = 0, BAM_EMPTY, BAM_COMMENT, BAM_GLOBAL, BAM_ENTRY, BAM_TITLE } menu_flag_t; /* struct for menu.lst contents */ typedef struct line { int lineNum; /* Line number in menu.lst */ int entryNum; /* menu boot entry #. ENTRY_INIT if not applicable */ char *cmd; char *sep; char *arg; char *line; menu_flag_t flags; struct line *next; struct line *prev; } line_t; typedef struct entry { struct entry *next; struct entry *prev; line_t *start; line_t *end; int entryNum; uint_t flags; } entry_t; /* For flags value in entry_t */ #define BAM_ENTRY_BOOTADM 0x01 /* entry created by bootadm */ #define BAM_ENTRY_LU 0x02 /* entry created by Live Upgrade */ #define BAM_ENTRY_CHAINLOADER 0x04 /* chainloader entry; do not disturb */ #define BAM_ENTRY_ROOT 0x08 /* entry has a root line */ #define BAM_ENTRY_FAILSAFE 0x10 /* failsafe entry */ #define BAM_ENTRY_DBOOT 0x20 /* Is dboot (normal or failsafe) */ #define BAM_ENTRY_32BIT 0x40 /* Is a 32-bit entry */ #define BAM_ENTRY_HV 0x80 /* Is a hypervisor entry */ #define BAM_ENTRY_FINDROOT 0x100 /* entry has a findroot line */ #define BAM_ENTRY_MULTIBOOT 0x200 /* is multiboot (normal or failsafe) */ #define BAM_ENTRY_64BIT 0x400 /* Is a 64-bit entry */ #define BAM_ENTRY_UPGFSKERNEL 0x800 /* Upgrade failsafe kernel entry */ #define BAM_ENTRY_UPGFSMODULE 0x1000 /* Upgrade failsafe module entry */ #define BAM_ENTRY_LIBBE 0x2000 /* entry created by libbe */ typedef struct { line_t *start; line_t *end; line_t *curdefault; /* line containing default */ line_t *olddefault; /* old default line (commented) */ line_t *old_rc_default; /* old default line for bootenv.rc */ entry_t *entries; /* os entries */ } menu_t; typedef enum { BAM_ERROR = -1, /* Must be negative. add_boot_entry() depends on it */ BAM_SUCCESS = 0, BAM_WRITE = 2, BAM_MSG, /* Used by upgrade_menu() */ BAM_NOCHANGE /* Used by cvt_to_hyper()/cvt_to_metal() */ } error_t; /* * Menu related * menu_cmd_t and menu_cmds must be kept in sync * * The *_DOLLAR_CMD values must be 1 greater than the * respective [KERNEL|MODULE]_CMD values. */ typedef enum { DEFAULT_CMD = 0, TIMEOUT_CMD, TITLE_CMD, ROOT_CMD, KERNEL_CMD, KERNEL_DOLLAR_CMD, /* Must be KERNEL_CMD + 1 */ MODULE_CMD, MODULE_DOLLAR_CMD, /* Must be MODULE_CMD + 1 */ SEP_CMD, COMMENT_CMD, CHAINLOADER_CMD, ARGS_CMD, FINDROOT_CMD, BOOTFS_CMD } menu_cmd_t; extern char *menu_cmds[]; /* For multi- or direct-boot */ typedef enum { BAM_DIRECT_NOT_SET, BAM_DIRECT_MULTIBOOT, BAM_DIRECT_DBOOT } direct_or_multi_t; /* Is there a hypervisor present? */ typedef enum { BAM_HV_UNKNOWN, BAM_HV_NO, BAM_HV_PRESENT } hv_t; /* Is there findroot capability present ? */ typedef enum { BAM_FINDROOT_UNKNOWN, BAM_FINDROOT_ABSENT, BAM_FINDROOT_PRESENT } findroot_t; typedef enum { OPT_ABSENT = 0, /* No option */ OPT_REQ, /* option required */ OPT_OPTIONAL /* option may or may not be present */ } option_t; typedef struct { char *subcmd; option_t option; error_t (*handler)(); int unpriv; /* is this an unprivileged command */ } subcmd_defn_t; typedef enum zfs_mnted { ZFS_MNT_ERROR = -1, LEGACY_MOUNTED = 1, LEGACY_ALREADY, ZFS_MOUNTED, ZFS_ALREADY } zfs_mnted_t; extern int bam_verbose; extern int bam_force; extern direct_or_multi_t bam_direct; extern hv_t bam_is_hv; extern findroot_t bam_is_findroot; extern int bam_debug; extern void bam_add_line(menu_t *mp, entry_t *entry, line_t *prev, line_t *lp); extern void update_numbering(menu_t *mp); extern error_t set_global(menu_t *, char *, int); extern error_t upgrade_menu(menu_t *, char *, char *); extern error_t cvt_to_hyper(menu_t *, char *, char *); extern error_t cvt_to_metal(menu_t *, char *, char *); extern error_t check_subcmd_and_options(char *, char *, subcmd_defn_t *, error_t (**fp)()); extern char *mount_top_dataset(char *pool, zfs_mnted_t *mnted); extern void elide_trailing_slash(const char *, char *, size_t); extern int umount_top_dataset(char *, zfs_mnted_t, char *); extern void *s_calloc(size_t, size_t); extern void *s_realloc(void *, size_t); extern char *s_fgets(char *buf, int n, FILE *fp); extern void bam_error(char *format, ...); extern void bam_exit(int); extern void bam_print(char *, ...); extern void bam_print_stderr(char *format, ...); extern void bam_derror(char *format, ...); extern error_t bam_loader_menu(char *, char *, int, char *[]); extern error_t get_boot_cap(const char *osroot); extern char *get_special(char *); extern char *os_to_grubdisk(char *, int); extern void update_line(line_t *); extern int add_boot_entry(menu_t *, char *, char *, char *, char *, char *, char *); extern error_t delete_boot_entry(menu_t *, int, int); extern int is_grub(const char *); extern char *get_grubsign(char *osroot, char *osdev); extern char *get_grubroot(char *osroot, char *osdev, char *menu_root); extern int root_optional(char *osroot, char *menu_root); extern void unlink_line(menu_t *mp, line_t *lp); extern void line_free(line_t *lp); extern char *s_strdup(char *); extern int is_sparc(void); extern int is_pcfs(char *); extern int is_zfs(char *); extern int bootadm_digest(const char *, char **); #define BAM_MAXLINE 8192 /* menu.lst comments created by bootadm */ #define BAM_BOOTADM_HDR "---------- ADDED BY BOOTADM - DO NOT EDIT ----------" #define BAM_BOOTADM_FTR "---------------------END BOOTADM--------------------" /* * menu.lst comments create by Live Upgrade. Note that these are the end of * the comment strings - there will be other text before them. */ #define BAM_LU_HDR " - ADDED BY LIVE UPGRADE - DO NOT EDIT -----" #define BAM_LU_FTR " -------------- END LIVE UPGRADE ------------" #define BAM_OLDDEF "BOOTADM SAVED DEFAULT: " #define BAM_OLD_RC_DEF "BOOTADM RC SAVED DEFAULT: " /* * menu.lst comment created by libbe */ #define BAM_LIBBE_FTR "============ End of LIBBE entry =============" /* Title used for failsafe entries */ #define FAILSAFE_TITLE "Hammerhead failsafe" /* ZFS boot option */ #define ZFS_BOOT "-B $ZFS-BOOTFS" /* multiboot (legacy — unused with loader) */ #define MULTI_BOOT "/kernel/multiboot" #define MULTI_BOOT_FAILSAFE "/boot/multiboot" #define MULTI_BOOT_FAILSAFE_UNIX "kernel/unix" #define MULTI_BOOT_FAILSAFE_LINE "/boot/multiboot kernel/unix -s" /* directboot kernels — flat /kernel/ layout */ #define DIRECT_BOOT_64 "/kernel/unix" #define DIRECT_BOOT_32 DIRECT_BOOT_64 #define DIRECT_BOOT_KERNEL "/kernel/unix" #define DIRECT_BOOT_FAILSAFE_64 "/boot/kernel/unix" #define DIRECT_BOOT_FAILSAFE_32 DIRECT_BOOT_FAILSAFE_64 #define DIRECT_BOOT_FAILSAFE_KERNEL "/boot/kernel/unix" #define DIRECT_BOOT_FAILSAFE_LINE DIRECT_BOOT_FAILSAFE_KERNEL " -s" #define DIRECT_BOOT_KERNEL_ZFS DIRECT_BOOT_KERNEL " " ZFS_BOOT #define DIRECT_BOOT_PREFIX "/kernel/" #define KERNEL_PREFIX "/kernel/" #define UNIX_SPACE "/unix " #define AMD_UNIX_SPACE UNIX_SPACE /* Boot archives — stored in /boot/ */ #define ARCHIVE_PREFIX "/boot/" #define ARCHIVE_SUFFIX "boot_archive" #define CACHEDIR_SUFFIX "archive_cache" #define UPDATEDIR_SUFFIX "updates" #define DIRECT_BOOT_ARCHIVE "/boot/boot_archive" #define DIRECT_BOOT_ARCHIVE_64 "/boot/boot_archive" #define DIRECT_BOOT_ARCHIVE_32 DIRECT_BOOT_ARCHIVE_64 #define MULTIBOOT_ARCHIVE DIRECT_BOOT_ARCHIVE #define FAILSAFE_ARCHIVE "/boot/x86.miniroot-safe" #define FAILSAFE_ARCHIVE_64 "/boot/x86.miniroot-safe" #define FAILSAFE_ARCHIVE_32 FAILSAFE_ARCHIVE_64 #define CACHEDIR_64 "/boot/archive_cache" #define UPDATEDIR_64 "/boot/updates" /* Xen/xVM stubs — dead code, retained for compilation (TODO: remove) */ #define XEN_KERNEL_SUBSTR "xen.gz" #define XEN_64 "/boot/amd64/xen.gz" #define XEN_MENU XEN_64 #define HYPERVISOR_KERNEL DIRECT_BOOT_KERNEL #define XEN_KERNEL_MODULE_LINE HYPERVISOR_KERNEL " " HYPERVISOR_KERNEL #define XEN_KERNEL_MODULE_LINE_ZFS \ HYPERVISOR_KERNEL " " HYPERVISOR_KERNEL " " ZFS_BOOT #define NEW_HV_ENTRY "Hammerhead" /* Helpers */ #define MKISOFS_PATH "/usr/bin/mkisofs" #define DD_PATH_USR "/bin/dd" #define LOCKFS_PATH "/usr/sbin/lockfs" /* A first guess at the number of entries in a menu */ #define BAM_ENTRY_NUM 10 /* toggle for whether delete_boot_entry prints an error message or not */ #define DBE_PRINTERR 0 #define DBE_QUIET 1 /* * Debugging defines */ #define INJECT_ERROR1(x, y) \ { \ if (bam_debug) { \ char *inj = getenv("_BOOTADM_INJECT"); \ if (inj && strcmp(inj, (x)) == 0) { \ y; \ } \ } \ } #define INJECT_ERROR2(x, y, z) \ { \ if (bam_debug) { \ char *inj = getenv("_BOOTADM_INJECT"); \ if (inj && strcmp(inj, (x)) == 0) { \ y; \ z; \ } \ } \ } #define BAM_DPRINTF(x) {if (bam_debug) bam_derror x; } #ifdef __cplusplus } #endif #endif /* _BOOTADM_H */ /* * This file and its contents are supplied under the terms of the * Common Development and Distribution License ("CDDL"), version 1.0. * You may only use this file in accordance with the terms of version * 1.0 of the CDDL. * * A full copy of the text of the CDDL should have accompanied this * source. A copy of the CDDL is also available via the Internet at * http://www.illumos.org/license/CDDL. */ /* * Copyright 2016 Toomas Soome * Copyright 2017 OmniTI Computer Consulting, Inc. All rights reserved. */ /* * Create sha1 hash for file. * * NOTE: This is hardwired for now, so use libmd's SHA1 for simplicity. */ #include #include #include #include #include #include #include #include #include #include "bootadm.h" #define BUFFERSIZE (64 * 1024) static uint8_t buf[BUFFERSIZE]; int bootadm_digest(const char *filename, char **result) { int fd; char *resultstr = NULL; uint8_t *resultbuf; int resultstrlen, resultlen, exitcode; SHA1_CTX sha1_ctx; ssize_t nread; /* Allocate a buffer to store result. */ resultlen = SHA1_DIGEST_LENGTH; if ((resultbuf = malloc(resultlen)) == NULL) { bam_print(gettext("out of memory\n")); exitcode = BAM_ERROR; goto cleanup; } if ((fd = open(filename, O_RDONLY | O_NONBLOCK)) == -1) { bam_print(gettext("can not open input file %s\n"), filename); exitcode = BAM_ERROR; goto cleanup; } SHA1Init(&sha1_ctx); while ((nread = read(fd, buf, sizeof (buf))) > 0) SHA1Update(&sha1_ctx, buf, nread); if (nread == -1) { bam_print(gettext("error reading file: %s\n"), strerror(errno)); exitcode = BAM_ERROR; goto cleanup; } SHA1Final(resultbuf, &sha1_ctx); /* Allocate a buffer to store result string */ resultstrlen = 2 * resultlen + 1; /* Two hex chars per byte. */ if ((resultstr = malloc(resultstrlen)) == NULL) { bam_print(gettext("out of memory\n")); exitcode = BAM_ERROR; goto cleanup; } tohexstr(resultbuf, resultlen, resultstr, resultstrlen); exitcode = BAM_SUCCESS; (void) close(fd); cleanup: if (exitcode == BAM_ERROR) { free(resultstr); resultstr = NULL; } free(resultbuf); *result = resultstr; return (exitcode); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2016 Toomas Soome * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved. * * Xen hypervisor support removed — Hammerhead is bare metal only. * These stubs satisfy the bootadm subcmd table. */ #include "bootadm.h" /*ARGSUSED*/ error_t cvt_to_hyper(menu_t *mp, char *osroot, char *extra_args) { bam_error(_("hypervisor support has been removed\n")); return (BAM_ERROR); } /*ARGSUSED*/ error_t cvt_to_metal(menu_t *mp, char *osroot, char *menu_root) { bam_error(_("hypervisor support has been removed\n")); return (BAM_ERROR); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Milan Jurik. All rights reserved. */ /* * Copyright 2015 Nexenta Systems, Inc. All rights reserved. * Copyright 2016 Toomas Soome * Copyright 2019 OmniOS Community Edition (OmniOSce) Association. * Copyright 2020 2020 Data Direct Networks. */ /* * Loader menu management. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "bootadm.h" extern int bam_rootlen; extern int bam_alt_root; extern char *rootbuf; extern char *bam_root; #define BOOT_DIR "/boot" #define CONF_DIR BOOT_DIR "/conf.d" #define MENU BOOT_DIR "/menu.lst" #define TRANSIENT BOOT_DIR "/transient.conf" #define XEN_CONFIG CONF_DIR "/xen" typedef struct menu_entry { int me_idx; boolean_t me_active; boolean_t me_active_next; char *me_title; char *me_type; char *me_bootfs; STAILQ_ENTRY(menu_entry) me_next; } menu_entry_t; STAILQ_HEAD(menu_lst, menu_entry); static error_t set_option(struct menu_lst *, char *, char *); static error_t list_entry(struct menu_lst *, char *, char *); static error_t update_entry(struct menu_lst *, char *, char *); static error_t update_temp(struct menu_lst *, char *, char *); static error_t list_setting(struct menu_lst *menu, char *, char *); static error_t disable_hyper(struct menu_lst *, char *, char *); static error_t enable_hyper(struct menu_lst *, char *, char *); /* Menu related sub commands */ static subcmd_defn_t menu_subcmds[] = { "set_option", OPT_ABSENT, set_option, 0, /* PUB */ "list_entry", OPT_OPTIONAL, list_entry, 1, /* PUB */ "update_entry", OPT_REQ, update_entry, 0, /* menu */ "update_temp", OPT_OPTIONAL, update_temp, 0, /* reboot */ "list_setting", OPT_OPTIONAL, list_setting, 1, /* menu */ "disable_hypervisor", OPT_ABSENT, disable_hyper, 0, /* menu */ "enable_hypervisor", OPT_ABSENT, enable_hyper, 0, /* menu */ NULL, 0, NULL, 0 /* must be last */ }; #define NUM_COLS (5) static boolean_t print_menu_cb(ofmt_arg_t *ofarg, char *buf, uint_t bufsize) { menu_entry_t *entry = ofarg->ofmt_cbarg; switch (ofarg->ofmt_id) { case 0: (void) snprintf(buf, bufsize, "%d", entry->me_idx); break; case 1: (void) snprintf(buf, bufsize, "%s", entry->me_title); break; case 2: (void) snprintf(buf, bufsize, "%s", entry->me_bootfs); break; case 3: (void) snprintf(buf, bufsize, "%s", entry->me_type); break; case 4: if (entry->me_active_next == B_TRUE) { (void) snprintf(buf, bufsize, " T"); break; } if (entry->me_active == B_TRUE) (void) snprintf(buf, bufsize, " *"); else (void) snprintf(buf, bufsize, " -"); break; default: return (B_FALSE); } return (B_TRUE); } static void init_hdr_cols(ofmt_field_t *hdr) { uint_t i; for (i = 0; i < NUM_COLS; i++) { char *name = NULL; switch (i) { case 0: name = _("INDEX"); break; case 1: name = _("NAME"); break; case 2: name = _("DEVICE"); break; case 3: name = _("TYPE"); break; case 4: name = _("DEFAULT"); break; } hdr[i].of_name = name; hdr[i].of_id = i; hdr[i].of_cb = print_menu_cb; if (name != NULL) { wchar_t wname[128]; size_t sz = mbstowcs(wname, name, sizeof (wname) / sizeof (wchar_t)); if (sz > 0) { int wcsw = wcswidth(wname, sz); if (wcsw > 0) hdr[i].of_width = wcsw; else hdr[i].of_width = sz; } else { hdr[i].of_width = strlen(name); } } } } static void menu_update_widths(ofmt_field_t *hdr, struct menu_lst *menu) { size_t len[NUM_COLS]; menu_entry_t *entry; int i; for (i = 0; i < NUM_COLS; i++) len[i] = hdr[i].of_width + 1; STAILQ_FOREACH(entry, menu, me_next) { size_t entry_len; entry_len = strlen(entry->me_title) + 1; if (entry_len > len[1]) len[1] = entry_len; entry_len = strlen(entry->me_bootfs) + 1; if (entry_len > len[2]) len[2] = entry_len; entry_len = strlen(entry->me_type) + 1; if (entry_len > len[3]) len[3] = entry_len; } for (i = 0; i < NUM_COLS; i++) hdr[i].of_width = len[i]; } static ofmt_field_t * init_menu_template(struct menu_lst *menu) { ofmt_field_t *temp; if ((temp = calloc(NUM_COLS + 1, sizeof (ofmt_field_t))) == NULL) return (temp); init_hdr_cols(temp); menu_update_widths(temp, menu); return (temp); } static void print_nodes(boolean_t parsable, struct menu_lst *menu) { ofmt_status_t oferr; ofmt_handle_t ofmt; uint_t ofmtflags = 0; ofmt_field_t *menu_template; menu_entry_t *entry; if (parsable == B_TRUE) ofmtflags = OFMT_PARSABLE; menu_template = init_menu_template(menu); oferr = ofmt_open(NULL, menu_template, ofmtflags, 0, &ofmt); if (oferr != OFMT_SUCCESS) { char buf[OFMT_BUFSIZE]; (void) ofmt_strerror(ofmt, oferr, buf, sizeof (buf)); (void) printf("bootadm: %s\n", buf); free(menu_template); return; } STAILQ_FOREACH(entry, menu, me_next) ofmt_print(ofmt, entry); ofmt_close(ofmt); free(menu_template); } /* * Get the be_active_on_boot for bootfs. */ static boolean_t menu_active_on_boot(be_node_list_t *be_nodes, const char *bootfs) { be_node_list_t *be_node; boolean_t rv = B_FALSE; for (be_node = be_nodes; be_node != NULL; be_node = be_node->be_next_node) { if (strcmp(be_node->be_root_ds, bootfs) == 0) { rv = be_node->be_active_on_boot; break; } } return (rv); } /* * Get the be_active_next for bootfs. */ static boolean_t menu_active_next(be_node_list_t *be_nodes, const char *bootfs) { be_node_list_t *be_node; boolean_t rv = B_FALSE; for (be_node = be_nodes; be_node != NULL; be_node = be_node->be_next_node) { if (strcmp(be_node->be_root_ds, bootfs) == 0) { rv = be_node->be_active_next; break; } } return (rv); } error_t menu_read(struct menu_lst *menu, char *menu_path) { FILE *fp; be_node_list_t *be_nodes; menu_entry_t *mp; char buf[PATH_MAX]; char *title; char *bootfs; char *type; char *key, *value; int i = 0; int ret = BAM_SUCCESS; fp = fopen(menu_path, "r"); if (fp == NULL) return (BAM_ERROR); if (be_list(NULL, &be_nodes, BE_LIST_DEFAULT) != BE_SUCCESS) be_nodes = NULL; /* * menu.lst entry is on two lines, one for title, one for bootfs * so we process both lines in succession. */ title = NULL; type = NULL; bootfs = NULL; do { if (fgets(buf, PATH_MAX, fp) == NULL) { if (!feof(fp)) ret = BAM_ERROR; goto done; } if (buf[0] == '\n') /* Skip empty lines */ continue; key = strtok(buf, " \n"); if (key == NULL || strcmp(key, "title") != 0) { ret = BAM_ERROR; goto done; } value = strtok(NULL, " \n"); if (value == NULL || (title = strdup(value)) == NULL) { ret = BAM_ERROR; goto done; } do { if (fgets(buf, PATH_MAX, fp) == NULL) { ret = BAM_ERROR; goto done; } } while (buf[0] == '\n'); /* Skip empty lines */ key = strtok(buf, " \n"); if (key == NULL || (type = strdup(key)) == NULL) { ret = BAM_ERROR; goto done; } value = strtok(NULL, " \n"); if (value == NULL || (bootfs = strdup(value)) == NULL) { ret = BAM_ERROR; goto done; } if ((mp = malloc(sizeof (menu_entry_t))) == NULL) { ret = BAM_ERROR; goto done; } mp->me_idx = i++; mp->me_title = title; mp->me_type = type; mp->me_bootfs = bootfs; mp->me_active = menu_active_on_boot(be_nodes, bootfs); mp->me_active_next = menu_active_next(be_nodes, bootfs); STAILQ_INSERT_TAIL(menu, mp, me_next); title = NULL; type = NULL; bootfs = NULL; } while (feof(fp) == 0); done: free(title); free(type); free(bootfs); (void) fclose(fp); be_free_list(be_nodes); return (ret); } void menu_free(struct menu_lst *menu) { menu_entry_t *entry; while (!STAILQ_EMPTY(menu)) { entry = STAILQ_FIRST(menu); STAILQ_REMOVE_HEAD(menu, me_next); free(entry->me_title); free(entry->me_type); free(entry->me_bootfs); free(entry); } } error_t bam_loader_menu(char *subcmd, char *opt, int largc, char *largv[]) { error_t ret; char menu_path[PATH_MAX]; char clean_menu_root[PATH_MAX]; char menu_root[PATH_MAX]; struct stat sb; error_t (*f)(struct menu_lst *, char *, char *); char *special; char *pool = NULL; zfs_mnted_t zmnted; char *zmntpt; char *osdev; char *osroot; const char *fcn = "bam_loader_menu()"; struct menu_lst menu = {0}; STAILQ_INIT(&menu); /* * Check arguments */ ret = check_subcmd_and_options(subcmd, opt, menu_subcmds, &f); if (ret == BAM_ERROR) { return (BAM_ERROR); } assert(bam_root); (void) strlcpy(menu_root, bam_root, sizeof (menu_root)); osdev = osroot = NULL; if (strcmp(subcmd, "update_entry") == 0) { assert(opt); osdev = strtok(opt, ","); assert(osdev); osroot = strtok(NULL, ","); if (osroot) { /* fixup bam_root so that it points at osroot */ if (realpath(osroot, rootbuf) == NULL) { bam_error(_("cannot resolve path %s: %s\n"), osroot, strerror(errno)); return (BAM_ERROR); } bam_alt_root = 1; bam_root = rootbuf; bam_rootlen = strlen(rootbuf); } } if (stat(menu_root, &sb) == -1) { bam_error(_("cannot find menu\n")); return (BAM_ERROR); } if (!is_zfs(menu_root)) { bam_error(_("only ZFS root is supported\n")); return (BAM_ERROR); } assert(strcmp(menu_root, bam_root) == 0); special = get_special(menu_root); INJECT_ERROR1("Z_MENU_GET_SPECIAL", special = NULL); if (special == NULL) { bam_error(_("cant find special file for mount-point %s\n"), menu_root); return (BAM_ERROR); } pool = strtok(special, "/"); INJECT_ERROR1("Z_MENU_GET_POOL", pool = NULL); if (pool == NULL) { free(special); bam_error(_("cant find pool for mount-point %s\n"), menu_root); return (BAM_ERROR); } BAM_DPRINTF(("%s: derived pool=%s from special\n", fcn, pool)); zmntpt = mount_top_dataset(pool, &zmnted); INJECT_ERROR1("Z_MENU_MOUNT_TOP_DATASET", zmntpt = NULL); if (zmntpt == NULL) { bam_error(_("cannot mount pool dataset for pool: %s\n"), pool); free(special); return (BAM_ERROR); } BAM_DPRINTF(("%s: top dataset mountpoint=%s\n", fcn, zmntpt)); (void) strlcpy(menu_root, zmntpt, sizeof (menu_root)); BAM_DPRINTF(("%s: zfs menu_root=%s\n", fcn, menu_root)); elide_trailing_slash(menu_root, clean_menu_root, sizeof (clean_menu_root)); BAM_DPRINTF(("%s: cleaned menu root is <%s>\n", fcn, clean_menu_root)); (void) strlcpy(menu_path, clean_menu_root, sizeof (menu_path)); (void) strlcat(menu_path, MENU, sizeof (menu_path)); BAM_DPRINTF(("%s: menu path is: %s\n", fcn, menu_path)); /* * update_entry is special case, its used by installer * and needs to create menu.lst file for loader */ if (menu_read(&menu, menu_path) == BAM_ERROR && strcmp(subcmd, "update_entry") != 0) { bam_error(_("cannot find menu file: %s\n"), menu_path); if (special != NULL) free(special); return (BAM_ERROR); } /* * If listing the menu, display the menu location */ if (strcmp(subcmd, "list_entry") == 0) bam_print(_("the location for the active menu is: %s\n"), menu_path); /* * We already checked the following case in * check_subcmd_and_suboptions() above. Complete the * final step now. */ if (strcmp(subcmd, "set_option") == 0) { assert(largc == 1 && largv[0] && largv[1] == NULL); opt = largv[0]; } else if ((strcmp(subcmd, "enable_hypervisor") != 0) && (strcmp(subcmd, "list_setting") != 0)) { assert(largc == 0 && largv == NULL); } /* * Once the sub-cmd handler has run * only the line field is guaranteed to have valid values */ if (strcmp(subcmd, "update_entry") == 0) { ret = f(&menu, menu_root, osdev); } else if (strcmp(subcmd, "upgrade") == 0) { ret = f(&menu, bam_root, menu_root); } else if (strcmp(subcmd, "list_entry") == 0) { ret = f(&menu, menu_path, opt); } else if (strcmp(subcmd, "list_setting") == 0) { ret = f(&menu, ((largc > 0) ? largv[0] : ""), ((largc > 1) ? largv[1] : "")); } else if (strcmp(subcmd, "disable_hypervisor") == 0) { if (is_sparc()) { bam_error(_("%s operation unsupported on SPARC " "machines\n"), subcmd); ret = BAM_ERROR; } else { ret = f(&menu, bam_root, NULL); } } else if (strcmp(subcmd, "enable_hypervisor") == 0) { if (is_sparc()) { bam_error(_("%s operation unsupported on SPARC " "machines\n"), subcmd); ret = BAM_ERROR; } else { char *extra_args = NULL; /* * Compress all arguments passed in the largv[] array * into one string that can then be appended to the * end of the kernel$ string the routine to enable the * hypervisor will build. * * This allows the caller to supply arbitrary unparsed * arguments, such as dom0 memory settings or APIC * options. * * This concatenation will be done without ANY syntax * checking whatsoever, so it's the responsibility of * the caller to make sure the arguments are valid and * do not duplicate arguments the conversion routines * may create. */ if (largc > 0) { int extra_len, i; for (extra_len = 0, i = 0; i < largc; i++) extra_len += strlen(largv[i]); /* * Allocate space for argument strings, * intervening spaces and terminating NULL. */ extra_args = alloca(extra_len + largc); (void) strcpy(extra_args, largv[0]); for (i = 1; i < largc; i++) { (void) strcat(extra_args, " "); (void) strcat(extra_args, largv[i]); } } ret = f(&menu, bam_root, extra_args); } } else ret = f(&menu, NULL, opt); if (ret == BAM_WRITE) { BAM_DPRINTF(("%s: writing menu to clean-menu-root: <%s>\n", fcn, clean_menu_root)); /* ret = menu_write(clean_menu_root, menu); */ } INJECT_ERROR1("POOL_SET", pool = "/pooldata"); assert((is_zfs(menu_root)) ^ (pool == NULL)); if (pool) { (void) umount_top_dataset(pool, zmnted, zmntpt); free(special); } menu_free(&menu); return (ret); } /* * To suppress output from ficl. We do not want to see messages * from interpreting loader config. */ /*ARGSUSED*/ static void ficlTextOutSilent(ficlCallback *cb, char *text) { } /*ARGSUSED*/ static error_t set_option(struct menu_lst *menu, char *dummy, char *opt) { char path[PATH_MAX]; char *val; char *rest; int optval; menu_entry_t *entry; nvlist_t *be_attrs; FILE *fp; int rv, ret = BAM_SUCCESS; assert(menu); assert(opt); assert(dummy == NULL); val = strchr(opt, '='); if (val != NULL) { *val++ = '\0'; } else { bam_error(_("missing value in key=value\n")); return (BAM_ERROR); } if (strcmp(opt, "default") == 0) { errno = 0; optval = strtol(val, &rest, 10); if (errno != 0 || *rest != '\0') { bam_error(_("invalid boot entry number: %s\n"), val); return (BAM_ERROR); } STAILQ_FOREACH(entry, menu, me_next) { if (entry->me_idx == optval) break; } if (entry == NULL) { bam_error(_("invalid boot entry number: %s\n"), val); return (BAM_ERROR); } if (nvlist_alloc(&be_attrs, NV_UNIQUE_NAME, 0) != 0) { bam_error(_("out of memory\n")); return (BAM_ERROR); } if (nvlist_add_string(be_attrs, BE_ATTR_ORIG_BE_NAME, entry->me_title) != 0) { bam_error(_("out of memory\n")); nvlist_free(be_attrs); return (BAM_ERROR); } ret = be_activate(be_attrs); nvlist_free(be_attrs); if (ret != 0) ret = BAM_ERROR; return (ret); } else if (strcmp(opt, "timeout") == 0) { errno = 0; optval = strtol(val, &rest, 10); if (errno != 0 || *rest != '\0') { bam_error(_("invalid timeout: %s\n"), val); return (BAM_ERROR); } (void) snprintf(path, PATH_MAX, "%s" CONF_DIR "/timeout", bam_root); fp = fopen(path, "w"); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), path, strerror(errno)); return (BAM_ERROR); } /* * timeout=-1 is to disable auto boot in illumos, but * loader needs "NO" to disable auto boot. */ if (optval == -1) rv = fprintf(fp, "autoboot_delay=\"NO\"\n"); else rv = fprintf(fp, "autoboot_delay=\"%d\"\n", optval); if (rv < 0) { bam_error(_("write to file failed: %s: %s\n"), path, strerror(errno)); (void) fclose(fp); ret = BAM_ERROR; } else rv = fclose(fp); if (rv < 0) { bam_error(_("failed to close file: %s: %s\n"), path, strerror(errno)); ret = BAM_ERROR; } if (ret == BAM_ERROR) (void) unlink(path); return (BAM_SUCCESS); } bam_error(_("invalid option: %s\n"), opt); return (BAM_ERROR); } static int bam_mount_be(menu_entry_t *entry, char **dir) { nvlist_t *be_attrs = NULL; const char *tmpdir = getenv("TMPDIR"); const char *tmpname = "bam.XXXXXX"; be_node_list_t *be_node, *be_nodes = NULL; int ret; *dir = NULL; if (tmpdir == NULL) tmpdir = "/tmp"; ret = asprintf(dir, "%s/%s", tmpdir, tmpname); if (ret < 0) { return (BE_ERR_NOMEM); } *dir = mkdtemp(*dir); if (nvlist_alloc(&be_attrs, NV_UNIQUE_NAME, 0) != 0) { ret = BE_ERR_NOMEM; goto out; } ret = be_list(NULL, &be_nodes, BE_LIST_DEFAULT); if (ret != BE_SUCCESS) { goto out; } for (be_node = be_nodes; be_node; be_node = be_node->be_next_node) if (strcmp(be_node->be_root_ds, entry->me_bootfs) == 0) break; if (be_node == NULL) { ret = BE_ERR_BE_NOENT; goto out; } if (nvlist_add_string(be_attrs, BE_ATTR_ORIG_BE_NAME, be_node->be_node_name) != 0) { ret = BE_ERR_NOMEM; goto out; } if (nvlist_add_string(be_attrs, BE_ATTR_MOUNTPOINT, *dir) != 0) { ret = BE_ERR_NOMEM; goto out; } ret = be_mount(be_attrs); if (ret == BE_ERR_MOUNTED) { /* * if BE is mounted, dir does not point to correct directory */ (void) rmdir(*dir); free(*dir); *dir = NULL; } out: if (be_nodes != NULL) be_free_list(be_nodes); nvlist_free(be_attrs); return (ret); } static int bam_umount_be(char *dir) { nvlist_t *be_attrs; int ret; if (dir == NULL) /* nothing to do */ return (BE_SUCCESS); if (nvlist_alloc(&be_attrs, NV_UNIQUE_NAME, 0) != 0) return (BE_ERR_NOMEM); if (nvlist_add_string(be_attrs, BE_ATTR_ORIG_BE_NAME, dir) != 0) { ret = BE_ERR_NOMEM; goto out; } ret = be_unmount(be_attrs); out: nvlist_free(be_attrs); return (ret); } /* * display details of menu entry or single property */ static error_t list_menu_entry(menu_entry_t *entry, char *setting) { int ret = BAM_SUCCESS; char *ptr, *dir; char buf[MAX_INPUT]; ficlVm *vm; int mounted; ptr = strrchr(entry->me_bootfs, ':'); if (strcmp(entry->me_type, "bootfs") != 0 || (ptr != NULL && ptr[1] == '\0')) { (void) printf("\nTitle: %s\n", entry->me_title); (void) printf("Type: %s\n", entry->me_type); (void) printf("Device: %s\n", entry->me_bootfs); return (ret); } mounted = bam_mount_be(entry, &dir); if (mounted != BE_SUCCESS && mounted != BE_ERR_MOUNTED) { if (dir != NULL) { (void) rmdir(dir); free(dir); } bam_error(_("%s is not mounted: %s\n"), entry->me_title, be_err_to_str(mounted)); return (BAM_ERROR); } vm = bf_init("", ficlTextOutSilent); if (vm == NULL) { bam_error(_("error setting up forth interpreter\n")); ret = BAM_ERROR; goto done; } /* should only get FICL_VM_STATUS_OUT_OF_TEXT */ (void) snprintf(buf, MAX_INPUT, "set currdev=zfs:%s:", entry->me_bootfs); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("error interpreting boot config\n")); ret = BAM_ERROR; goto done; } (void) snprintf(buf, MAX_INPUT, "include /boot/forth/loader.4th"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("error interpreting boot config\n")); ret = BAM_ERROR; goto done; } (void) snprintf(buf, MAX_INPUT, "start"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("error interpreting boot config\n")); ret = BAM_ERROR; goto done; } (void) snprintf(buf, MAX_INPUT, "boot"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("error interpreting boot config\n")); ret = BAM_ERROR; goto done; } ret = BAM_SUCCESS; if (*setting == '\0') (void) printf("\nTitle: %s\n", entry->me_title); else if (strcasecmp(setting, "title") == 0) { (void) printf("%s\n", entry->me_title); goto done; } ptr = getenv("autoboot_delay"); if (ptr != NULL) { char *timeout = "-1"; if (strcasecmp(ptr, "NO") != 0) timeout = ptr; if (*setting == '\0') (void) printf("Timeout: %s\n", timeout); else if (strcasecmp(setting, "timeout") == 0) { (void) printf("%s\n", timeout); goto done; } } ptr = getenv("console"); if (ptr != NULL) { if (*setting == '\0') (void) printf("Console: %s\n", ptr); else if (strcasecmp(setting, "console") == 0) { (void) printf("%s\n", ptr); goto done; } } if (*setting == '\0') (void) printf("Bootfs: %s\n", entry->me_bootfs); else if (strcasecmp(setting, "bootfs") == 0) { (void) printf("%s\n", entry->me_bootfs); goto done; } ptr = getenv("xen_kernel"); if (ptr != NULL) { if (*setting == '\0') { (void) printf("Xen kernel: %s\n", ptr); } else if (strcasecmp(setting, "xen_kernel") == 0) { (void) printf("%s\n", ptr); goto done; } if (*setting == '\0') { (void) printf("Xen args: \"%s\"\n", getenv("xen_cmdline")); } else if (strcasecmp(setting, "xen_cmdline") == 0) { (void) printf("%s\n", getenv("xen_cmdline")); goto done; } if (*setting == '\0') { (void) printf("Kernel: %s\n", getenv("bootfile")); } else if (strcasecmp(setting, "kernel") == 0) { (void) printf("%s\n", getenv("bootfile")); goto done; } } else { ptr = getenv("kernelname"); if (ptr != NULL) { if (*setting == '\0') { (void) printf("Kernel: %s\n", ptr); } else if (strcasecmp(setting, "kernel") == 0) { (void) printf("%s\n", ptr); goto done; } } } ptr = getenv("boot-args"); if (ptr != NULL) { if (*setting == '\0') { (void) printf("Boot-args: \"%s\"\n", ptr); } else if (strcasecmp(setting, "boot-args") == 0) { (void) printf("%s\n", ptr); goto done; } } if (*setting == '\0' || strcasecmp(setting, "modules") == 0) { (void) printf("\nModules:\n"); ficlVmSetTextOut(vm, ficlCallbackDefaultTextOut); (void) snprintf(buf, MAX_INPUT, "show-module-options"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("error interpreting boot config\n")); ret = BAM_ERROR; goto done; } ret = BAM_SUCCESS; goto done; } /* if we got here with setting string, its unknown property */ if (*setting != '\0') { bam_error(_("unknown property: %s\n"), setting); ret = BAM_ERROR; } else ret = BAM_SUCCESS; done: bf_fini(); if (mounted != BE_ERR_MOUNTED) { (void) bam_umount_be(dir); } if (dir != NULL) { (void) rmdir(dir); free(dir); } return (ret); } /*ARGSUSED*/ static error_t list_entry(struct menu_lst *menu, char *menu_root, char *opt) { error_t ret = BAM_SUCCESS; menu_entry_t *entry; char *ptr, *title = NULL; int i, e = -1; if (opt == NULL) { print_nodes(B_FALSE, menu); return (ret); } if ((ptr = strchr(opt, '=')) == NULL) { bam_error(_("invalid option: %s\n"), opt); return (BAM_ERROR); } i = ptr - opt; if (strncmp(opt, "entry", i) == 0) { e = atoi(ptr+1); } else if (strncmp(opt, "title", i) == 0) { title = ptr+1; } else { bam_error(_("invalid option: %s\n"), opt); return (BAM_ERROR); } STAILQ_FOREACH(entry, menu, me_next) { if (title != NULL) { if (strcmp(title, entry->me_title) == 0) break; } else if (entry->me_idx == e) break; } if (entry == NULL) { bam_error(_("no matching entry found\n")); return (BAM_ERROR); } return (list_menu_entry(entry, "")); } /* * For now this is just stub entry to support grub interface, the * known consumer is installer ict.py code, calling as: * bootadm update-menu -R /a -Z -o rdisk * Later this can be converted to do something useful. */ /*ARGSUSED*/ static error_t update_entry(struct menu_lst *menu, char *menu_root, char *osdev) { char path[PATH_MAX]; char *pool = menu_root + 1; be_node_list_t *be_nodes, *be_node; int rv; FILE *fp; (void) snprintf(path, PATH_MAX, "%s%s", menu_root, MENU); rv = be_list(NULL, &be_nodes, BE_LIST_DEFAULT); if (rv != BE_SUCCESS) return (BAM_ERROR); fp = fopen(path, "w"); if (fp == NULL) { be_free_list(be_nodes); return (BAM_ERROR); } for (be_node = be_nodes; be_node; be_node = be_node->be_next_node) { if (strcmp(be_node->be_rpool, pool) == 0) { (void) fprintf(fp, "title %s\n", be_node->be_node_name); (void) fprintf(fp, "bootfs %s\n", be_node->be_root_ds); } } be_free_list(be_nodes); (void) fclose(fp); return (BAM_SUCCESS); } /*ARGSUSED*/ static error_t update_temp(struct menu_lst *menu, char *dummy, char *opt) { error_t ret = BAM_ERROR; char path[PATH_MAX]; char buf[MAX_INPUT]; struct mnttab mpref = { 0 }; struct mnttab mp = { 0 }; ficlVm *vm; char *env, *o; FILE *fp; (void) snprintf(path, PATH_MAX, "%s" TRANSIENT, bam_root); /* * if opt == NULL, remove transient config */ if (opt == NULL) { (void) unlink(path); return (BAM_SUCCESS); } fp = fopen(MNTTAB, "r"); if (fp == NULL) return (BAM_ERROR); mpref.mnt_mountp = "/"; if (getmntany(fp, &mp, &mpref) != 0) { (void) fclose(fp); return (BAM_ERROR); } (void) fclose(fp); vm = bf_init("", ficlTextOutSilent); if (vm == NULL) { bam_error(_("Error setting up forth interpreter\n")); return (ret); } /* * need to check current boot config, so fire up the ficl * if its xen setup, we add option to boot-args list, not replacing it. */ (void) snprintf(buf, MAX_INPUT, "set currdev=zfs:%s:", mp.mnt_special); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "include /boot/forth/loader.4th"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "start"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "boot"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } bf_fini(); if (opt[0] == '-') { env = getenv("xen_kernel"); fp = fopen(path, "w"); if (fp == NULL) return (BAM_ERROR); if (env != NULL) { env = getenv("boot-args"); (void) fprintf(fp, "boot-args='%s %s'\n", env, opt); } else (void) fprintf(fp, "boot-args='%s'\n", opt); (void) fclose(fp); return (BAM_SUCCESS); } /* * it should be the case with "kernel args" * so, we split the opt at first space * and store bootfile= and boot-args= */ env = getenv("xen_kernel"); o = strchr(opt, ' '); if (o == NULL) { fp = fopen(path, "w"); if (fp == NULL) return (BAM_ERROR); (void) fprintf(fp, "bootfile='%s;unix'\n", opt); (void) fclose(fp); return (BAM_SUCCESS); } *o++ = '\0'; fp = fopen(path, "w"); if (fp == NULL) return (BAM_ERROR); (void) fprintf(fp, "bootfile='%s;unix'\n", opt); if (env != NULL) { env = getenv("boot-args"); (void) fprintf(fp, "boot-args='%s %s'\n", env, o); } else (void) fprintf(fp, "boot-args='%s'\n", o); (void) fflush(fp); (void) fclose(fp); return (ret); } static error_t list_setting(struct menu_lst *menu, char *which, char *setting) { int entry = -1; menu_entry_t *m; be_node_list_t *be_nodes, *be_node = NULL; int ret; assert(which); assert(setting); /* * which can be: * "" - list default entry * number - use for entry number * property name */ if (*which != '\0') { if (isdigit(*which)) { char *rest; errno = 0; entry = strtol(which, &rest, 10); if (errno != 0 || *rest != '\0') { bam_error(_("invalid boot entry number: %s\n"), which); return (BAM_ERROR); } } else setting = which; } /* find default entry */ if (entry == -1) { ret = be_list(NULL, &be_nodes, BE_LIST_DEFAULT); if (ret != BE_SUCCESS) { bam_error(_("No BE's found\n")); return (BAM_ERROR); } STAILQ_FOREACH(m, menu, me_next) { entry++; for (be_node = be_nodes; be_node; be_node = be_node->be_next_node) { if (strcmp(be_node->be_root_ds, m->me_bootfs) == 0) break; } if (be_node != NULL && be_node->be_active_on_boot == B_TRUE) break; /* found active node */ } be_free_list(be_nodes); if (be_node == NULL) { bam_error(_("None of BE nodes is marked active\n")); return (BAM_ERROR); } } else { STAILQ_FOREACH(m, menu, me_next) if (m->me_idx == entry) break; if (m == NULL) { bam_error(_("no matching entry found\n")); return (BAM_ERROR); } } return (list_menu_entry(m, setting)); } /*ARGSUSED*/ static error_t disable_hyper(struct menu_lst *menu, char *osroot, char *opt) { char path[PATH_MAX]; (void) snprintf(path, PATH_MAX, "%s" XEN_CONFIG, bam_root); (void) unlink(path); return (BAM_SUCCESS); } /*ARGSUSED*/ static error_t enable_hyper(struct menu_lst *menu, char *osroot, char *opt) { ficlVm *vm; char path[PATH_MAX]; char buf[MAX_INPUT]; FILE *fp; struct mnttab mpref = { 0 }; struct mnttab mp = { 0 }; int ret; fp = fopen(MNTTAB, "r"); if (fp == NULL) return (BAM_ERROR); mpref.mnt_mountp = "/"; if (getmntany(fp, &mp, &mpref) != 0) { (void) fclose(fp); return (BAM_ERROR); } (void) fclose(fp); vm = bf_init("", ficlTextOutSilent); if (vm == NULL) { bam_error(_("Error setting up forth interpreter\n")); return (BAM_ERROR); } /* * need to check current boot config, so fire up the ficl * if its xen setup, we add option to boot-args list, not replacing it. */ (void) snprintf(buf, MAX_INPUT, "set currdev=zfs:%s:", mp.mnt_special); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "include /boot/forth/loader.4th"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "start"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } (void) snprintf(buf, MAX_INPUT, "boot"); ret = ficlVmEvaluate(vm, buf); if (ret != FICL_VM_STATUS_OUT_OF_TEXT) { bam_error(_("Error interpreting boot config\n")); bf_fini(); return (BAM_ERROR); } bf_fini(); (void) mkdir(CONF_DIR, 0755); (void) snprintf(path, PATH_MAX, "%s" XEN_CONFIG, bam_root); fp = fopen(path, "w"); if (fp == NULL) { return (BAM_ERROR); /* error, cant write config */ } errno = 0; /* * on write error, remove file to ensure we have bootable config. * note we dont mind if config exists, it will get updated */ /* Xen HVM support removed — write standard kernel boot config */ (void) fprintf(fp, "bootfile=\"/kernel/unix\"\n"); if (errno != 0) goto error; (void) fclose(fp); if (errno != 0) { (void) unlink(path); return (BAM_ERROR); } return (BAM_SUCCESS); error: (void) fclose(fp); (void) unlink(path); return (BAM_ERROR); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * Copyright 2017 Toomas Soome */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "bootadm.h" direct_or_multi_t bam_direct = BAM_DIRECT_NOT_SET; hv_t bam_is_hv = BAM_HV_UNKNOWN; findroot_t bam_is_findroot = BAM_FINDROOT_UNKNOWN; static void get_findroot_cap(const char *osroot) { FILE *fp; char path[PATH_MAX]; char buf[BAM_MAXLINE]; struct stat sb; int dboot; int error; int ret; const char *fcn = "get_findroot_cap()"; (void) snprintf(path, sizeof (path), "%s/%s", osroot, "boot/grub/capability"); if (stat(path, &sb) == -1) { bam_is_findroot = BAM_FINDROOT_ABSENT; BAM_DPRINTF(("%s: findroot capability absent\n", fcn)); return; } fp = fopen(path, "r"); error = errno; INJECT_ERROR1("GET_CAP_FINDROOT_FOPEN", fp = NULL); if (fp == NULL) { bam_error(_("failed to open file: %s: %s\n"), path, strerror(error)); return; } dboot = 0; while (s_fgets(buf, sizeof (buf), fp) != NULL) { if (strcmp(buf, "findroot") == 0) { BAM_DPRINTF(("%s: findroot capability present\n", fcn)); bam_is_findroot = BAM_FINDROOT_PRESENT; } if (strcmp(buf, "dboot") == 0) { BAM_DPRINTF(("%s: dboot capability present\n", fcn)); dboot = 1; } } assert(dboot); if (bam_is_findroot == BAM_FINDROOT_UNKNOWN) { bam_is_findroot = BAM_FINDROOT_ABSENT; BAM_DPRINTF(("%s: findroot capability absent\n", fcn)); } ret = fclose(fp); error = errno; INJECT_ERROR1("GET_CAP_FINDROOT_FCLOSE", ret = 1); if (ret != 0) { bam_error(_("failed to close file: %s: %s\n"), path, strerror(error)); } } error_t get_boot_cap(const char *osroot) { char fname[PATH_MAX]; char *image; uchar_t *ident; uchar_t class; int fd; int m; multiboot_header_t *mbh; struct stat sb; int error; const char *fcn = "get_boot_cap()"; if (is_sparc()) { /* there is no non dboot sparc new-boot */ bam_direct = BAM_DIRECT_DBOOT; BAM_DPRINTF(("%s: is sparc - always DBOOT\n", fcn)); return (BAM_SUCCESS); } /* * The install media can support both 64 and 32 bit boot * by using boot archive as ramdisk image. However, to save * the memory, the ramdisk may only have either 32 or 64 * bit kernel files. To avoid error message about missing unix, * we should try both variants here and only complain if neither * is found. Since the 64-bit systems are more common, we start * from amd64. */ class = ELFCLASS64; (void) snprintf(fname, PATH_MAX, "%s/%s", osroot, "kernel/unix"); fd = open(fname, O_RDONLY); error = errno; INJECT_ERROR1("GET_CAP_UNIX_OPEN", fd = -1); if (fd < 0) { bam_error(_("failed to open file: %s: %s\n"), fname, strerror(error)); return (BAM_ERROR); } /* * Verify that this is a sane unix at least 8192 bytes in length */ if (fstat(fd, &sb) == -1 || sb.st_size < 8192) { (void) close(fd); bam_error(_("invalid or corrupted binary: %s\n"), fname); return (BAM_ERROR); } /* * mmap the first 8K */ image = mmap(NULL, 8192, PROT_READ, MAP_SHARED, fd, 0); error = errno; INJECT_ERROR1("GET_CAP_MMAP", image = MAP_FAILED); if (image == MAP_FAILED) { bam_error(_("failed to mmap file: %s: %s\n"), fname, strerror(error)); return (BAM_ERROR); } ident = (uchar_t *)image; if (ident[EI_MAG0] != ELFMAG0 || ident[EI_MAG1] != ELFMAG1 || ident[EI_MAG2] != ELFMAG2 || ident[EI_MAG3] != ELFMAG3) { bam_error(_("%s is not an ELF file.\n"), fname); return (BAM_ERROR); } if (ident[EI_CLASS] != class) { bam_error(_("%s is wrong ELF class 0x%x\n"), fname, ident[EI_CLASS]); return (BAM_ERROR); } /* * The GRUB multiboot header must be 32-bit aligned and completely * contained in the 1st 8K of the file. If the unix binary has * a multiboot header, then it is a 'dboot' kernel. Otherwise, * this kernel must be booted via multiboot -- we call this a * 'multiboot' kernel. */ bam_direct = BAM_DIRECT_MULTIBOOT; for (m = 0; m < 8192 - sizeof (multiboot_header_t); m += 4) { mbh = (void *)(image + m); if (mbh->magic == MB_HEADER_MAGIC) { BAM_DPRINTF(("%s: is DBOOT unix\n", fcn)); bam_direct = BAM_DIRECT_DBOOT; break; } } (void) munmap(image, 8192); (void) close(fd); INJECT_ERROR1("GET_CAP_MULTIBOOT", bam_direct = BAM_DIRECT_MULTIBOOT); if (bam_direct == BAM_DIRECT_DBOOT) { if (bam_is_hv == BAM_HV_PRESENT) { BAM_DPRINTF(("%s: is xVM system\n", fcn)); } else { BAM_DPRINTF(("%s: is *NOT* xVM system\n", fcn)); } } else { BAM_DPRINTF(("%s: is MULTIBOOT unix\n", fcn)); } /* Not a fatal error if this fails */ get_findroot_cap(osroot); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } #define INST_RELEASE "var/sadm/system/admin/INST_RELEASE" /* * Return true if root has been bfu'ed. bfu will blow away * var/sadm/system/admin/INST_RELEASE, so if it's still there, we can * assume the system has not been bfu'ed. */ static int is_bfu_system(const char *root) { static int is_bfu = -1; char path[PATH_MAX]; struct stat sb; const char *fcn = "is_bfu_system()"; if (is_bfu != -1) { BAM_DPRINTF(("%s: already done bfu test. bfu is %s present\n", fcn, is_bfu ? "" : "NOT")); return (is_bfu); } (void) snprintf(path, sizeof (path), "%s/%s", root, INST_RELEASE); if (stat(path, &sb) != 0) { is_bfu = 1; BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); } else { is_bfu = 0; BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); } return (is_bfu); } #define MENU_URL(root) (is_bfu_system(root) ? \ "http://illumos.org/msg/SUNOS-8000-CF" : \ "http://illumos.org/msg/SUNOS-8000-AK") /* * Simply allocate a new line and copy in cmd + sep + arg */ void update_line(line_t *linep) { size_t size; const char *fcn = "update_line()"; BAM_DPRINTF(("%s: line before update: %s\n", fcn, linep->line)); free(linep->line); size = strlen(linep->cmd) + strlen(linep->sep) + strlen(linep->arg) + 1; linep->line = s_calloc(1, size); (void) snprintf(linep->line, size, "%s%s%s", linep->cmd, linep->sep, linep->arg); BAM_DPRINTF(("%s: line after update: %s\n", fcn, linep->line)); } static char * skip_wspace(char *ptr) { const char *fcn = "skip_wspace()"; INJECT_ERROR1("SKIP_WSPACE", ptr = NULL); if (ptr == NULL) { BAM_DPRINTF(("%s: NULL ptr\n", fcn)); return (NULL); } BAM_DPRINTF(("%s: ptr on entry: %s\n", fcn, ptr)); for (; *ptr != '\0'; ptr++) { if ((*ptr != ' ') && (*ptr != '\t') && (*ptr != '\n')) break; } ptr = (*ptr == '\0' ? NULL : ptr); BAM_DPRINTF(("%s: ptr on exit: %s\n", fcn, ptr ? ptr : "NULL")); return (ptr); } static char * rskip_bspace(char *bound, char *ptr) { const char *fcn = "rskip_bspace()"; assert(bound); assert(ptr); assert(bound <= ptr); assert(*bound != ' ' && *bound != '\t' && *bound != '\n'); BAM_DPRINTF(("%s: ptr on entry: %s\n", fcn, ptr)); for (; ptr > bound; ptr--) { if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') break; } BAM_DPRINTF(("%s: ptr on exit: %s\n", fcn, ptr)); return (ptr); } /* * The parse_kernel_line function examines a menu.lst kernel line. For * multiboot, this is: * * kernel * * is either /platform/i86pc/multiboot or /boot/multiboot * * may be missing, or may be any full or relative path to unix. * We check for it by looking for a word ending in "/unix". If it ends * in "kernel/unix", we upgrade it to a 32-bit entry. If it ends in * "kernel/amd64/unix", we upgrade it to the default entry. Otherwise, * it's a custom kernel, and we skip it. * * are anything that doesn't fit either of the above - these will be * copied over. * * For direct boot, the defaults are * * kernel$ * * is one of: * /platform/i86pc/kernel/$ISADIR/unix * /boot/platform/i86pc/kernel/$ISADIR/unix * /platform/i86pc/kernel/unix * /platform/i86pc/kernel/amd64/unix * /boot/platform/i86pc/kernel/unix * /boot/platform/i86pc/kernel/amd64/unix * * If is any of the last four, the command may also be "kernel". * * is anything that isn't . * * This function is only called to convert a multiboot entry to a dboot entry * * For safety, we do one more check: if the kernel path starts with /boot, * we verify that the new kernel exists before changing it. This is mainly * done for bfu, as it may cause the failsafe archives to be a different * boot architecture from the newly bfu'ed system. */ static error_t cvt_kernel_line(line_t *line, const char *osroot, entry_t *entry) { char path[PATH_MAX], path_64[PATH_MAX]; char linebuf[PATH_MAX]; char new_arg[PATH_MAX]; struct stat sb, sb_64; char *old_ptr; char *unix_ptr; char *flags1_ptr; char *flags2_ptr; const char *fcn = "cvt_kernel_line()"; BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, line->line, osroot)); /* * We only convert multiboot to dboot and nothing else. */ if (!(entry->flags & BAM_ENTRY_MULTIBOOT)) { BAM_DPRINTF(("%s: not MULTIBOOT, not converting\n", fcn)); return (BAM_SUCCESS); } if (entry->flags & BAM_ENTRY_FAILSAFE) { /* * We're attempting to change failsafe to dboot. * In the bfu case, we may not have a dboot failsafe * kernel i.e. a "unix" under the "/boot" hierarchy. * If so, just emit a message in verbose mode and * return success. */ BAM_DPRINTF(("%s: trying to convert failsafe to DBOOT\n", fcn)); (void) snprintf(path, PATH_MAX, "%s%s", osroot, DIRECT_BOOT_FAILSAFE_32); (void) snprintf(path_64, PATH_MAX, "%s%s", osroot, DIRECT_BOOT_FAILSAFE_64); if (stat(path, &sb) != 0 && stat(path_64, &sb_64) != 0) { if (bam_verbose) { bam_error(_("bootadm -m upgrade run, but the " "failsafe archives have not been\nupdated. " "Not updating line %d\n"), line->lineNum); } BAM_DPRINTF(("%s: no FAILSAFE unix, not converting\n", fcn)); return (BAM_SUCCESS); } } /* * Make sure we have the correct cmd */ free(line->cmd); line->cmd = s_strdup(menu_cmds[KERNEL_DOLLAR_CMD]); BAM_DPRINTF(("%s: converted kernel cmd to %s\n", fcn, line->cmd)); assert(sizeof (linebuf) > strlen(line->arg) + 32); (void) strlcpy(linebuf, line->arg, sizeof (linebuf)); old_ptr = strpbrk(linebuf, " \t\n"); old_ptr = skip_wspace(old_ptr); if (old_ptr == NULL) { /* * only multiboot and nothing else * i.e. flags1 = unix = flags2 = NULL */ flags1_ptr = unix_ptr = flags2_ptr = NULL; BAM_DPRINTF(("%s: NULL flags1, unix, flags2\n", fcn)) goto create; } /* * * old_ptr is either at "flags1" or "unix" */ if ((unix_ptr = strstr(old_ptr, "/unix")) != NULL) { /* * There is a unix. */ BAM_DPRINTF(("%s: unix present\n", fcn)); /* See if there's a flags2 past unix */ flags2_ptr = unix_ptr + strlen("/unix"); flags2_ptr = skip_wspace(flags2_ptr); if (flags2_ptr) { BAM_DPRINTF(("%s: flags2 present: %s\n", fcn, flags2_ptr)); } else { BAM_DPRINTF(("%s: flags2 absent\n", fcn)); } /* see if there is a flags1 before unix */ unix_ptr = rskip_bspace(old_ptr, unix_ptr); if (unix_ptr == old_ptr) { flags1_ptr = NULL; BAM_DPRINTF(("%s: flags1 absent\n", fcn)); } else { flags1_ptr = old_ptr; *unix_ptr = '\0'; unix_ptr++; BAM_DPRINTF(("%s: flags1 present: %s\n", fcn, flags1_ptr)); } } else { /* There is no unix, there is only a bunch of flags */ flags1_ptr = old_ptr; unix_ptr = flags2_ptr = NULL; BAM_DPRINTF(("%s: flags1 present: %s, unix, flags2 absent\n", fcn, flags1_ptr)); } /* * With dboot, unix is fixed and is at the beginning. We need to * migrate flags1 and flags2 */ create: if (entry->flags & BAM_ENTRY_FAILSAFE) { (void) snprintf(new_arg, sizeof (new_arg), "%s", DIRECT_BOOT_FAILSAFE_KERNEL); } else { (void) snprintf(new_arg, sizeof (new_arg), "%s", DIRECT_BOOT_KERNEL); } BAM_DPRINTF(("%s: converted unix: %s\n", fcn, new_arg)); if (flags1_ptr != NULL) { (void) strlcat(new_arg, " ", sizeof (new_arg)); (void) strlcat(new_arg, flags1_ptr, sizeof (new_arg)); } if (flags2_ptr != NULL) { (void) strlcat(new_arg, " ", sizeof (new_arg)); (void) strlcat(new_arg, flags2_ptr, sizeof (new_arg)); } BAM_DPRINTF(("%s: converted unix with flags : %s\n", fcn, new_arg)); free(line->arg); line->arg = s_strdup(new_arg); update_line(line); BAM_DPRINTF(("%s: converted line is: %s\n", fcn, line->line)); return (BAM_SUCCESS); } /* * Similar to above, except this time we're looking at a module line, * which is quite a bit simpler. * * Under multiboot, the archive line is: * * module /platform/i86pc/boot_archive * * Under directboot, the archive line is: * * module$ /platform/i86pc/$ISADIR/boot_archive * * which may be specified exactly as either of: * * module /platform/i86pc/boot_archive * module /platform/i86pc/amd64/boot_archive * * Under multiboot, the failsafe is: * * module /boot/x86.miniroot-safe * * Under dboot, the failsafe is: * * module$ /boot/$ISADIR/x86.miniroot-safe * * which may be specified exactly as either of: * * module /boot/x86.miniroot-safe * module /boot/amd64/x86.miniroot-safe */ static error_t cvt_module_line(line_t *line, entry_t *entry) { const char *fcn = "cvt_module_line()"; BAM_DPRINTF(("%s: entered. arg: %s\n", fcn, line->line)); /* * We only convert multiboot to dboot and nothing else */ if (!(entry->flags & BAM_ENTRY_MULTIBOOT)) { BAM_DPRINTF(("%s: not MULTIBOOT, not converting\n", fcn)); return (BAM_SUCCESS); } if (entry->flags & BAM_ENTRY_FAILSAFE) { if (strcmp(line->arg, FAILSAFE_ARCHIVE) == 0) { BAM_DPRINTF(("%s: failsafe module line needs no " "conversion: %s\n", fcn, line->arg)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } } else if (strcmp(line->arg, MULTIBOOT_ARCHIVE) != 0) { bam_error(_("module command on line %d not recognized.\n"), line->lineNum); BAM_DPRINTF(("%s: returning FAILURE\n", fcn)); return (BAM_MSG); } free(line->cmd); free(line->arg); line->cmd = s_strdup(menu_cmds[MODULE_DOLLAR_CMD]); line->arg = s_strdup(entry->flags & BAM_ENTRY_FAILSAFE ? FAILSAFE_ARCHIVE : DIRECT_BOOT_ARCHIVE); update_line(line); BAM_DPRINTF(("%s: converted module line is: %s\n", fcn, line->line)); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } static void bam_warn_hand_entries(menu_t *mp, char *osroot) { int hand_num; int hand_max; int *hand_list; int i; entry_t *entry; const char *fcn = "bam_warn_hand_entries()"; if (bam_force) { /* * No warning needed, we are automatically converting * the "hand" entries */ BAM_DPRINTF(("%s: force specified, no warnings about hand " "entries\n", fcn)); return; } hand_num = 0; hand_max = BAM_ENTRY_NUM; hand_list = s_calloc(1, hand_max); for (entry = mp->entries; entry; entry = entry->next) { if (entry->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU)) continue; BAM_DPRINTF(("%s: found hand entry #: %d\n", fcn, entry->entryNum)); if (++hand_num > hand_max) { hand_max *= 2; hand_list = s_realloc(hand_list, hand_max * sizeof (int)); } hand_list[hand_num - 1] = entry->entryNum; } bam_error(_("bootadm(8) will only upgrade GRUB menu entries added " "by \nbootadm(8) or lu(8). The following entries on %s will " "not be upgraded.\nFor details on manually updating entries, " "see %s\n"), osroot, MENU_URL(osroot)); bam_print_stderr("Entry Number%s: ", (hand_num > 1) ? "s" : ""); for (i = 0; i < hand_num; i++) { bam_print_stderr("%d ", hand_list[i]); } bam_print_stderr("\n"); } static entry_t * find_matching_entry( entry_t *estart, char *grubsign, char *grubroot, int root_opt) { entry_t *entry; line_t *line; char opt[10]; const char *fcn = "find_matching_entry()"; assert(grubsign); assert(root_opt == 0 || root_opt == 1); (void) snprintf(opt, sizeof (opt), "%d", root_opt); BAM_DPRINTF(("%s: entered. args: %s %s %s\n", fcn, grubsign, grubroot, opt)); for (entry = estart; entry; entry = entry->next) { if (!(entry->flags & (BAM_ENTRY_BOOTADM|BAM_ENTRY_LU)) && !bam_force) { BAM_DPRINTF(("%s: skipping hand entry #: %d\n", fcn, entry->entryNum)); continue; } if (entry->flags & BAM_ENTRY_ROOT) { for (line = entry->start; line; line = line->next) { if (line->cmd == NULL || line->arg == NULL) { if (line == entry->end) { BAM_DPRINTF(("%s: entry has " "ended\n", fcn)); break; } else { BAM_DPRINTF(("%s: skipping " "NULL line\n", fcn)); continue; } } if (strcmp(line->cmd, menu_cmds[ROOT_CMD]) == 0 && strcmp(line->arg, grubroot) == 0) { BAM_DPRINTF(("%s: found matching root " "line: %s,%s\n", fcn, line->line, grubsign)); return (entry); } if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } } } else if (entry->flags & BAM_ENTRY_FINDROOT) { for (line = entry->start; line; line = line->next) { if (line->cmd == NULL || line->arg == NULL) { if (line == entry->end) { BAM_DPRINTF(("%s: entry has " "ended\n", fcn)); break; } else { BAM_DPRINTF(("%s: skipping " "NULL line\n", fcn)); continue; } } if (strcmp(line->cmd, menu_cmds[FINDROOT_CMD]) == 0 && strcmp(line->arg, grubsign) == 0) { BAM_DPRINTF(("%s: found matching " "findroot line: %s,%s\n", fcn, line->line, grubsign)); return (entry); } if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } } } else if (root_opt) { /* Neither root nor findroot */ BAM_DPRINTF(("%s: no root or findroot and root is " "opt: %d\n", fcn, entry->entryNum)); return (entry); } } BAM_DPRINTF(("%s: no matching entry found\n", fcn)); return (NULL); } /* * The following is a set of routines that attempt to convert the * menu entries for the supplied osroot into a format compatible * with the GRUB installation on osroot. * * Each of these conversion routines make no assumptions about * the current state of the menu entry, it does its best to * convert the menu entry to the new state. In the process * we may either upgrade or downgrade. * * We don't make any heroic efforts at conversion. It is better * to be conservative and bail out at the first sign of error. We will * in such cases, point the user at the knowledge-base article * so that they can upgrade manually. */ static error_t bam_add_findroot(menu_t *mp, char *grubsign, char *grubroot, int root_opt) { entry_t *entry; line_t *line; line_t *newlp; int update_num; char linebuf[PATH_MAX]; const char *fcn = "bam_add_findroot()"; update_num = 0; bam_print(_("converting entries to findroot...\n")); entry = find_matching_entry(mp->entries, grubsign, grubroot, root_opt); while (entry != NULL) { if (entry->flags & BAM_ENTRY_FINDROOT) { /* already converted */ BAM_DPRINTF(("%s: entry %d already converted to " "findroot\n", fcn, entry->entryNum)); entry = find_matching_entry(entry->next, grubsign, grubroot, root_opt); continue; } for (line = entry->start; line; line = line->next) { if (line->cmd == NULL || line->arg == NULL) { if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } else { BAM_DPRINTF(("%s: skipping NULL line\n", fcn)); continue; } } if (strcmp(line->cmd, menu_cmds[TITLE_CMD]) == 0) { newlp = s_calloc(1, sizeof (line_t)); newlp->cmd = s_strdup(menu_cmds[FINDROOT_CMD]); newlp->sep = s_strdup(" "); newlp->arg = s_strdup(grubsign); (void) snprintf(linebuf, sizeof (linebuf), "%s%s%s", newlp->cmd, newlp->sep, newlp->arg); newlp->line = s_strdup(linebuf); bam_add_line(mp, entry, line, newlp); update_num = 1; entry->flags &= ~BAM_ENTRY_ROOT; entry->flags |= BAM_ENTRY_FINDROOT; BAM_DPRINTF(("%s: added findroot line: %s\n", fcn, newlp->line)); line = newlp; } if (strcmp(line->cmd, menu_cmds[ROOT_CMD]) == 0) { BAM_DPRINTF(("%s: freeing root line: %s\n", fcn, line->line)); unlink_line(mp, line); line_free(line); } if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } } entry = find_matching_entry(entry->next, grubsign, grubroot, root_opt); } if (update_num) { BAM_DPRINTF(("%s: updated numbering\n", fcn)); update_numbering(mp); } BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } static error_t bam_add_hv(menu_t *mp, char *grubsign, char *grubroot, int root_opt) { entry_t *entry; const char *fcn = "bam_add_hv()"; bam_print(_("adding xVM entries...\n")); entry = find_matching_entry(mp->entries, grubsign, grubroot, root_opt); while (entry != NULL) { if (entry->flags & BAM_ENTRY_HV) { BAM_DPRINTF(("%s: entry %d already converted to " "xvm HV\n", fcn, entry->entryNum)); return (BAM_SUCCESS); } entry = find_matching_entry(entry->next, grubsign, grubroot, root_opt); } (void) add_boot_entry(mp, NEW_HV_ENTRY, grubsign, XEN_MENU, XEN_KERNEL_MODULE_LINE, DIRECT_BOOT_ARCHIVE, NULL); BAM_DPRINTF(("%s: added xVM HV entry via add_boot_entry()\n", fcn)); update_numbering(mp); BAM_DPRINTF(("%s: returning SUCCESS\n", fcn)); return (BAM_SUCCESS); } static error_t bam_add_dboot( menu_t *mp, char *osroot, char *grubsign, char *grubroot, int root_opt) { int msg = 0; entry_t *entry; line_t *line; error_t ret; const char *fcn = "bam_add_dboot()"; bam_print(_("converting entries to dboot...\n")); entry = find_matching_entry(mp->entries, grubsign, grubroot, root_opt); while (entry != NULL) { for (line = entry->start; line; line = line->next) { if (line->cmd == NULL || line->arg == NULL) { if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } else { BAM_DPRINTF(("%s: skipping NULL line\n", fcn)); continue; } } /* * If we have a kernel$ command, assume it * is dboot already. If it is not a dboot * entry, something funny is going on and * we will leave it alone */ if (strcmp(line->cmd, menu_cmds[KERNEL_CMD]) == 0) { ret = cvt_kernel_line(line, osroot, entry); INJECT_ERROR1("ADD_DBOOT_KERN_ERR", ret = BAM_ERROR); INJECT_ERROR1("ADD_DBOOT_KERN_MSG", ret = BAM_MSG); if (ret == BAM_ERROR) { BAM_DPRINTF(("%s: cvt_kernel_line() " "failed\n", fcn)); return (ret); } else if (ret == BAM_MSG) { msg = 1; BAM_DPRINTF(("%s: BAM_MSG returned " "from cvt_kernel_line()\n", fcn)); } } if (strcmp(line->cmd, menu_cmds[MODULE_CMD]) == 0) { ret = cvt_module_line(line, entry); INJECT_ERROR1("ADD_DBOOT_MOD_ERR", ret = BAM_ERROR); INJECT_ERROR1("ADD_DBOOT_MOD_MSG", ret = BAM_MSG); if (ret == BAM_ERROR) { BAM_DPRINTF(("%s: cvt_module_line() " "failed\n", fcn)); return (ret); } else if (ret == BAM_MSG) { BAM_DPRINTF(("%s: BAM_MSG returned " "from cvt_module_line()\n", fcn)); msg = 1; } } if (line == entry->end) { BAM_DPRINTF(("%s: entry has ended\n", fcn)); break; } } entry = find_matching_entry(entry->next, grubsign, grubroot, root_opt); } ret = msg ? BAM_MSG : BAM_SUCCESS; BAM_DPRINTF(("%s: returning ret = %d\n", fcn, ret)); return (ret); } /*ARGSUSED*/ error_t upgrade_menu(menu_t *mp, char *osroot, char *menu_root) { char *osdev; char *grubsign; char *grubroot; int ret1; int ret2; int ret3; const char *fcn = "upgrade_menu()"; assert(osroot); assert(menu_root); BAM_DPRINTF(("%s: entered. args: %s %s\n", fcn, osroot, menu_root)); /* * We only support upgrades. Xen may not be present * on smaller metaclusters so we don't check for that. */ if (bam_is_findroot != BAM_FINDROOT_PRESENT || bam_direct != BAM_DIRECT_DBOOT) { bam_error(_("automated downgrade of GRUB menu to older " "version not supported.\n")); return (BAM_ERROR); } /* * First get the GRUB signature */ osdev = get_special(osroot); INJECT_ERROR1("UPGRADE_OSDEV", osdev = NULL); if (osdev == NULL) { bam_error(_("cant find special file for mount-point %s\n"), osroot); return (BAM_ERROR); } grubsign = get_grubsign(osroot, osdev); INJECT_ERROR1("UPGRADE_GRUBSIGN", grubsign = NULL); if (grubsign == NULL) { free(osdev); bam_error(_("cannot find GRUB signature for %s\n"), osroot); return (BAM_ERROR); } /* not fatal if we can't get grubroot */ grubroot = get_grubroot(osroot, osdev, menu_root); INJECT_ERROR1("UPGRADE_GRUBROOT", grubroot = NULL); free(osdev); ret1 = bam_add_findroot(mp, grubsign, grubroot, root_optional(osroot, menu_root)); INJECT_ERROR1("UPGRADE_ADD_FINDROOT", ret1 = BAM_ERROR); if (ret1 == BAM_ERROR) goto abort; if (bam_is_hv == BAM_HV_PRESENT) { ret2 = bam_add_hv(mp, grubsign, grubroot, root_optional(osroot, menu_root)); INJECT_ERROR1("UPGRADE_ADD_HV", ret2 = BAM_ERROR); if (ret2 == BAM_ERROR) goto abort; } else ret2 = BAM_SUCCESS; ret3 = bam_add_dboot(mp, osroot, grubsign, grubroot, root_optional(osroot, menu_root)); INJECT_ERROR1("UPGRADE_ADD_DBOOT", ret3 = BAM_ERROR); if (ret3 == BAM_ERROR) goto abort; if (ret1 == BAM_MSG || ret2 == BAM_MSG || ret3 == BAM_MSG) { bam_error(_("one or more GRUB menu entries were not " "automatically upgraded\nFor details on manually " "updating entries, see %s\n"), MENU_URL(osroot)); } else { bam_warn_hand_entries(mp, osroot); } free(grubsign); BAM_DPRINTF(("%s: returning ret = %d\n", fcn, BAM_WRITE)); return (BAM_WRITE); abort: free(grubsign); bam_error(_("error upgrading GRUB menu entries on %s. Aborting.\n" "For details on manually updating entries, see %s\n"), osroot, MENU_URL(osroot)); return (BAM_ERROR); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include "bblk_einfo.h" #include "boot_utils.h" bblk_hash_t bblk_no_hash = {BBLK_NO_HASH, 0, "(no hash)", NULL}; bblk_hash_t bblk_md5_hash = {BBLK_HASH_MD5, 0x10, "MD5", md5_calc}; bblk_hash_t *bblk_hash_list[BBLK_HASH_TOT] = { &bblk_no_hash, &bblk_md5_hash }; /* * einfo_compare_dotted_version() * Compares two strings with an arbitrary long number of dot-separated numbers. * Returns: 0 - if the version numbers are equal * 1 - if str1 version number is more recent than str2 * 2 - if str2 version number is more recent than str1 * -1 - if an error occurred * * Comparison is done field by field, by retrieving an unsigned integer value, * (missing fields are assumed as 0, but explict zeroes take precedence) so: * 4.1.2.11 > 4.1.2.2 > 4.1.2.0 > 4.1.2 * * where ">" means "more recent than". */ static int einfo_compare_dotted_version(const char *str1, const char *str2) { int retval = 0; char *verstr1, *verstr2, *freeptr1, *freeptr2; char *parsep1, *parsep2; unsigned int val_str1, val_str2; freeptr1 = verstr1 = strdup(str1); freeptr2 = verstr2 = strdup(str2); if (verstr1 == NULL || verstr2 == NULL) { retval = -1; goto out; } while (verstr1 != NULL && verstr2 != NULL) { parsep1 = strsep(&verstr1, "."); parsep2 = strsep(&verstr2, "."); val_str1 = atoi(parsep1); val_str2 = atoi(parsep2); if (val_str1 > val_str2) { retval = 1; goto out; } if (val_str2 > val_str1) { retval = 2; goto out; } } /* Common portion of the version string is equal. */ if (verstr1 == NULL && verstr2 != NULL) retval = 2; if (verstr2 == NULL && verstr1 != NULL) retval = 1; out: free(freeptr1); free(freeptr2); return (retval); } /* * einfo_compare_timestamps() * Currently, timestamp is in %Y%m%dT%H%M%SZ format in UTC, which means that * we can simply do a lexicographic comparison to know which one is the most * recent. * * Returns: 0 - if timestamps coincide * 1 - if the timestamp in str1 is more recent * 2 - if the timestamp in str2 is more recent */ static int einfo_compare_timestamps(const char *str1, const char *str2) { int retval; retval = strcmp(str1, str2); if (retval > 0) retval = 1; if (retval < 0) retval = 2; return (retval); } /* * einfo_compare_version() * Given two extended versions, compare the two and returns which one is more * "recent". Comparison is based on dotted version number fields and a * timestamp. * * Returns: -1 - on error * 0 - if the two versions coincide * 1 - if the version in str1 is more recent * 2 - if the version in str2 is more recent * * The version string generally uses following form: * self_release,build_release:timestamp * The release numbers are compared as dotted versions. * * While comparing, if the self releases are identical but the build * release is missing, this version string is considered older. * * If the release strings are identical, and one of the timestamps is missing, * we return an error. Otherwise, return the result from comparing the * timestamps. */ static int einfo_compare_version(const char *str1, const char *str2) { int retval = 0; char *verstr1, *verstr2, *freeptr1, *freeptr2; char *parsep1, *parsep2; char *timep1, *timep2; freeptr1 = verstr1 = strdup(str1); freeptr2 = verstr2 = strdup(str2); if (verstr1 == NULL || verstr2 == NULL) { retval = -1; goto out; } /* Extract the time part from the version string. */ timep1 = verstr1; timep2 = verstr2; parsep1 = strsep(&timep1, ":"); parsep2 = strsep(&timep2, ":"); while (parsep1 != NULL && parsep2 != NULL) { parsep1 = strsep(&verstr1, ",-"); parsep2 = strsep(&verstr2, ",-"); /* If both are NULL, compare timestamps */ if (parsep1 == NULL && parsep2 == NULL) break; if (parsep1 == NULL) { retval = 2; goto out; } if (parsep2 == NULL) { retval = 1; goto out; } retval = einfo_compare_dotted_version(parsep1, parsep2); if (retval == 0) continue; else goto out; } /* The dotted versions are identical, check timestamps. */ if (timep1 == NULL || timep2 == NULL) { retval = -1; goto out; } retval = einfo_compare_timestamps(timep1, timep2); out: free(freeptr1); free(freeptr2); return (retval); } /* * print_einfo() * * Print the extended information contained into the pointed structure. * 'bufsize' specifies the real size of the structure, since str_off and * hash_off need to point somewhere past the header. */ void print_einfo(uint8_t flags, bblk_einfo_t *einfo, unsigned long bufsize) { int i = 0; char *version; boolean_t has_hash = B_FALSE; unsigned char *hash = NULL; if (einfo->str_off + einfo->str_size > bufsize) { (void) fprintf(stdout, gettext("String offset %d is beyond the " "buffer size\n"), einfo->str_off); return; } version = (char *)einfo + einfo->str_off; if (einfo->hash_type != BBLK_NO_HASH && einfo->hash_type < BBLK_HASH_TOT) { if (einfo->hash_off + einfo->hash_size > bufsize) { (void) fprintf(stdout, gettext("Warning: hashing " "present but hash offset %d is beyond the buffer " "size\n"), einfo->hash_off); has_hash = B_FALSE; } else { hash = (unsigned char *)einfo + einfo->hash_off; has_hash = B_TRUE; } } if (flags & EINFO_PRINT_HEADER) { (void) fprintf(stdout, "Boot Block Extended Info Header:\n"); (void) fprintf(stdout, "\tmagic: "); for (i = 0; i < EINFO_MAGIC_SIZE; i++) (void) fprintf(stdout, "%c", einfo->magic[i]); (void) fprintf(stdout, "\n"); (void) fprintf(stdout, "\tversion: %d\n", einfo->version); (void) fprintf(stdout, "\tflags: %x\n", einfo->flags); (void) fprintf(stdout, "\textended version string offset: %d\n", einfo->str_off); (void) fprintf(stdout, "\textended version string size: %d\n", einfo->str_size); (void) fprintf(stdout, "\thashing type: %d (%s)\n", einfo->hash_type, has_hash ? bblk_hash_list[einfo->hash_type]->name : "nil"); (void) fprintf(stdout, "\thash offset: %d\n", einfo->hash_off); (void) fprintf(stdout, "\thash size: %d\n", einfo->hash_size); } if (flags & EINFO_EASY_PARSE) { (void) fprintf(stdout, "%s\n", version); } else { (void) fprintf(stdout, "Extended version string: %s\n", version); if (has_hash) { (void) fprintf(stdout, "%s hash: ", bblk_hash_list[einfo->hash_type]->name); } else { (void) fprintf(stdout, "No hashing available\n"); } } if (has_hash) { for (i = 0; i < einfo->hash_size; i++) { (void) fprintf(stdout, "%02x", hash[i]); } (void) fprintf(stdout, "\n"); } } static int compute_hash(bblk_hs_t *hs, unsigned char *dest, bblk_hash_t *hash) { if (hs == NULL || dest == NULL || hash == NULL) return (-1); hash->compute_hash(dest, hs->src_buf, hs->src_size); return (0); } int prepare_and_write_einfo(unsigned char *dest, char *infostr, bblk_hs_t *hs, uint32_t maxsize, uint32_t *used_space) { uint16_t hash_size; uint32_t hash_off; unsigned char *data; bblk_einfo_t *einfo = (bblk_einfo_t *)dest; bblk_hash_t *hashinfo = bblk_hash_list[BBLK_DEFAULT_HASH]; /* * 'dest' might be both containing the buffer we want to hash and * containing our einfo structure: delay any update of it after the * hashing has been calculated. */ hash_size = hashinfo->size; hash_off = sizeof (bblk_einfo_t); if (hash_off + hash_size > maxsize) { (void) fprintf(stderr, gettext("Unable to add extended info, " "not enough space\n")); return (-1); } data = dest + hash_off; if (compute_hash(hs, data, hashinfo) < 0) { (void) fprintf(stderr, gettext("%s hash operation failed\n"), hashinfo->name); einfo->hash_type = bblk_no_hash.type; einfo->hash_size = bblk_no_hash.size; } else { einfo->hash_type = hashinfo->type; einfo->hash_size = hashinfo->size; } (void) memcpy(einfo->magic, EINFO_MAGIC, EINFO_MAGIC_SIZE); einfo->version = BBLK_EINFO_VERSION; einfo->flags = 0; einfo->hash_off = hash_off; einfo->hash_size = hash_size; einfo->str_off = einfo->hash_off + einfo->hash_size + 1; if (infostr == NULL) { (void) fprintf(stderr, gettext("Unable to add extended info, " "string is empty\n")); return (-1); } einfo->str_size = strlen(infostr); if (einfo->str_off + einfo->str_size > maxsize) { (void) fprintf(stderr, gettext("Unable to add extended info, " "not enough space\n")); return (-1); } data = dest + einfo->str_off; (void) memcpy(data, infostr, einfo->str_size); *used_space = einfo->str_off + einfo->str_size; return (0); } /* * einfo_should_update() * Given information on the boot block currently on disk (disk_einfo) and * information on the supplied boot block (hs for hashing, verstr as the * associated version string) decide if an update of the on-disk boot block * is necessary or not. */ boolean_t einfo_should_update(bblk_einfo_t *disk_einfo, bblk_hs_t *hs, char *verstr) { bblk_hash_t *hashing; unsigned char *disk_hash; unsigned char *local_hash; char *disk_version; int retval; if (disk_einfo == NULL) return (B_TRUE); if (memcmp(disk_einfo->magic, EINFO_MAGIC, EINFO_MAGIC_SIZE) != 0) return (B_TRUE); if (disk_einfo->version < BBLK_EINFO_VERSION) return (B_TRUE); disk_version = einfo_get_string(disk_einfo); retval = einfo_compare_version(verstr, disk_version); /* * If something goes wrong or if the on-disk version is more recent * do not update the bootblock. */ if (retval == -1 || retval == 2) return (B_FALSE); /* * If we got here it means that the two version strings are either * equal or the new bootblk binary is more recent. In order to save * some needless writes let's use the hash to determine if an update * is really necessary. */ if (disk_einfo->hash_type == bblk_no_hash.type) return (B_TRUE); if (disk_einfo->hash_type >= BBLK_HASH_TOT) return (B_TRUE); hashing = bblk_hash_list[disk_einfo->hash_type]; local_hash = malloc(hashing->size); if (local_hash == NULL) return (B_TRUE); /* * Failure in computing the hash may mean something wrong * with the boot block file. Better be conservative here. */ if (compute_hash(hs, local_hash, hashing) < 0) { free(local_hash); return (B_FALSE); } disk_hash = (unsigned char *)einfo_get_hash(disk_einfo); if (memcmp(local_hash, disk_hash, disk_einfo->hash_size) == 0) { free(local_hash); return (B_FALSE); } free(local_hash); return (B_TRUE); } char * einfo_get_string(bblk_einfo_t *einfo) { if (einfo == NULL) return (NULL); return ((char *)einfo + einfo->str_off); } char * einfo_get_hash(bblk_einfo_t *einfo) { if (einfo == NULL) return (NULL); return ((char *)einfo + einfo->hash_off); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ #ifndef _BBLKEINFO_H #define _BBLKEINFO_H #ifdef __cplusplus extern "C" { #endif #include #include #include #include #define BBLK_EINFO_VERSION (1) #define EINFO_MAGIC "EXTINFO" #define EINFO_MAGIC_SIZE (7) #pragma pack(1) typedef struct _extended_info { char magic[EINFO_MAGIC_SIZE]; uint8_t version; uint8_t flags; uint32_t str_off; uint16_t str_size; uint8_t hash_type; uint32_t hash_off; uint16_t hash_size; char rsvd[32]; } bblk_einfo_t; #pragma pack() enum bblk_hash_types_t { BBLK_NO_HASH = 0, BBLK_HASH_MD5, BBLK_HASH_TOT }; #define EINFO_PRINT_HEADER 0x01 #define EINFO_EASY_PARSE 0x02 typedef struct _hashing_function { unsigned int type; unsigned int size; char name[16]; void (*compute_hash)(void *, const void *, unsigned int); } bblk_hash_t; typedef struct _hashing_source { unsigned char *src_buf; unsigned int src_size; } bblk_hs_t; #define BBLK_DEFAULT_HASH BBLK_HASH_MD5 extern bblk_hash_t bblk_no_hash; extern bblk_hash_t bblk_md5_hash; extern bblk_hash_t *bblk_hash_list[BBLK_HASH_TOT]; void print_einfo(uint8_t, bblk_einfo_t *, unsigned long); int prepare_and_write_einfo(unsigned char *, char *, bblk_hs_t *, uint32_t, uint32_t *); boolean_t einfo_should_update(bblk_einfo_t *, bblk_hs_t *, char *); char *einfo_get_string(bblk_einfo_t *); char *einfo_get_hash(bblk_einfo_t *); #ifdef __cplusplus } #endif #endif /* _BBLKEINFO_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ #include #include #include #include #include #include "bblk_einfo.h" #include "boot_utils.h" boolean_t boot_debug = B_FALSE; boolean_t nowrite = B_FALSE; void boot_gdebug(const char *funcname, char *format, ...) { va_list ap; if (boot_debug == B_FALSE) return; (void) fprintf(stdout, "%s(): ", funcname); va_start(ap, format); /* LINTED: E_SEC_PRINTF_VAR_FMT */ (void) vfprintf(stdout, format, ap); va_end(ap); } /* * Common functions to write out and read in block-sized data to a file * descriptor. */ int write_out(int fd, void *buffer, size_t size, off_t off) { int ret; char *buf = buffer; if (size % SECTOR_SIZE != 0) BOOT_DEBUG("Expected block-sized data, got: %d\n", size); /* Dry run. */ if (nowrite) return (BC_SUCCESS); for (;;) { again: ret = pwrite(fd, buf, size, off); if (ret == -1) { if (errno == EAGAIN) goto again; else return (BC_ERROR); } if (ret < size) { size -= ret; off += ret; buf += ret; } else { break; } } return (BC_SUCCESS); } int read_in(int fd, void *buffer, size_t size, off_t off) { int ret; char *buf = buffer; if (size % SECTOR_SIZE != 0) BOOT_DEBUG("Expected block-sized data, got: %d\n", size); for (;;) { again: ret = pread(fd, buf, size, off); if (ret == -1) { if (errno == EAGAIN) goto again; else return (BC_ERROR); } if (ret < size) { size -= ret; off += ret; buf += ret; } else { break; } } return (BC_SUCCESS); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ #ifndef _BOOT_UTILS_H #define _BOOT_UTILS_H #ifdef __cplusplus extern "C" { #endif #include #include #include "bblk_einfo.h" /* Common return values for various operations. */ #define BC_SUCCESS (0) #define BC_ERROR (1) #define BC_NOUPDT (4) #define BC_NOEXTRA (5) #define BC_NOEINFO (6) #define SECTOR_SIZE (512) extern boolean_t boot_debug; extern boolean_t nowrite; #define BOOT_DEBUG(...) boot_gdebug(__func__, __VA_ARGS__) void boot_gdebug(const char *, char *, ...); int write_out(int, void *, size_t, off_t); int read_in(int, void *, size_t, off_t); #ifdef __cplusplus } #endif #endif /* _BOOT_UTILS_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Nexenta Systems, Inc. All rights reserved. */ #include #include #include #include #include #include #include #include "bblk_einfo.h" #include "boot_utils.h" #include "mboot_extra.h" /* * Common functions to deal with the fake-multiboot encapsulation of the * bootblock and the location of the extra information area. */ /* mboot checksum routine. */ uint32_t compute_checksum(char *data, uint32_t size) { uint32_t *ck_ptr; uint32_t cksum = 0; int i; ck_ptr = (uint32_t *)data; for (i = 0; i < size; i += sizeof (uint32_t)) cksum += *ck_ptr++; return (-cksum); } /* Given a buffer, look for a multiboot header within it. */ int find_multiboot(char *buffer, uint32_t buf_size, uint32_t *mboot_off) { multiboot_header_t *mboot; uint32_t *iter; uint32_t cksum; uint32_t boundary; int i = 0; iter = (uint32_t *)buffer; *mboot_off = 0; /* multiboot header has to be within the first 32K. */ boundary = MBOOT_SCAN_SIZE; if (boundary > buf_size) boundary = buf_size; boundary = boundary - sizeof (multiboot_header_t); for (i = 0; i < boundary; i += 4, iter++) { mboot = (multiboot_header_t *)iter; if (mboot->magic != MB_HEADER_MAGIC) continue; /* Found magic signature -- check checksum. */ cksum = -(mboot->flags + mboot->magic); if (mboot->checksum != cksum) { BOOT_DEBUG("multiboot magic found at %p, but checksum " "mismatches (is %x, should be %x)\n", mboot, mboot->checksum, cksum); continue; } else { if (!(mboot->flags & BB_MBOOT_AOUT_FLAG)) { BOOT_DEBUG("multiboot structure found, but no " "AOUT kludge specified, skipping.\n"); continue; } else { /* proper multiboot structure found. */ *mboot_off = i; return (BC_SUCCESS); } } } return (BC_ERROR); } /* * Given a pointer to the extra information area (a sequence of bb_header_ext_t * + payload chunks), find the extended information structure. */ bblk_einfo_t * find_einfo(char *extra, uint32_t size) { bb_header_ext_t *ext_header; bblk_einfo_t *einfo; uint32_t cksum; assert(extra != NULL); ext_header = (bb_header_ext_t *)extra; if (ext_header->size > size) { BOOT_DEBUG("Unable to find extended versioning information, " "data size too big\n"); return (NULL); } cksum = compute_checksum(extra + sizeof (bb_header_ext_t), ext_header->size); BOOT_DEBUG("Extended information header checksum is %x\n", cksum); if (cksum != ext_header->checksum) { BOOT_DEBUG("Unable to find extended versioning information, " "data looks corrupted\n"); return (NULL); } /* * Currently we only have one extra header so it must be encapsulating * the extended information structure. */ einfo = (bblk_einfo_t *)(extra + sizeof (bb_header_ext_t)); if (memcmp(einfo->magic, EINFO_MAGIC, EINFO_MAGIC_SIZE) != 0) { BOOT_DEBUG("Unable to read stage2 extended versioning " "information, wrong magic identifier\n"); BOOT_DEBUG("Found %s, expected %s\n", einfo->magic, EINFO_MAGIC); return (NULL); } return (einfo); } /* * Given a pointer to the extra area, add the extended information structure * encapsulated by a bb_header_ext_t structure. */ void add_einfo(char *extra, char *updt_str, bblk_hs_t *hs, uint32_t avail_space) { bb_header_ext_t *ext_hdr; uint32_t used_space; unsigned char *dest; int ret; assert(extra != NULL); if (updt_str == NULL) { BOOT_DEBUG("WARNING: no update string passed to " "add_stage2_einfo()\n"); return; } /* Reserve space for the extra header. */ ext_hdr = (bb_header_ext_t *)extra; dest = (unsigned char *)extra + sizeof (*ext_hdr); /* Place the extended information structure. */ ret = prepare_and_write_einfo(dest, updt_str, hs, avail_space, &used_space); if (ret != 0) { (void) fprintf(stderr, gettext("Unable to write the extended " "versioning information\n")); return; } /* Fill the extended information associated header. */ ext_hdr->size = P2ROUNDUP(used_space, 8); ext_hdr->checksum = compute_checksum((char *)dest, ext_hdr->size); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Nexenta Systems, Inc. All rights reserved. */ #ifndef _MBOOT_EXTRA_H #define _MBOOT_EXTRA_H #ifdef __cplusplus extern "C" { #endif #include #include #include "bblk_einfo.h" /* multiboot header needs to be located in the first 64KB. */ #define MBOOT_SCAN_SIZE (64 * 1024) /* multiboot header AOUT_KLUDGE flag. */ #define BB_MBOOT_AOUT_FLAG (0x00010000) /* Extra header preceeding the payloads at the end of the bootblock. */ typedef struct _bb_extra_header { uint32_t size; uint32_t checksum; } bb_header_ext_t; uint32_t compute_checksum(char *, uint32_t); bblk_einfo_t *find_einfo(char *, uint32_t); int find_multiboot(char *, uint32_t, uint32_t *); void add_einfo(char *, char *, bblk_hs_t *, uint32_t); int compare_bootblocks(char *, char *, char **); #ifdef __cplusplus } #endif #endif /* _MBOOT_EXTRA_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Hammerhead: amd64-only SUBDIRS = $(MACH64) all : TARGET= all install : TARGET= install clean : TARGET= clean clobber : TARGET= clobber _msg : TARGET= _msg lint : TARGET= lint .KEEP_STATE: install: $(SUBDIRS) all clobber clean lint _msg: FRC: $(SUBDIRS): FRC @cd $@; pwd; $(MAKE) $(TARGET) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # # # Common prologue for /boot/solaris filelist generation # # # filelists # DATA= \ filelist.ramdisk \ filelist.safe include $(SRC)/cmd/boot/Makefile.com # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # # # Common epilogue for /boot/solaris filelist generation # include $(SRC)/cmd/boot/Makefile.targ # # This file and its contents are supplied under the terms of the # Common Development and Distribution License ("CDDL"), version 1.0. # Copyright 2025 Hammerhead Project # include ../Makefile.com include $(SRC)/cmd/Makefile.cmd.64 # Hammerhead: filelist data files (filelist.ramdisk, filelist.safe) are not # present in this tree. Provide empty targets to avoid build errors. all: install: all include ../Makefile.targ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Copyright (c) 2018, Joyent, Inc. PROG= fiocompress SBINLINKS= $(PROG) OBJS= fiocompress.o SRCS = $(OBJS:.o=.c) include ../Makefile.com .KEEP_STATE: LDLIBS += -lz CFLAGS += -I../../../uts/common SMOFF += leaks all: $(PROG) $(PROG): $(OBJS) $(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(POST_PROCESS) install: all $(ROOTSBINPROG) .WAIT $(ROOTUSRSBINLINKS) clean: -$(RM) $(OBJS) _msg: include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * fiocompress - a utility to compress files with a filesystem. * Used to build compressed boot archives to reduce memory * requirements for booting. */ #include #include #include #include #include #include #include #include #include #include #include #include #include "message.h" static void setup_infile(char *); static void setup_outfile(char *); static void do_comp(size_t); static void do_decomp(void); static caddr_t srcaddr; static size_t srclen; static int dstfd; static char *srcfile; static char *dstfile; int main(int argc, char **argv) { int compress = 0; int decompress = 0; int doioc = 0; size_t blksize = 8192; int c; while ((c = getopt(argc, argv, "mcdb:")) != -1) { switch (c) { case 'm': doioc++; break; case 'c': if (decompress) { (void) fprintf(stderr, OPT_DC_EXCL); exit(-1); } compress = 1; break; case 'd': if (compress) { (void) fprintf(stderr, OPT_DC_EXCL); exit(-1); } decompress = 1; break; case 'b': blksize = atoi(optarg); if (blksize == 0 || (blksize & (blksize-1))) { (void) fprintf(stderr, INVALID_BLKSZ); exit(-1); } break; case '?': (void) fprintf(stderr, UNKNOWN_OPTION, optopt); exit(-1); } } if (argc - optind != 2) { (void) fprintf(stderr, MISS_FILES); exit(-1); } setup_infile(argv[optind]); setup_outfile(argv[optind + 1]); if (decompress) do_decomp(); else { do_comp(blksize); if (doioc) { if (ioctl(dstfd, _FIO_COMPRESSED, 0) == -1) { (void) fprintf(stderr, FIO_COMP_FAIL, dstfile, strerror(errno)); exit(-1); } } } return (0); } static void setup_infile(char *file) { int fd; void *addr; struct stat stbuf; srcfile = file; fd = open(srcfile, O_RDONLY, 0); if (fd == -1) { (void) fprintf(stderr, CANT_OPEN, srcfile, strerror(errno)); exit(-1); } if (fstat(fd, &stbuf) == -1) { (void) fprintf(stderr, STAT_FAIL, srcfile, strerror(errno)); exit(-1); } srclen = stbuf.st_size; addr = mmap(0, srclen, PROT_READ, MAP_SHARED, fd, 0); if (addr == MAP_FAILED) { (void) fprintf(stderr, MMAP_FAIL, srcfile, strerror(errno)); exit(-1); } srcaddr = addr; } static void setup_outfile(char *file) { int fd; dstfile = file; fd = open(dstfile, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { (void) fprintf(stderr, OPEN_FAIL, dstfile, strerror(errno)); exit(-1); } dstfd = fd; } static void do_comp(size_t blksize) { struct comphdr *hdr; off_t offset; size_t blks, dstlen, hlen; void *dstbuf; int i; blks = ((srclen - 1) / blksize) + 1; hlen = offset = sizeof (struct comphdr) + blks * sizeof (uint64_t); hdr = malloc(hlen); if (hdr == NULL) { (void) fprintf(stderr, HDR_ALLOC, hlen); exit(-1); } hdr->ch_magic = CH_MAGIC_ZLIB; hdr->ch_version = CH_VERSION; hdr->ch_algorithm = CH_ALG_ZLIB; hdr->ch_fsize = srclen; hdr->ch_blksize = blksize; dstlen = ZMAXBUF(blksize); dstbuf = malloc(dstlen); if (dstbuf == NULL) { (void) fprintf(stderr, BUF_ALLOC, dstlen); exit(-1); } if (lseek(dstfd, offset, SEEK_SET) == (off_t)-1) { (void) fprintf(stderr, SEEK_ERR, offset, dstfile, strerror(errno)); exit(-1); } for (i = 0; i < blks; i++) { ulong_t slen, dlen; int ret; hdr->ch_blkmap[i] = offset; slen = MIN(srclen, blksize); dlen = dstlen; ret = compress2(dstbuf, &dlen, (Bytef *)srcaddr, slen, 9); if (ret != Z_OK) { (void) fprintf(stderr, COMP_ERR, srcfile, ret); exit(-1); } if (write(dstfd, dstbuf, dlen) != dlen) { (void) fprintf(stderr, WRITE_ERR, dlen, dstfile, strerror(errno)); exit(-1); } offset += dlen; srclen -= slen; srcaddr += slen; } if (lseek(dstfd, 0, SEEK_SET) == (off_t)-1) { (void) fprintf(stderr, SEEK_ERR, 0, dstfile, strerror(errno)); exit(-1); } if (write(dstfd, hdr, hlen) != hlen) { (void) fprintf(stderr, WRITE_ERR, hlen, dstfile, strerror(errno)); exit(-1); } } static void do_decomp() { struct comphdr *hdr; size_t blks, blksize; void *dstbuf; int i; ulong_t slen, dlen; int ret; hdr = (struct comphdr *)(void *)srcaddr; if (hdr->ch_magic != CH_MAGIC_ZLIB) { (void) fprintf(stderr, BAD_MAGIC, srcfile, (uint64_t)hdr->ch_magic, CH_MAGIC_ZLIB); exit(-1); } if (hdr->ch_version != CH_VERSION) { (void) fprintf(stderr, BAD_VERS, srcfile, (uint64_t)hdr->ch_version, CH_VERSION); exit(-1); } if (hdr->ch_algorithm != CH_ALG_ZLIB) { (void) fprintf(stderr, BAD_ALG, srcfile, (uint64_t)hdr->ch_algorithm, CH_ALG_ZLIB); exit(-1); } blksize = hdr->ch_blksize; dstbuf = malloc(blksize); if (dstbuf == NULL) { (void) fprintf(stderr, HDR_ALLOC, blksize); exit(-1); } blks = (hdr->ch_fsize - 1) / blksize; srcaddr += hdr->ch_blkmap[0]; for (i = 0; i < blks; i++) { dlen = blksize; slen = hdr->ch_blkmap[i + 1] - hdr->ch_blkmap[i]; ret = uncompress(dstbuf, &dlen, (Bytef *)srcaddr, slen); if (ret != Z_OK) { (void) fprintf(stderr, DECOMP_ERR, srcfile, ret); exit(-1); } if (dlen != blksize) { (void) fprintf(stderr, CORRUPT, srcfile); exit(-1); } if (write(dstfd, dstbuf, dlen) != dlen) { (void) fprintf(stderr, WRITE_ERR, dlen, dstfile, strerror(errno)); exit(-1); } srcaddr += slen; } dlen = blksize; slen = hdr->ch_fsize - hdr->ch_blkmap[i]; if ((ret = uncompress(dstbuf, &dlen, (Bytef *)srcaddr, slen)) != Z_OK) { (void) fprintf(stderr, DECOMP_ERR, dstfile, ret); exit(-1); } if (write(dstfd, dstbuf, dlen) != dlen) { (void) fprintf(stderr, WRITE_ERR, dlen, dstfile, strerror(errno)); exit(-1); } } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _MESSAGE_H #define _MESSAGE_H #ifdef __cplusplus extern "C" { #endif #include #define OPT_DC_EXCL gettext("fiocompress: -c and -d are exclusive\n") #define INVALID_BLKSZ gettext("fiocompress: invalid block size\n") #define UNKNOWN_OPTION gettext("fiocompress: unknown option -%c\n") #define MISS_FILES gettext("fiocompress: input and output files\ must be specified\n") #define FIO_COMP_FAIL gettext("fiocompress: FIO_COMPRESSED on %s failed\ - %s\n") #define CANT_OPEN gettext("fiocompress: cannot open %s - %s\n") #define STAT_FAIL gettext("fiocompress: stat of %s failed - %s\n") #define MMAP_FAIL gettext("fiocompress: mmapping on %s failed - %s\n") #define OPEN_FAIL gettext("fiocompress: open of %s failed - %s\n") #define HDR_ALLOC gettext("fiocompress: failed to allocate %d bytes\ for header\n") #define BUF_ALLOC gettext("fiocompress: failed to allocate %d bytes\ for buffer\n") #define SEEK_ERR gettext("fiocompress: seek to %ld on %s failed - %s\n") #define COMP_ERR gettext("fiocompress: %s - compression error %d\n") #define WRITE_ERR gettext("fiocompress: write of %ld bytes on %s failed\ - %s\n") #define BAD_MAGIC gettext("fiocompress: %s - bad magic (0x%llx/0x%x)\n") #define BAD_VERS gettext("fiocompress: %s - bad version (0x%llx/0x%x)\n") #define BAD_ALG gettext("fiocompress: %s - bad algorithm\ (0x%llx/0x%x)\n") #define DECOMP_ERR gettext("fiocompress: %s - decompression error %d\n") #define CORRUPT gettext("fiocompress: %s - corrupt file\n") #ifdef __cplusplus } #endif #endif /* _MESSAGE_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2016 Toomas Soome # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Hammerhead: amd64-only SUBDIRS = $(MACH64) all : TARGET= all install : TARGET= install clean : TARGET= clean clobber : TARGET= clobber _msg : TARGET= _msg lint : TARGET= lint .KEEP_STATE: install: $(SUBDIRS) all clobber clean lint _msg: $(SUBDIRS) FRC: $(SUBDIRS): FRC @cd $@; pwd; $(MAKE) $(TARGET) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. # Copyright 2016 Toomas Soome # PROG= installboot EINFO_SRC =../../common/bblk_einfo.c UTILS_SRC =../../common/boot_utils.c EXTRA_SRC =../../common/mboot_extra.c OBJS= installboot.o bblk_einfo.o boot_utils.o mboot_extra.o include ../../Makefile.com CPPFLAGS += -I$(SRC)/uts/common LDLIBS += -lmd5 CSTD= $(CSTD_GNU99) .KEEP_STATE: all: $(PROG) $(PROG): $(OBJS) $(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(POST_PROCESS) boot_utils.o: $(UTILS_SRC) $(COMPILE.c) -o $@ $(UTILS_SRC) mboot_extra.o: $(EXTRA_SRC) $(COMPILE.c) -o $@ $(EXTRA_SRC) bblk_einfo.o: $(EINFO_SRC) $(COMPILE.c) -o $@ $(EINFO_SRC) install: all $(ROOTUSRSBINPROG) clean: $(RM) $(OBJS) include $(SRC)/cmd/Makefile.targ # # This file and its contents are supplied under the terms of the # Common Development and Distribution License ("CDDL"), version 1.0. # You may only use this file in accordance with the terms of version # 1.0 of the CDDL. # # A full copy of the text of the CDDL should have accompanied this # source. A copy of the CDDL is also available via the Internet at # http://www.illumos.org/license/CDDL. # # Copyright 2025 Hammerhead Project # include ../Makefile.com include $(SRC)/cmd/Makefile.cmd.64 install: all $(ROOTPROG64) /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Nexenta Systems, Inc. All rights reserved. * Copyright 2016 Toomas Soome * Copyright 2025 Hammerhead Project */ #ifndef _INSTALLBOOT_H #define _INSTALLBOOT_H #ifdef __cplusplus extern "C" { #endif #include #include #include #include #define SECTOR_SIZE (512) /* partitioning type for device */ typedef enum ib_devtype { IB_DEV_UNKNOWN = 0, IB_DEV_VTOC, IB_DEV_MBR, IB_DEV_EFI } ib_devtype_t; /* file system type */ typedef enum ib_fstype { IB_FS_NONE = 0, IB_FS_ZFS, IB_FS_UFS, IB_FS_PCFS } ib_fstype_t; /* boot block type */ typedef enum ib_bblktype { IB_BBLK_FILE, IB_BBLK_MBR, /* MBR/PMBR */ IB_BBLK_STAGE1, /* BIOS stage 1 */ IB_BBLK_STAGE2, /* BIOS stage 2 */ IB_BBLK_EFI /* EFI Boot Program */ } ib_bblktype_t; /* partition info for boot block location. */ struct stage_part { char *path; /* device name */ char *mntpnt; /* mountpoint for stage fs */ int id; /* partition/slice number */ ib_devtype_t devtype; /* partitioning type */ ib_fstype_t fstype; uint16_t tag; /* partition tag */ uint64_t start; /* partition LBA */ uint64_t size; /* partition size */ uint64_t offset; /* block offset */ }; /* boot device data */ typedef struct _ib_device { ib_devtype_t devtype; struct stage_part stage; /* location of boot block */ struct stage_part target; /* target file system */ } ib_device_t; /* stage 2 location */ typedef struct _ib_bootblock { char *buf; char *file; char *extra; multiboot_header_t *mboot; uint32_t mboot_off; uint32_t file_size; uint32_t buf_size; uint32_t extra_size; } ib_bootblock_t; struct partlist; struct part_cb { bool (*read)(struct partlist *); bool (*read_bbl)(struct partlist *); bool (*compare)(struct partlist *); void (*install)(void *, struct partlist *); void (*print)(struct partlist *); }; struct partlist { char *pl_devname; ib_device_t *pl_device; /* boot block type */ ib_bblktype_t pl_type; /* stage from target disk, either stage1 or stage2 */ void *pl_stage; /* name of the source file */ const char *pl_src_name; /* stage data from source file. */ void *pl_src_data; struct part_cb pl_cb; STAILQ_ENTRY(partlist) pl_next; }; typedef STAILQ_HEAD(part_list, partlist) part_list_t; typedef struct _ib_data { ib_device_t device; /* boot device */ ib_bootblock_t bootblock; /* stage 2 */ struct stage_part target; /* target file system */ part_list_t *plist; /* boot blocks */ } ib_data_t; #define BBLK_BLKLIST_OFF 50 /* vtoc/disk boot offset sectors */ #define BBLK_ZFS_BLK_OFF (1 << 19) /* vdev boot offset bytes */ #define BBLK_ZFS_BLK_SIZE (7ULL << 19) /* vdev max boot size bytes */ /* locations of MBR parts, must be reviewd if mbr code is changed */ #define STAGE1_BPB_OFFSET (0x3) /* technically BPB starts at 0xb */ #define STAGE1_BPB_BPS (0xb) /* Bytes Per Sector */ #define STAGE1_BPB_SIZE (0x3b) #define STAGE1_MBR_VERSION (0xfa) /* 2 bytes, not used */ #define STAGE1_STAGE2_SIZE (0xfc) /* 16bits */ #define STAGE1_STAGE2_LBA (0xfe) /* 64bits */ #define STAGE1_STAGE2_UUID (0x106) /* 128bits */ #define STAGE1_SIG (0x1b8) /* 4+2 bytes */ #define STAGE1_PARTTBL (0x1be) /* MBR partition table */ #define STAGE1_MAGIC (0x1fe) /* 0xAA55 */ #ifdef __cplusplus } #endif #endif /* _INSTALLBOOT_H */ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. # Copyright 2015, Nexenta Systems, Inc. # Copyright (c) 2018, Joyent, Inc. PROG= installgrub PCFS_SRC= $(SRC)/common/fs/pcfs.c EINFO_SRC= ./../common/bblk_einfo.c UTILS_SRC =./../common/boot_utils.c EXTRA_SRC =./../common/mboot_extra.c OBJS= installgrub.o pcfs_glue.o pcfs.o bblk_einfo.o boot_utils.o mboot_extra.o \ getresponse.o SBINLINKS= $(PROG) include ../Makefile.com CPPFLAGS += -I$(SRC)/uts/i86pc -I$(SRC)/uts/intel -I$(SRC)/uts/common CPPFLAGS += -I$(SRC)/common/util # not linted SMATCH=off LDLIBS += -lmd5 i386_CFLAGS += -D_LARGEFILE64_SOURCE i386_CFLAGS += -D_FILE_OFFSET_BITS=64 LDLIBS += -lfdisk -lefi -lfstyp CSTD= $(CSTD_GNU99) .KEEP_STATE: all: $(PROG) $(PROG): $(OBJS) $(LINK.c) -o $@ $(OBJS) $(LDLIBS) $(POST_PROCESS) # pick pcfs from usr/src/common/fs pcfs.o: $(PCFS_SRC) $(COMPILE.c) -o $@ $(PCFS_SRC) boot_utils.o: $(UTILS_SRC) $(COMPILE.c) -o $@ $(UTILS_SRC) mboot_extra.o: $(EXTRA_SRC) $(COMPILE.c) -o $@ $(EXTRA_SRC) bblk_einfo.o: $(EINFO_SRC) $(COMPILE.c) -o $@ $(EINFO_SRC) %.o: $(SRC)/common/util/%.c $(COMPILE.c) $(OUTPUT_OPTION) $< install: all $(ROOTSBINPROG) .WAIT $(ROOTUSRSBINLINKS) clean: $(RM) $(OBJS) include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2012 Milan Jurik. All rights reserved. * Copyright 2016 Toomas Soome * Copyright 2016 Nexenta Systems, Inc. All rights reserved. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "message.h" #include "installgrub.h" #include "./../common/bblk_einfo.h" #include "./../common/boot_utils.h" #include "./../common/mboot_extra.h" #include "getresponse.h" #ifndef TEXT_DOMAIN #define TEXT_DOMAIN "SUNW_OST_OSCMD" #endif /* * Variables to track installgrub desired mode of operation. * 'nowrite' and 'boot_debug' come from boot_common.h. */ static boolean_t write_mbr = B_FALSE; static boolean_t force_mbr = B_FALSE; static boolean_t force_update = B_FALSE; static boolean_t do_getinfo = B_FALSE; static boolean_t do_version = B_FALSE; static boolean_t do_mirror_bblk = B_FALSE; static boolean_t strip = B_FALSE; static boolean_t verbose_dump = B_FALSE; /* Installing the bootblock is the default operation. */ static boolean_t do_install = B_TRUE; /* Versioning string, if present. */ static char *update_str; /* * Temporary buffer to store the first 32K of data looking for a multiboot * signature. */ char mboot_scan[MBOOT_SCAN_SIZE]; /* Function prototypes. */ static void check_options(char *); static int handle_install(char *, char **); static int handle_mirror(char *, char **); static int handle_getinfo(char *, char **); static int commit_to_disk(ig_data_t *, char *); static int init_device(ig_device_t *, char *path); static void cleanup_device(ig_device_t *); static void cleanup_stage2(ig_stage2_t *); static int get_start_sector(ig_device_t *); static int get_disk_fd(ig_device_t *device); static int get_raw_partition_fd(ig_device_t *); static char *get_raw_partition_path(ig_device_t *); static int propagate_bootblock(ig_data_t *, ig_data_t *, char *); static int find_x86_bootpar(struct mboot *, int *, uint32_t *); static int write_stage2(ig_data_t *); static int write_stage1(ig_data_t *); static void usage(char *); static int read_stage1_from_file(char *, ig_data_t *); static int read_stage2_from_file(char *, ig_data_t *); static int read_stage1_from_disk(int, char *); static int read_stage2_from_disk(int, ig_stage2_t *, int); static int prepare_stage1(ig_data_t *); static int prepare_stage2(ig_data_t *, char *); static void prepare_fake_multiboot(ig_stage2_t *); static void add_stage2_einfo(ig_stage2_t *, char *updt_str); static boolean_t is_update_necessary(ig_data_t *, char *); extern int read_stage2_blocklist(int, unsigned int *); int main(int argc, char *argv[]) { int opt; int params = 3; int ret; char **handle_args; char *progname; (void) setlocale(LC_ALL, ""); (void) textdomain(TEXT_DOMAIN); if (init_yes() < 0) { (void) fprintf(stderr, gettext(ERR_MSG_INIT_YES), strerror(errno)); exit(BC_ERROR); } /* * retro-compatibility: installing the bootblock is the default * and there is no switch for it. */ do_install = B_TRUE; while ((opt = getopt(argc, argv, "dVMFfmneiu:")) != EOF) { switch (opt) { case 'm': write_mbr = B_TRUE; break; case 'n': nowrite = B_TRUE; break; case 'f': force_mbr = B_TRUE; break; case 'i': do_getinfo = B_TRUE; do_install = B_FALSE; params = 1; break; case 'V': verbose_dump = B_TRUE; break; case 'd': boot_debug = B_TRUE; break; case 'F': force_update = B_TRUE; break; case 'e': strip = B_TRUE; break; case 'M': do_mirror_bblk = B_TRUE; do_install = B_FALSE; params = 2; break; case 'u': do_version = B_TRUE; update_str = malloc(strlen(optarg) + 1); if (update_str == NULL) { (void) fprintf(stderr, gettext("Unable to " "allocate memory\n")); exit(BC_ERROR); } (void) strlcpy(update_str, optarg, strlen(optarg) + 1); break; default: /* fall through to process non-optional args */ break; } } /* check arguments */ if (argc != optind + params) { usage(argv[0]); exit(BC_ERROR); } /* * clean up options (and bail out if an unrecoverable combination is * requested. */ progname = argv[0]; check_options(progname); handle_args = argv + optind; if (nowrite) (void) fprintf(stdout, DRY_RUN); if (do_getinfo) { ret = handle_getinfo(progname, handle_args); } else if (do_mirror_bblk) { ret = handle_mirror(progname, handle_args); } else { ret = handle_install(progname, handle_args); } return (ret); } #define MEANINGLESS_OPT gettext("%s specified but meaningless, ignoring\n") static void check_options(char *progname) { if (do_getinfo && do_mirror_bblk) { (void) fprintf(stderr, gettext("Only one of -M and -i can be " "specified at the same time\n")); usage(progname); exit(BC_ERROR); } if (do_mirror_bblk) { /* * -u and -F may actually reflect a user intent that is not * correct with this command (mirror can be interpreted * "similar" to install. Emit a message and continue. * -e and -V have no meaning, be quiet here and only report the * incongruence if a debug output is requested. */ if (do_version) { (void) fprintf(stderr, MEANINGLESS_OPT, "-u"); do_version = B_FALSE; } if (force_update) { (void) fprintf(stderr, MEANINGLESS_OPT, "-F"); force_update = B_FALSE; } if (strip || verbose_dump) { BOOT_DEBUG(MEANINGLESS_OPT, "-e|-V"); strip = B_FALSE; verbose_dump = B_FALSE; } } if (do_getinfo) { if (write_mbr || force_mbr || do_version || force_update) { BOOT_DEBUG(MEANINGLESS_OPT, "-m|-f|-u|-F"); write_mbr = force_mbr = do_version = B_FALSE; force_update = B_FALSE; } } } /* * Install a new stage1/stage2 pair on the specified device. handle_install() * expects argv to contain 3 parameters (the path to stage1, the path to stage2, * the target device). * * Returns: BC_SUCCESS - if the installation is successful * BC_ERROR - if the installation failed * BC_NOUPDT - if no installation was performed because the GRUB * version currently installed is more recent than the * supplied one. * */ static int handle_install(char *progname, char **argv) { ig_data_t install_data; char *stage1_path = NULL; char *stage2_path = NULL; char *device_path = NULL; int ret = BC_ERROR; stage1_path = strdup(argv[0]); stage2_path = strdup(argv[1]); device_path = strdup(argv[2]); bzero(&install_data, sizeof (ig_data_t)); if (!stage1_path || !stage2_path || !device_path) { (void) fprintf(stderr, gettext("Missing parameter")); usage(progname); goto out; } BOOT_DEBUG("stage1 path: %s, stage2 path: %s, device: %s\n", stage1_path, stage2_path, device_path); if (init_device(&install_data.device, device_path) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Unable to gather device " "information for %s\n"), device_path); goto out; } /* read in stage1 and stage2. */ if (read_stage1_from_file(stage1_path, &install_data) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error opening %s\n"), stage1_path); goto out_dev; } if (read_stage2_from_file(stage2_path, &install_data) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error opening %s\n"), stage2_path); goto out_dev; } /* We do not support versioning on PCFS. */ if (is_bootpar(install_data.device.type) && do_version) do_version = B_FALSE; /* * is_update_necessary() will take care of checking if versioning and/or * forcing the update have been specified. It will also emit a warning * if a non-versioned update is attempted over a versioned bootblock. */ if (!is_update_necessary(&install_data, update_str)) { (void) fprintf(stderr, gettext("GRUB version installed " "on %s is more recent or identical\n" "Use -F to override or install without the -u option\n"), device_path); ret = BC_NOUPDT; goto out_dev; } /* * We get here if: * - the installed GRUB version is older than the one about to be * installed. * - no versioning string has been passed through the command line. * - a forced update is requested (-F). */ BOOT_DEBUG("Ready to commit to disk\n"); ret = commit_to_disk(&install_data, update_str); out_dev: cleanup_device(&install_data.device); out: free(stage1_path); free(stage2_path); free(device_path); return (ret); } /* * Retrieves from a device the extended information (einfo) associated to the * installed stage2. * Expects one parameter, the device path, in the form: /dev/rdsk/c?[t?]d?s0. * Returns: * - BC_SUCCESS (and prints out einfo contents depending on 'flags') * - BC_ERROR (on error) * - BC_NOEINFO (no extended information available) */ static int handle_getinfo(char *progname, char **argv) { ig_data_t data; ig_stage2_t *stage2 = &data.stage2; ig_device_t *device = &data.device; bblk_einfo_t *einfo; uint8_t flags = 0; uint32_t size; char *device_path; int retval = BC_ERROR; int ret; device_path = strdup(argv[0]); if (!device_path) { (void) fprintf(stderr, gettext("Missing parameter")); usage(progname); goto out; } bzero(&data, sizeof (ig_data_t)); BOOT_DEBUG("device path: %s\n", device_path); if (init_device(device, device_path) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Unable to gather device " "information for %s\n"), device_path); goto out_dev; } if (is_bootpar(device->type)) { (void) fprintf(stderr, gettext("Versioning not supported on " "PCFS\n")); goto out_dev; } ret = read_stage2_from_disk(device->part_fd, stage2, device->type); if (ret == BC_ERROR) { (void) fprintf(stderr, gettext("Error reading stage2 from " "%s\n"), device_path); goto out_dev; } if (ret == BC_NOEXTRA) { (void) fprintf(stdout, gettext("No multiboot header found on " "%s, unable to locate extra information area\n"), device_path); retval = BC_NOEINFO; goto out_dev; } einfo = find_einfo(stage2->extra, stage2->extra_size); if (einfo == NULL) { retval = BC_NOEINFO; (void) fprintf(stderr, gettext("No extended information " "found\n")); goto out_dev; } /* Print the extended information. */ if (strip) flags |= EINFO_EASY_PARSE; if (verbose_dump) flags |= EINFO_PRINT_HEADER; size = stage2->buf_size - P2ROUNDUP(stage2->file_size, 8); print_einfo(flags, einfo, size); retval = BC_SUCCESS; out_dev: cleanup_device(&data.device); out: free(device_path); return (retval); } /* * Attempt to mirror (propagate) the current stage2 over the attaching disk. * * Returns: * - BC_SUCCESS (a successful propagation happened) * - BC_ERROR (an error occurred) * - BC_NOEXTRA (it is not possible to dump the current bootblock since * there is no multiboot information) */ static int handle_mirror(char *progname, char **argv) { ig_data_t curr_data; ig_data_t attach_data; ig_device_t *curr_device = &curr_data.device; ig_device_t *attach_device = &attach_data.device; ig_stage2_t *stage2_curr = &curr_data.stage2; ig_stage2_t *stage2_attach = &attach_data.stage2; bblk_einfo_t *einfo_curr = NULL; char *curr_device_path; char *attach_device_path; char *updt_str = NULL; int retval = BC_ERROR; int ret; curr_device_path = strdup(argv[0]); attach_device_path = strdup(argv[1]); if (!curr_device_path || !attach_device_path) { (void) fprintf(stderr, gettext("Missing parameter")); usage(progname); goto out; } BOOT_DEBUG("Current device path is: %s, attaching device path is: " " %s\n", curr_device_path, attach_device_path); bzero(&curr_data, sizeof (ig_data_t)); bzero(&attach_data, sizeof (ig_data_t)); if (init_device(curr_device, curr_device_path) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Unable to gather device " "information for %s (current device)\n"), curr_device_path); goto out_currdev; } if (init_device(attach_device, attach_device_path) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Unable to gather device " "information for %s (attaching device)\n"), attach_device_path); goto out_devs; } if (is_bootpar(curr_device->type) || is_bootpar(attach_device->type)) { (void) fprintf(stderr, gettext("boot block mirroring is not " "supported on PCFS\n")); goto out_devs; } ret = read_stage2_from_disk(curr_device->part_fd, stage2_curr, curr_device->type); if (ret == BC_ERROR) { BOOT_DEBUG("Error reading first stage2 blocks from %s\n", curr_device->path); retval = BC_ERROR; goto out_devs; } if (ret == BC_NOEXTRA) { BOOT_DEBUG("No multiboot header found on %s, unable to grab " "stage2\n", curr_device->path); retval = BC_NOEXTRA; goto out_devs; } einfo_curr = find_einfo(stage2_curr->extra, stage2_curr->extra_size); if (einfo_curr != NULL) updt_str = einfo_get_string(einfo_curr); write_mbr = B_TRUE; force_mbr = B_TRUE; retval = propagate_bootblock(&curr_data, &attach_data, updt_str); cleanup_stage2(stage2_curr); cleanup_stage2(stage2_attach); out_devs: cleanup_device(attach_device); out_currdev: cleanup_device(curr_device); out: free(curr_device_path); free(attach_device_path); return (retval); } static int commit_to_disk(ig_data_t *install, char *updt_str) { assert(install != NULL); /* * vanilla stage1 and stage2 need to be updated at runtime. * Update stage2 before stage1 because stage1 needs to know the first * sector stage2 will be written to. */ if (prepare_stage2(install, updt_str) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error building stage2\n")); return (BC_ERROR); } if (prepare_stage1(install) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error building stage1\n")); return (BC_ERROR); } /* Write stage2 out to disk. */ if (write_stage2(install) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error writing stage2 to " "disk\n")); return (BC_ERROR); } /* Write stage1 to disk and, if requested, to the MBR. */ if (write_stage1(install) != BC_SUCCESS) { (void) fprintf(stderr, gettext("Error writing stage1 to " "disk\n")); return (BC_ERROR); } return (BC_SUCCESS); } /* * Propagate the bootblock on the source disk to the destination disk and * version it with 'updt_str' in the process. Since we cannot trust any data * on the attaching disk, we do not perform any specific check on a potential * target extended information structure and we just blindly update. */ static int propagate_bootblock(ig_data_t *source, ig_data_t *target, char *updt_str) { ig_device_t *src_device = &source->device; ig_device_t *dest_device = &target->device; ig_stage2_t *src_stage2 = &source->stage2; ig_stage2_t *dest_stage2 = &target->stage2; uint32_t buf_size; int retval; assert(source != NULL); assert(target != NULL); /* read in stage1 from the source disk. */ if (read_stage1_from_disk(src_device->part_fd, target->stage1_buf) != BC_SUCCESS) return (BC_ERROR); /* Prepare target stage2 for commit_to_disk. */ cleanup_stage2(dest_stage2); if (updt_str != NULL) do_version = B_TRUE; else do_version = B_FALSE; buf_size = src_stage2->file_size + SECTOR_SIZE; dest_stage2->buf_size = P2ROUNDUP(buf_size, SECTOR_SIZE); dest_stage2->buf = malloc(dest_stage2->buf_size); if (dest_stage2->buf == NULL) { perror(gettext("Memory allocation failed")); return (BC_ERROR); } dest_stage2->file = dest_stage2->buf; dest_stage2->file_size = src_stage2->file_size; memcpy(dest_stage2->file, src_stage2->file, dest_stage2->file_size); dest_stage2->extra = dest_stage2->buf + P2ROUNDUP(dest_stage2->file_size, 8); /* If we get down here we do have a mboot structure. */ assert(src_stage2->mboot); dest_stage2->mboot_off = src_stage2->mboot_off; dest_stage2->mboot = (multiboot_header_t *)(dest_stage2->buf + dest_stage2->mboot_off); (void) fprintf(stdout, gettext("Propagating %s stage1/stage2 to %s\n"), src_device->path, dest_device->path); retval = commit_to_disk(target, updt_str); return (retval); } /* * open the device and fill the various members of ig_device_t. */ static int init_device(ig_device_t *device, char *path) { struct dk_gpt *vtoc; fstyp_handle_t fhdl; const char *fident; bzero(device, sizeof (*device)); device->part_fd = -1; device->disk_fd = -1; device->path_p0 = NULL; device->path = strdup(path); if (device->path == NULL) { perror(gettext("Memory allocation failed")); return (BC_ERROR); } if (strstr(device->path, "diskette")) { (void) fprintf(stderr, gettext("installing GRUB to a floppy " "disk is no longer supported\n")); return (BC_ERROR); } /* Detect if the target device is a pcfs partition. */ if (strstr(device->path, "p0:boot")) device->type = IG_DEV_X86BOOTPAR; if (get_disk_fd(device) != BC_SUCCESS) return (BC_ERROR); /* read in the device boot sector. */ if (read(device->disk_fd, device->boot_sector, SECTOR_SIZE) != SECTOR_SIZE) { (void) fprintf(stderr, gettext("Error reading boot sector\n")); perror("read"); return (BC_ERROR); } if (efi_alloc_and_read(device->disk_fd, &vtoc) >= 0) { device->type = IG_DEV_EFI; efi_free(vtoc); } if (get_raw_partition_fd(device) != BC_SUCCESS) return (BC_ERROR); if (is_efi(device->type)) { if (fstyp_init(device->part_fd, 0, NULL, &fhdl) != 0) return (BC_ERROR); if (fstyp_ident(fhdl, "zfs", &fident) != 0) { fstyp_fini(fhdl); (void) fprintf(stderr, gettext("Booting of EFI labeled " "disks is only supported with ZFS\n")); return (BC_ERROR); } fstyp_fini(fhdl); } if (get_start_sector(device) != BC_SUCCESS) return (BC_ERROR); return (BC_SUCCESS); } static void cleanup_device(ig_device_t *device) { if (device->path) free(device->path); if (device->path_p0) free(device->path_p0); if (device->part_fd != -1) (void) close(device->part_fd); if (device->disk_fd != -1) (void) close(device->disk_fd); bzero(device, sizeof (ig_device_t)); device->part_fd = -1; device->disk_fd = -1; } static void cleanup_stage2(ig_stage2_t *stage2) { if (stage2->buf) free(stage2->buf); bzero(stage2, sizeof (ig_stage2_t)); } static int get_start_sector(ig_device_t *device) { uint32_t secnum = 0, numsec = 0; int i, pno, rval, log_part = 0; struct mboot *mboot; struct ipart *part = NULL; ext_part_t *epp; struct part_info dkpi; struct extpart_info edkpi; if (is_efi(device->type)) { struct dk_gpt *vtoc; if (efi_alloc_and_read(device->disk_fd, &vtoc) < 0) return (BC_ERROR); device->start_sector = vtoc->efi_parts[device->slice].p_start; /* GPT doesn't use traditional slice letters */ device->partition = device->slice; device->slice = 0xff; efi_free(vtoc); goto found_part; } mboot = (struct mboot *)device->boot_sector; if (is_bootpar(device->type)) { if (find_x86_bootpar(mboot, &pno, &secnum) != BC_SUCCESS) { (void) fprintf(stderr, NOBOOTPAR); return (BC_ERROR); } else { device->start_sector = secnum; device->partition = pno; goto found_part; } } /* * Search for Solaris fdisk partition * Get the solaris partition information from the device * and compare the offset of S2 with offset of solaris partition * from fdisk partition table. */ if (ioctl(device->part_fd, DKIOCEXTPARTINFO, &edkpi) < 0) { if (ioctl(device->part_fd, DKIOCPARTINFO, &dkpi) < 0) { (void) fprintf(stderr, PART_FAIL); return (BC_ERROR); } else { edkpi.p_start = dkpi.p_start; } } for (i = 0; i < FD_NUMPART; i++) { part = (struct ipart *)mboot->parts + i; if (part->relsect == 0) { (void) fprintf(stderr, BAD_PART, i); return (BC_ERROR); } if (edkpi.p_start >= part->relsect && edkpi.p_start < (part->relsect + part->numsect)) { /* Found the partition */ break; } } if (i == FD_NUMPART) { /* No solaris fdisk partitions (primary or logical) */ (void) fprintf(stderr, NOSOLPAR); return (BC_ERROR); } /* * We have found a Solaris fdisk partition (primary or extended) * Handle the simple case first: Solaris in a primary partition */ if (!fdisk_is_dos_extended(part->systid)) { device->start_sector = part->relsect; device->partition = i; goto found_part; } /* * Solaris in a logical partition. Find that partition in the * extended part. */ if ((rval = libfdisk_init(&epp, device->path_p0, NULL, FDISK_READ_DISK)) != FDISK_SUCCESS) { switch (rval) { /* * The first 3 cases are not an error per-se, just that * there is no Solaris logical partition */ case FDISK_EBADLOGDRIVE: case FDISK_ENOLOGDRIVE: case FDISK_EBADMAGIC: (void) fprintf(stderr, NOSOLPAR); return (BC_ERROR); case FDISK_ENOVGEOM: (void) fprintf(stderr, NO_VIRT_GEOM); return (BC_ERROR); case FDISK_ENOPGEOM: (void) fprintf(stderr, NO_PHYS_GEOM); return (BC_ERROR); case FDISK_ENOLGEOM: (void) fprintf(stderr, NO_LABEL_GEOM); return (BC_ERROR); default: (void) fprintf(stderr, LIBFDISK_INIT_FAIL); return (BC_ERROR); } } rval = fdisk_get_solaris_part(epp, &pno, &secnum, &numsec); libfdisk_fini(&epp); if (rval != FDISK_SUCCESS) { /* No solaris logical partition */ (void) fprintf(stderr, NOSOLPAR); return (BC_ERROR); } device->start_sector = secnum; device->partition = pno - 1; log_part = 1; found_part: /* get confirmation for -m */ if (write_mbr && !force_mbr) { (void) fprintf(stdout, MBOOT_PROMPT); if (!yes()) { write_mbr = 0; (void) fprintf(stdout, MBOOT_NOT_UPDATED); return (BC_ERROR); } } /* * Currently if Solaris is in an extended partition we need to * write GRUB to the MBR. Check for this. */ if (log_part && !write_mbr) { (void) fprintf(stdout, gettext("Installing Solaris on an " "extended partition... forcing MBR update\n")); write_mbr = 1; } /* * warn, if Solaris in primary partition and GRUB not in MBR and * partition is not active */ if (part != NULL) { if (!log_part && part->bootid != 128 && !write_mbr) { (void) fprintf(stdout, SOLPAR_INACTIVE, device->partition + 1); } } return (BC_SUCCESS); } static int get_disk_fd(ig_device_t *device) { int i = 0; char save[2] = { '\0', '\0' }; char *end = NULL; assert(device != NULL); assert(device->path != NULL); if (is_bootpar(device->type)) { end = strstr(device->path, "p0:boot"); /* tested at the start of init_device() */ assert(end != NULL); /* chop off :boot */ save[0] = end[2]; end[2] = '\0'; } else { i = strlen(device->path); save[0] = device->path[i - 2]; save[1] = device->path[i - 1]; device->path[i - 2] = 'p'; device->path[i - 1] = '0'; } if (nowrite) device->disk_fd = open(device->path, O_RDONLY); else device->disk_fd = open(device->path, O_RDWR); device->path_p0 = strdup(device->path); if (device->path_p0 == NULL) { perror("strdup"); return (BC_ERROR); } if (is_bootpar(device->type)) { end[2] = save[0]; } else { device->path[i - 2] = save[0]; device->path[i - 1] = save[1]; } if (device->disk_fd == -1) { perror("open"); return (BC_ERROR); } return (BC_SUCCESS); } static void prepare_fake_multiboot(ig_stage2_t *stage2) { multiboot_header_t *mboot; assert(stage2 != NULL); assert(stage2->mboot != NULL); assert(stage2->buf != NULL); mboot = stage2->mboot; /* * Currently we expect find_multiboot() to have located a multiboot * header with the AOUT kludge flag set. */ assert(mboot->flags & BB_MBOOT_AOUT_FLAG); /* Insert the information necessary to locate stage2. */ mboot->header_addr = stage2->mboot_off; mboot->load_addr = 0; mboot->load_end_addr = stage2->file_size; } static void add_stage2_einfo(ig_stage2_t *stage2, char *updt_str) { bblk_hs_t hs; uint32_t avail_space; assert(stage2 != NULL); /* Fill bootblock hashing source information. */ hs.src_buf = (unsigned char *)stage2->file; hs.src_size = stage2->file_size; /* How much space for the extended information structure? */ avail_space = stage2->buf_size - P2ROUNDUP(stage2->file_size, 8); add_einfo(stage2->extra, updt_str, &hs, avail_space); } static int write_stage2(ig_data_t *install) { ig_device_t *device = &install->device; ig_stage2_t *stage2 = &install->stage2; off_t offset; assert(install != NULL); if (is_bootpar(device->type)) { /* * stage2 is already on the filesystem, we only need to update * the first two blocks (that we have modified during * prepare_stage2()) */ if (write_out(device->part_fd, stage2->file, SECTOR_SIZE, stage2->pcfs_first_sectors[0] * SECTOR_SIZE) != BC_SUCCESS || write_out(device->part_fd, stage2->file + SECTOR_SIZE, SECTOR_SIZE, stage2->pcfs_first_sectors[1] * SECTOR_SIZE) != BC_SUCCESS) { (void) fprintf(stderr, WRITE_FAIL_STAGE2); return (BC_ERROR); } (void) fprintf(stdout, WRITE_STAGE2_PCFS); return (BC_SUCCESS); } /* * For disk, write stage2 starting at STAGE2_BLKOFF sector. * Note that we use stage2->buf rather than stage2->file, because we * may have extended information after the latter. * * If we're writing to an EFI-labeled disk where stage2 lives in the * 3.5MB boot loader gap following the ZFS vdev labels, make sure the * size of the buffer doesn't exceed the size of the gap. */ if (is_efi(device->type) && stage2->buf_size > STAGE2_MAXSIZE) { (void) fprintf(stderr, WRITE_FAIL_STAGE2); return (BC_ERROR); } offset = STAGE2_BLKOFF(device->type) * SECTOR_SIZE; if (write_out(device->part_fd, stage2->buf, stage2->buf_size, offset) != BC_SUCCESS) { perror("write"); return (BC_ERROR); } /* Simulate the "old" installgrub output. */ (void) fprintf(stdout, WRITE_STAGE2_DISK, device->partition, (stage2->buf_size / SECTOR_SIZE) + 1, STAGE2_BLKOFF(device->type), stage2->first_sector); return (BC_SUCCESS); } static int write_stage1(ig_data_t *install) { ig_device_t *device = &install->device; assert(install != NULL); if (write_out(device->part_fd, install->stage1_buf, sizeof (install->stage1_buf), 0) != BC_SUCCESS) { (void) fprintf(stdout, WRITE_FAIL_PBOOT); perror("write"); return (BC_ERROR); } /* Simulate "old" installgrub output. */ (void) fprintf(stdout, WRITE_PBOOT, device->partition, device->start_sector); if (write_mbr) { if (write_out(device->disk_fd, install->stage1_buf, sizeof (install->stage1_buf), 0) != BC_SUCCESS) { (void) fprintf(stdout, WRITE_FAIL_BOOTSEC); perror("write"); return (BC_ERROR); } /* Simulate "old" installgrub output. */ (void) fprintf(stdout, WRITE_MBOOT); } return (BC_SUCCESS); } #define USAGE_STRING "%s [-m|-f|-n|-F|-u verstr] stage1 stage2 device\n" \ "%s -M [-n] device1 device2\n" \ "%s [-V|-e] -i device\n" \ #define CANON_USAGE_STR gettext(USAGE_STRING) static void usage(char *progname) { (void) fprintf(stdout, CANON_USAGE_STR, progname, progname, progname); } static int read_stage1_from_file(char *path, ig_data_t *dest) { int fd; assert(dest); /* read the stage1 file from filesystem */ fd = open(path, O_RDONLY); if (fd == -1 || read(fd, dest->stage1_buf, SECTOR_SIZE) != SECTOR_SIZE) { (void) fprintf(stderr, READ_FAIL_STAGE1, path); return (BC_ERROR); } (void) close(fd); return (BC_SUCCESS); } static int read_stage2_from_file(char *path, ig_data_t *dest) { int fd; struct stat sb; ig_stage2_t *stage2 = &dest->stage2; ig_device_t *device = &dest->device; uint32_t buf_size; assert(dest); assert(stage2->buf == NULL); fd = open(path, O_RDONLY); if (fstat(fd, &sb) == -1) { perror("fstat"); goto out; } stage2->file_size = sb.st_size; if (!is_bootpar(device->type)) { /* * buffer size needs to account for stage2 plus the extra * versioning information at the end of it. We reserve one * extra sector (plus we round up to the next sector boundary). */ buf_size = stage2->file_size + SECTOR_SIZE; } else { /* In the PCFS case we only need to read in stage2. */ buf_size = stage2->file_size; } stage2->buf_size = P2ROUNDUP(buf_size, SECTOR_SIZE); BOOT_DEBUG("stage2 buffer size = %d (%d sectors)\n", stage2->buf_size, stage2->buf_size / SECTOR_SIZE); stage2->buf = malloc(stage2->buf_size); if (stage2->buf == NULL) { perror(gettext("Memory allocation failed")); goto out_fd; } stage2->file = stage2->buf; /* * Extra information (e.g. the versioning structure) is placed at the * end of stage2, aligned on a 8-byte boundary. */ if (!(is_bootpar(device->type))) stage2->extra = stage2->file + P2ROUNDUP(stage2->file_size, 8); if (lseek(fd, 0, SEEK_SET) == -1) { perror("lseek"); goto out_alloc; } if (read(fd, stage2->file, stage2->file_size) < 0) { perror(gettext("unable to read stage2")); goto out_alloc; } (void) close(fd); return (BC_SUCCESS); out_alloc: free(stage2->buf); stage2->buf = NULL; out_fd: (void) close(fd); out: return (BC_ERROR); } static int prepare_stage1(ig_data_t *install) { ig_device_t *device = &install->device; assert(install != NULL); /* If PCFS add the BIOS Parameter Block. */ if (is_bootpar(device->type)) { char bpb_sect[SECTOR_SIZE]; if (pread(device->part_fd, bpb_sect, SECTOR_SIZE, 0) != SECTOR_SIZE) { (void) fprintf(stderr, READ_FAIL_BPB); return (BC_ERROR); } bcopy(bpb_sect + STAGE1_BPB_OFFSET, install->stage1_buf + STAGE1_BPB_OFFSET, STAGE1_BPB_SIZE); } /* copy MBR to stage1 in case of overwriting MBR sector. */ bcopy(device->boot_sector + BOOTSZ, install->stage1_buf + BOOTSZ, SECTOR_SIZE - BOOTSZ); /* modify default stage1 file generated by GRUB. */ *((unsigned char *)(install->stage1_buf + STAGE1_FORCE_LBA)) = 1; *((ulong_t *)(install->stage1_buf + STAGE1_STAGE2_SECTOR)) = install->stage2.first_sector; *((ushort_t *)(install->stage1_buf + STAGE1_STAGE2_ADDRESS)) = STAGE2_MEMADDR; *((ushort_t *)(install->stage1_buf + STAGE1_STAGE2_SEGMENT)) = STAGE2_MEMADDR >> 4; return (BC_SUCCESS); } /* * Grab stage1 from the specified device file descriptor. */ static int read_stage1_from_disk(int dev_fd, char *stage1_buf) { assert(stage1_buf != NULL); if (read_in(dev_fd, stage1_buf, SECTOR_SIZE, 0) != BC_SUCCESS) { perror(gettext("Unable to read stage1 from disk")); return (BC_ERROR); } return (BC_SUCCESS); } static int read_stage2_from_disk(int dev_fd, ig_stage2_t *stage2, int type) { uint32_t size; uint32_t buf_size; uint32_t mboot_off; multiboot_header_t *mboot; assert(stage2 != NULL); assert(dev_fd != -1); if (read_in(dev_fd, mboot_scan, sizeof (mboot_scan), STAGE2_BLKOFF(type) * SECTOR_SIZE) != BC_SUCCESS) { perror(gettext("Error reading stage2 sectors")); return (BC_ERROR); } /* No multiboot means no chance of knowing stage2 size */ if (find_multiboot(mboot_scan, sizeof (mboot_scan), &mboot_off) != BC_SUCCESS) { BOOT_DEBUG("Unable to find multiboot header\n"); return (BC_NOEXTRA); } mboot = (multiboot_header_t *)(mboot_scan + mboot_off); /* * Unfilled mboot values mean an older version of installgrub installed * the stage2. Again we have no chance of knowing stage2 size. */ if (mboot->load_end_addr == 0 || mboot->load_end_addr < mboot->load_addr) return (BC_NOEXTRA); /* * Currently, the amount of space reserved for extra information * is "fixed". We may have to scan for the terminating extra payload * in the future. */ size = mboot->load_end_addr - mboot->load_addr; buf_size = P2ROUNDUP(size + SECTOR_SIZE, SECTOR_SIZE); stage2->buf = malloc(buf_size); if (stage2->buf == NULL) { perror(gettext("Memory allocation failed")); return (BC_ERROR); } stage2->buf_size = buf_size; if (read_in(dev_fd, stage2->buf, buf_size, STAGE2_BLKOFF(type) * SECTOR_SIZE) != BC_SUCCESS) { perror("read"); free(stage2->buf); return (BC_ERROR); } /* Update pointers. */ stage2->file = stage2->buf; stage2->file_size = size; stage2->mboot_off = mboot_off; stage2->mboot = (multiboot_header_t *)(stage2->buf + stage2->mboot_off); stage2->extra = stage2->buf + P2ROUNDUP(stage2->file_size, 8); stage2->extra_size = stage2->buf_size - P2ROUNDUP(stage2->file_size, 8); return (BC_SUCCESS); } static boolean_t is_update_necessary(ig_data_t *data, char *updt_str) { bblk_einfo_t *einfo; bblk_hs_t stage2_hs; ig_stage2_t stage2_disk; ig_stage2_t *stage2_file = &data->stage2; ig_device_t *device = &data->device; int dev_fd = device->part_fd; assert(data != NULL); assert(device->part_fd != -1); bzero(&stage2_disk, sizeof (ig_stage2_t)); /* Gather stage2 (if present) from the target device. */ if (read_stage2_from_disk(dev_fd, &stage2_disk, device->type) != BC_SUCCESS) { BOOT_DEBUG("Unable to read stage2 from %s\n", device->path); BOOT_DEBUG("No multiboot wrapped stage2 on %s\n", device->path); return (B_TRUE); } /* * Look for the extended information structure in the extra payload * area. */ einfo = find_einfo(stage2_disk.extra, stage2_disk.extra_size); if (einfo == NULL) { BOOT_DEBUG("No extended information available\n"); return (B_TRUE); } if (!do_version || updt_str == NULL) { (void) fprintf(stdout, "WARNING: target device %s has a " "versioned stage2 that is going to be overwritten by a non " "versioned one\n", device->path); return (B_TRUE); } if (force_update) { BOOT_DEBUG("Forcing update of %s bootblock\n", device->path); return (B_TRUE); } /* Compare the two extended information structures. */ stage2_hs.src_buf = (unsigned char *)stage2_file->file; stage2_hs.src_size = stage2_file->file_size; return (einfo_should_update(einfo, &stage2_hs, updt_str)); } #define START_BLOCK(pos) (*(ulong_t *)(pos)) #define NUM_BLOCK(pos) (*(ushort_t *)((pos) + 4)) #define START_SEG(pos) (*(ushort_t *)((pos) + 6)) static int prepare_stage2(ig_data_t *install, char *updt_str) { ig_device_t *device = &install->device; ig_stage2_t *stage2 = &install->stage2; uint32_t mboot_off = 0; assert(install != NULL); assert(stage2->file != NULL); /* New stage2 files come with an embedded stage2. */ if (find_multiboot(stage2->file, stage2->file_size, &mboot_off) != BC_SUCCESS) { BOOT_DEBUG("WARNING: no multiboot structure found in stage2, " "are you using an old GRUB stage2?\n"); if (do_version == B_TRUE) { (void) fprintf(stderr, gettext("Versioning requested " "but stage2 does not support it.. skipping.\n")); do_version = B_FALSE; } } else { /* Keep track of where the multiboot header is. */ stage2->mboot_off = mboot_off; stage2->mboot = (multiboot_header_t *)(stage2->file + mboot_off); if (do_version) { /* * Adding stage2 information needs to happen before * we modify the copy of stage2 we have in memory, so * that the hashing reflects the one of the file. * An error here is not fatal. */ add_stage2_einfo(stage2, updt_str); } /* * Fill multiboot information. We add them even without * versioning to support as much as possible mirroring. */ prepare_fake_multiboot(stage2); } if (is_bootpar(device->type)) { uint32_t blocklist[SECTOR_SIZE / sizeof (uint32_t)]; uint32_t install_addr = STAGE2_MEMADDR + SECTOR_SIZE; int i = 0; uchar_t *pos; bzero(blocklist, sizeof (blocklist)); if (read_stage2_blocklist(device->part_fd, blocklist) != 0) { (void) fprintf(stderr, gettext("Error reading pcfs " "stage2 blocklist\n")); return (BC_ERROR); } pos = (uchar_t *)stage2->file + STAGE2_BLOCKLIST; stage2->first_sector = device->start_sector + blocklist[0]; stage2->pcfs_first_sectors[0] = blocklist[0]; BOOT_DEBUG("stage2 first sector: %d\n", stage2->first_sector); if (blocklist[1] > 1) { blocklist[0]++; blocklist[1]--; } else { i += 2; } stage2->pcfs_first_sectors[1] = blocklist[i]; while (blocklist[i]) { if (START_BLOCK(pos - 8) != 0 && START_BLOCK(pos - 8) != blocklist[i + 2]) { (void) fprintf(stderr, PCFS_FRAGMENTED); return (BC_ERROR); } START_BLOCK(pos) = blocklist[i] + device->start_sector; START_SEG(pos) = (ushort_t)(install_addr >> 4); NUM_BLOCK(pos) = blocklist[i + 1]; install_addr += blocklist[i + 1] * SECTOR_SIZE; pos -= 8; i += 2; } } else { /* Solaris VTOC & EFI */ if (device->start_sector > UINT32_MAX - STAGE2_BLKOFF(device->type)) { fprintf(stderr, gettext("Error: partition start sector " "must be less than %lld\n"), (uint64_t)UINT32_MAX - STAGE2_BLKOFF(device->type)); return (BC_ERROR); } stage2->first_sector = device->start_sector + STAGE2_BLKOFF(device->type); BOOT_DEBUG("stage2 first sector: %d\n", stage2->first_sector); /* * In a solaris partition, stage2 is written to contiguous * blocks. So we update the starting block only. */ *((ulong_t *)(stage2->file + STAGE2_BLOCKLIST)) = stage2->first_sector + 1; } /* force lba and set disk partition */ *((unsigned char *) (stage2->file + STAGE2_FORCE_LBA)) = 1; *((long *)(stage2->file + STAGE2_INSTALLPART)) = (device->partition << 16) | (device->slice << 8) | 0xff; return (BC_SUCCESS); } static int find_x86_bootpar(struct mboot *mboot, int *part_num, uint32_t *start_sect) { int i; for (i = 0; i < FD_NUMPART; i++) { struct ipart *part; part = (struct ipart *)mboot->parts + i; if (part->systid == 0xbe) { if (start_sect) *start_sect = part->relsect; if (part_num) *part_num = i; /* solaris boot part */ return (BC_SUCCESS); } } return (BC_ERROR); } static char * get_raw_partition_path(ig_device_t *device) { char *raw; int len; if (is_bootpar(device->type)) { int part; struct mboot *mboot; mboot = (struct mboot *)device->boot_sector; if (find_x86_bootpar(mboot, &part, NULL) != BC_SUCCESS) { (void) fprintf(stderr, BOOTPAR_NOTFOUND, device->path_p0); return (NULL); } raw = strdup(device->path_p0); if (raw == NULL) { perror(gettext("Memory allocation failed")); return (NULL); } raw[strlen(raw) - 2] = '1' + part; return (raw); } /* For disk, remember slice and return whole fdisk partition */ raw = strdup(device->path); if (raw == NULL) { perror(gettext("Memory allocation failed")); return (NULL); } len = strlen(raw); if (!is_efi(device->type) && (raw[len - 2] != 's' || raw[len - 1] == '2')) { (void) fprintf(stderr, NOT_ROOT_SLICE); free(raw); return (NULL); } device->slice = atoi(&raw[len - 1]); if (!is_efi(device->type)) { raw[len - 2] = 's'; raw[len - 1] = '2'; } return (raw); } static int get_raw_partition_fd(ig_device_t *device) { struct stat stat = {0}; char *raw; raw = get_raw_partition_path(device); if (raw == NULL) return (BC_ERROR); if (nowrite) device->part_fd = open(raw, O_RDONLY); else device->part_fd = open(raw, O_RDWR); if (device->part_fd < 0 || fstat(device->part_fd, &stat) != 0) { (void) fprintf(stderr, OPEN_FAIL, raw); free(raw); return (BC_ERROR); } if (S_ISCHR(stat.st_mode) == 0) { (void) fprintf(stderr, NOT_RAW_DEVICE, raw); (void) close(device->part_fd); device->part_fd = -1; free(raw); return (BC_ERROR); } free(raw); return (BC_SUCCESS); } /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. * Copyright 2016 Nexenta Systems, Inc. All rights reserved. */ #ifndef _INSTALLGRUB_H #define _INSTALLGRUB_H #ifdef __cplusplus extern "C" { #endif #include #include "./../common/bblk_einfo.h" #define SECTOR_SIZE (512) typedef struct _device_data { char *path; char *path_p0; uint8_t type; int part_fd; int disk_fd; int slice; int partition; uint64_t start_sector; char boot_sector[SECTOR_SIZE]; } ig_device_t; typedef struct _stage2_data { char *buf; char *file; char *extra; multiboot_header_t *mboot; uint32_t mboot_off; uint32_t file_size; uint32_t extra_size; uint32_t buf_size; uint32_t first_sector; uint32_t pcfs_first_sectors[2]; } ig_stage2_t; typedef struct _ig_data { char stage1_buf[SECTOR_SIZE]; ig_stage2_t stage2; ig_device_t device; } ig_data_t; enum ig_devtype_t { IG_DEV_X86BOOTPAR = 1, IG_DEV_SOLVTOC, IG_DEV_EFI }; #define is_bootpar(type) (type == IG_DEV_X86BOOTPAR) #define is_efi(type) (type == IG_DEV_EFI) #define STAGE2_MEMADDR (0x8000) /* loading addr of stage2 */ #define STAGE1_BPB_OFFSET (0x3) #define STAGE1_BPB_SIZE (0x3B) #define STAGE1_BOOT_DRIVE (0x40) #define STAGE1_FORCE_LBA (0x41) #define STAGE1_STAGE2_ADDRESS (0x42) #define STAGE1_STAGE2_SECTOR (0x44) #define STAGE1_STAGE2_SEGMENT (0x48) #define STAGE2_BLOCKLIST (SECTOR_SIZE - 0x8) #define STAGE2_INSTALLPART (SECTOR_SIZE + 0x8) #define STAGE2_FORCE_LBA (SECTOR_SIZE + 0x11) #define STAGE2_BLKOFF(type) \ (is_efi(type) ? 1024 : 50) /* offset from start of part */ /* * Maximum size of stage2 on EFI-labeled disks. Must not be larger than * VDEV_BOOT_SIZE, defined in usr/src/uts/common/fs/zfs/sys/vdev_impl.h */ #define STAGE2_MAXSIZE (1ULL << 19) #ifdef __cplusplus } #endif #endif /* _INSTALLGRUB_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2010 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _MESSAGE_H #define _MESSAGE_H #ifdef __cplusplus extern "C" { #endif #define USAGE gettext("Usage: %s [-fm] stage1 stage2 raw-device\n") #define DRY_RUN gettext("dry run--nothing will be written to disk\n") #define NOSOLPAR \ gettext("Solaris partition not found. Aborting operation.\n") #define NOBOOTPAR \ gettext("Solaris x86 boot partition not found. Aborting operation.\n") #define SOLPAR_INACTIVE gettext("Solaris fdisk partition is inactive.\n") #define BOOTPAR_NOTFOUND \ gettext("Solaris boot partition not found on %s\n") #define NOT_RAW_DEVICE gettext("device %s is not a char special device\n") #define NOT_ROOT_SLICE gettext("raw device must be a root slice (not s2)\n") #define CONVERT_FAIL gettext("cannot convert %s to a block device.\n") #define MOUNT_FAIL gettext("cannot mount %s\n") #define MOUNT_FAIL_PCFS gettext("floppy: cannot mount pcfs\n") #define MBOOT_PROMPT \ gettext("Updating master boot sector destroys existing boot " \ "managers (if any).\ncontinue (y/n)? ") #define MBOOT_NOT_UPDATED gettext("master boot sector not updated\n") #define OPEN_FAIL gettext("cannot open/stat device %s\n") #define OPEN_FAIL_FILE gettext("cannot open %s\n") #define OPEN_FAIL_PCFS gettext("cannot open /boot/grub/stage2 on pcfs\n") #define PART_FAIL \ gettext("cannot get the partition information of the disk\n") #define BAD_PART \ gettext("Partition %d of the disk has an incorrect offset\n") #define READ_FAIL_STAGE1 gettext("cannot read stage1 file %s\n") #define READ_FAIL_STAGE2 gettext("cannot read stage2 file %s\n") #define READ_FAIL_BPB gettext("cannot read bios parameter block\n") #define READ_FAIL_MBR gettext("cannot read MBR on %s\n") #define WRITE_FAIL_BOOTSEC gettext("cannot write master boot sector\n") #define WRITE_FAIL_PBOOT gettext("cannot write partition boot sector\n") #define WRITE_FAIL_STAGE2 gettext("failed to write stage2\n") #define WRITE_FAIL_STAGE2_BLOCKS \ gettext("stage2 read/write error: read %d bytes, wrote %d bytes\n") #define WRITE_MBOOT gettext("stage1 written to master boot sector\n") #define WRITE_PBOOT \ gettext("stage1 written to partition %d sector 0 (abs %d)\n") #define WRITE_BOOTSEC_FLOPPY \ gettext("stage1 written to floppy boot sector\n") #define WRITE_STAGE2_PCFS gettext("stage2 written to pcfs\n") #define WRITE_STAGE2_DISK gettext("stage2 written to partition %d," \ " %d sectors starting at %d (abs %d)\n") #define PCFS_FRAGMENTED \ gettext("cannot install stage2 on pcfs, too many fragments.\n") #define OUT_OF_MEMORY gettext("diskread: out of memory\n") #define NO_VIRT_GEOM gettext("Could not get virtual geometry\n") #define NO_PHYS_GEOM gettext("Could not get physical geometry\n") #define NO_LABEL_GEOM gettext("Could not get label geometry\n") #define LIBFDISK_INIT_FAIL gettext("Failed to initialize libfdisk.\n") #ifdef __cplusplus } #endif #endif /* _MESSAGE_H */ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. */ #include #include #include #include #include #include #include #include #include "message.h" /* * This file is glue layer to pcfs module in usr/src/common/fs/pcfs.c. * It's main functionality is to get the stage file blocklist. It's * used for installing grub on a Solaris boot partition. */ extern struct boot_fs_ops bpcfs_ops; struct boot_fs_ops *bfs_ops; struct boot_fs_ops *bfs_tab[] = {&bpcfs_ops, NULL}; static int dev_fd; int bootrd_debug = 0; #define DEV_BSIZE 512 #define MAX_CHUNK 64 static unsigned int *blocklist; /* diskread_callback is set in filesystem module (pcfs.c) */ int (*diskread_callback)(int, int); int (*fileread_callback)(int, int); static int add_stage2_block(int blocknum, int nblk) { static int i = -2; if (i >= 0 && (blocklist[i] + blocklist[i + 1] == blocknum)) { blocklist[i + 1] += nblk; return (0); } i += 2; if (i >= DEV_BSIZE / 8) { fprintf(stderr, PCFS_FRAGMENTED); exit(-1); } blocklist[i] = blocknum; blocklist[i + 1] = nblk; return (0); } /* * This one reads the ramdisk. If fi_memp is set, we copy the * ramdisk content to the designated buffer. Otherwise, we * do a "cached" read (set fi_memp to the actual ramdisk buffer). */ int diskread(fileid_t *filep) { int ret; uint_t blocknum, diskloc; blocknum = filep->fi_blocknum; if (diskread_callback) { diskread_callback(blocknum, filep->fi_count / DEV_BSIZE); return (0); } diskloc = blocknum * DEV_BSIZE; if (filep->fi_memp == NULL) { filep->fi_memp = malloc(filep->fi_count); } if (filep->fi_memp == NULL) { fprintf(stderr, OUT_OF_MEMORY); return (-1); } ret = pread(dev_fd, filep->fi_memp, filep->fi_count, diskloc); if (ret < 0) perror("diskread: pread"); return (ret >= 0 ? 0 : -1); } void * bkmem_alloc(size_t s) { return (malloc(s)); } /*ARGSUSED*/ void bkmem_free(void *p, size_t s) { free(p); } static int mountroot(char *name) { int i; /* try ops in bfs_tab and return the first successful one */ for (i = 0; bfs_tab[i] != NULL; i++) { bfs_ops = bfs_tab[i]; if (BRD_MOUNTROOT(bfs_ops, name) == 0) return (0); } return (-1); } static int unmountroot() { return (BRD_UNMOUNTROOT(bfs_ops)); } static int pcfs_glue_open(const char *filename, int flags) { return (BRD_OPEN(bfs_ops, (char *)filename, flags)); } static int pcfs_glue_close(int fd) { return (BRD_CLOSE(bfs_ops, fd)); } static ssize_t pcfs_glue_read(int fd, void *buf, size_t size) { return (BRD_READ(bfs_ops, fd, buf, size)); } /* * Get the blocklist for stage2 */ int read_stage2_blocklist(int device_fd, unsigned int *blkbuf) { int i, fd, stage2_block; char buf[DEV_BSIZE]; ssize_t size; dev_fd = device_fd; if (mountroot("dummy") != 0) { fprintf(stderr, MOUNT_FAIL_PCFS); return (-1); } if ((fd = pcfs_glue_open("/boot/grub/stage2", 0)) == -1) { fprintf(stderr, OPEN_FAIL_PCFS); return (-1); } if (bootrd_debug) (void) printf("start reading stage2:\n"); stage2_block = 0; blocklist = blkbuf; fileread_callback = add_stage2_block; for (;;) { size = pcfs_glue_read(fd, buf, DEV_BSIZE); if (size != DEV_BSIZE) break; stage2_block++; } fileread_callback = NULL; (void) pcfs_glue_close(fd); if (bootrd_debug) { (void) printf("last block size = %d\n", size); for (i = 0; blocklist[i] != 0; i += 2) { (void) printf("sectors: %d-%d\n", blocklist[i], blocklist[i] + blocklist[i + 1] - 1); } (void) printf("total blocks in stage 2: %d\n", stage2_block); } (void) unmountroot(); return (0); } # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2006 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # # Hammerhead: amd64-only, dispatch to Makefile.i386 (which includes Makefile.com) all: TARGET= all install: TARGET= install clean: TARGET= clean clobber: TARGET= clobber check: TARGET= check .KEEP_STATE: all install clean clobber check: $(MAKE) -f Makefile.i386 $(TARGET) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # .SUFFIXES: .ksh MANIFEST= boot-archive-update.xml SVCMETHOD= boot-archive-update sparc_BOOTPROG= i386_BOOTPROG= \ create_diskmap COMMON_BOOTPROG= \ create_ramdisk \ extract_boot_filelist BOOTPROG= $(COMMON_BOOTPROG) $($(MACH)_BOOTPROG) METHODPROG= boot-archive-update PROG= root_archive include ../Makefile.com ROOTMANIFESTDIR= $(ROOTSVCSYSTEM) $(ROOTMANIFEST) : FILEMODE= 444 ROOTBOOTSOLARISUSRSBINLINKS= $(PROG:%=$(ROOTBOOTSOLARISBIN)/%) .KEEP_STATE: all: $(BOOTPROG) $(METHODPROG) $(PROG) check: $(CHKMANIFEST) clean: $(RM) $(BOOTPROG) $(METHODPROG) $(PROG) lint _msg: $(ROOTBOOTSOLARISUSRSBINLINKS): $(RM) $@; $(SYMLINK) ../../../usr/sbin/$(@F) $@ # Default rule for building ksh scripts. .ksh: $(RM) $@ $(CAT) $< > $@ $(CHMOD) +x $@ include ../Makefile.targ # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # include Makefile.com .KEEP_STATE: install: all \ $(ROOTBOOTSOLARISBINPROG) \ $(ROOTMANIFEST) \ $(ROOTSVCMETHOD) \ $(ROOTUSRSBINPROG) .WAIT \ $(ROOTBOOTSOLARISUSRSBINLINKS) # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # ident "%Z%%M% %I% %E% SMI" # include Makefile.com .KEEP_STATE: install: all \ $(ROOTBOOTSOLARISBINPROG) \ $(ROOTMANIFEST) \ $(ROOTSVCMETHOD) \ $(ROOTUSRSBINPROG) # .WAIT \ # $(ROOTBOOTSOLARISUSRSBINLINKS) #!/sbin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2010 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # Copyright 2018 OmniOS Community Edition (OmniOSce) Association. # Copyright 2021 Oxide Computer Company # . /lib/svc/share/smf_include.sh . /lib/svc/share/fs_include.sh UPDATEFILE=/etc/svc/volatile/boot_archive_safefile_update if smf_is_nonglobalzone || smf_root_is_ramdisk; then # # Boot archives only exist in the global zone of persistent root # systems, but this is either a non-global zone or a system booted from # a ramdisk image. # exit $SMF_EXIT_OK fi if [ `uname -p` = "amd64" ] || [ `uname -p` = "i386" ]; then # on x86 get rid of transient reboot entry in the GRUB menu if [ -f /stubboot/boot/grub/menu.lst ]; then /sbin/bootadm -m update_temp -R /stubboot else /sbin/bootadm -m update_temp fi # Remove old platform-based archives if present. for old_plat in /platform/i86pc /platform/amd64; do [ -f $old_plat/boot_archive ] && rm -f $old_plat/boot_archive [ -f $old_plat/boot_archive.hash ] && rm -f $old_plat/boot_archive.hash [ -d $old_plat/archive_cache ] && rm -rf $old_plat/archive_cache [ -f $old_plat/amd64/boot_archive ] && rm -f $old_plat/amd64/boot_archive [ -f $old_plat/amd64/boot_archive.hash ] && rm -f $old_plat/amd64/boot_archive.hash [ -d $old_plat/amd64/archive_cache ] && rm -rf $old_plat/amd64/archive_cache done fi if [ -f $UPDATEFILE ] || [ -f /reconfigure ]; then /usr/sbin/rtc -c > /dev/null 2>&1 /sbin/bootadm update-archive rm -f $UPDATEFILE fi exit $SMF_EXIT_OK #!/sbin/sh # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License, Version 1.0 only # (the "License"). You may not use this file except in compliance # with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2005 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # basic setup # GRUBDISKMAP=/var/run/solaris_grubdisk.map /bin/rm -f "$GRUBDISKMAP" /bin/touch "$GRUBDISKMAP" /sbin/biosdev 2> /dev/null | while read diskno diskpath do devname=`/bin/ls -l /dev/rdsk/*p0 | /bin/grep $diskpath | /bin/nawk '{ print $9 }'` ctdname=`echo $devname | /bin/sed "s#/dev/rdsk/##" | /bin/sed "s#p0##"` grubdisk=`echo $diskno | /bin/sed "s/0x8//"` echo "$grubdisk $ctdname $diskpath" >> "$GRUBDISKMAP" done # cleanup #!/bin/ksh -p # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2016 Toomas Soome # Copyright 2009 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # Copyright (c) 2014 by Delphix. All rights reserved. # Copyright 2018 OmniOS Community Edition (OmniOSce) Association. # ALT_ROOT= EXTRACT_ARGS= FORMAT= format_set=0 compress=yes dirsize=0 usage() { cat <<- EOM This utility is a component of the bootadm(8) implementation and it is not recommended for stand-alone use. Please use bootadm(8) instead. Usage: ${0##*/}: [-R ] [-p ] [ -f ] [--nocompress] where is amd64 and is one of ufs, ufs-nocompress or cpio EOM exit } # default platform is what we're running on PLATFORM=`uname -m` export PATH=/usr/sbin:/usr/bin:/sbin:/bin export GZIP_CMD=/usr/bin/gzip export CPIO_CMD=/usr/bin/cpio EXTRACT_FILELIST="/boot/solaris/bin/extract_boot_filelist" # # Parse options # while [ -n "$1" ]; do case $1 in -f) shift FORMAT="$1" format_set=1 ;; -n|--nocompress) compress=no ;; -p) shift PLATFORM="$1" EXTRACT_ARGS="${EXTRACT_ARGS} -p ${PLATFORM}" ;; -R) shift ALT_ROOT="$1" if [ "$ALT_ROOT" != "/" ]; then echo "Creating boot_archive for $ALT_ROOT" EXTRACT_ARGS="${EXTRACT_ARGS} -R ${ALT_ROOT}" EXTRACT_FILELIST="${ALT_ROOT}${EXTRACT_FILELIST}" fi ;; *) usage ;; esac shift done shift `expr $OPTIND - 1` if [ $# -eq 1 ]; then ALT_ROOT="$1" echo "Creating boot_archive for $ALT_ROOT" fi if [ -z "$FORMAT" ]; then if [ -n "$ALT_ROOT" ]; then SVCCFG_DTD=/$ALT_ROOT/usr/share/lib/xml/dtd/service_bundle.dtd.1 SVCCFG_REPOSITORY=/$ALT_ROOT/etc/svc/repository.db export SVCCFG_DTD SVCCFG_REPOSITORY fi FORMAT=`svccfg -s system/boot-archive listprop config/format \ | awk '{print $3}'` fi if [ $format_set -eq 0 -a "$FORMAT" = hsfs ]; then if /sbin/bootadm update-archive -R ${ALT_ROOT:-/} -f -L -F hsfs; then exit 0 else echo "Failed to create HSFS archive, falling back." fi fi [[ "$FORMAT" =~ ^(cpio|ufs|ufs-nocompress)$ ]] || FORMAT=ufs case $PLATFORM in amd64) PLATFORM=amd64 ISA=i386 ARCH64=amd64 ;; *) usage ;; esac BOOT_ARCHIVE_SUFFIX=boot_archive BOOT_ARCHIVE=boot/$BOOT_ARCHIVE_SUFFIX function fatal_error { print -u2 $* exit 1 } [ -x $GZIP_CMD ] || compress=no case $FORMAT in cpio) [ -x $CPIO_CMD ] || FORMAT=ufs ;; ufs-nocompress) FORMAT=ufs; compress=no ;; ufs) ;; esac # # Copies all desired files to a target directory. One argument should be # passed: the file containing the list of files to copy. This function also # depends on several variables that must be set before calling: # # $ALT_ROOT - the target directory # $compress - whether or not the files in the archives should be compressed # $rdmnt - the target directory # function copy_files { typeset listfile="$1" # # If compress is set, the files are gzip'd and put in the correct # location in the loop. Nothing is printed, so the pipe and cpio # at the end is a nop. # # If compress is not set, the file names are printed, which causes # the cpio at the end to do the copy. # while read path; do if [ $compress = yes ]; then dir="${path%/*}" [ -d "$rdmnt/$dir" ] || mkdir -p "$rdmnt/$dir" $GZIP_CMD -c "$path" > "$rdmnt/$path" else print "$path" fi done <"$listfile" | cpio -pdum "$rdmnt" 2>/dev/null if [ $ISA = sparc ] ; then # copy links find $filelist -type l -print 2>/dev/null |\ cpio -pdum "$rdmnt" 2>/dev/null if [ $compress = yes ] ; then # always copy unix uncompressed find $filelist -name unix -type f -print 2>/dev/null |\ cpio -pdum "$rdmnt" 2>/dev/null fi fi } function ufs_cleanup { umount -f "$rdmnt" 2>/dev/null lofiadm -d "$rdfile" 2>/dev/null [ -n "$rddir" ] && rm -fr "$rddir" 2> /dev/null [ -n "$new_rddir" ] && rm -fr "$new_rddir" 2>/dev/null } function ufs_getsize { # Estimate image size and add 10% overhead for ufs stuff. # Note, we can't use du here in case we're on a filesystem, e.g. zfs, # in which the disk usage is less than the sum of the file sizes. # The nawk code # # {t += ($5 % 1024) ? (int($5 / 1024) + 1) * 1024 : $5} # # below rounds up the size of a file/directory, in bytes, to the # next multiple of 1024. This mimics the behavior of ufs especially # with directories. This results in a total size that's slightly # bigger than if du was called on a ufs directory. size=$(cat "$list" | xargs -I {} ls -lLd "{}" 2> /dev/null | nawk '{t += ($5 % 1024) ? (int($5 / 1024) + 1) * 1024 : $5} END {print int(t * 1.10 / 1024)}') (( size += dirsize )) (( total_size = size )) # If compression is enabled, then each file within the archive will # be individually compressed. The compression ratio is around 60% # across the archive so make the image smaller. [ $compress = yes ] && (( total_size = total_size / 2 )) } function calculate_sizes_and_locations { find $filelist -print 2>/dev/null | while read path; do if [ -d "$path" ]; then size=`ls -lLd "$path" | nawk ' {print ($5 % 1024) ? (int($5 / 1024) + 1) * 1024 : $5}'` (( dirsize += size / 1024 )) else print "$path" fi done >"$list" # calculate image size ufs_getsize # check to see if there is sufficient space in tmpfs # tmp_free=`df -b /tmp | tail -1 | awk '{ print $2 }'` (( tmp_free = tmp_free / 3 )) if [ $total_size -gt $tmp_free ] ; then echo "Insufficient space in /tmp, using $ALT_ROOT/var/tmp" # assumes we have enough scratch space on $ALT_ROOT new_rddir="/$ALT_ROOT/var/tmp/create_ramdisk.$$.tmp" rm -rf "$new_rddir" mkdir "$new_rddir" || fatal_error \ "Could not create temporary directory $new_rddir" # Save the file lists mv "$list" "$new_rddir"/ list="/$new_rddir/filelist" # Remove the old $rddir and set the new value of rddir rm -rf "$rddir" rddir="$new_rddir" new_rddir= fi } function create_ufs_archive { typeset archive="$ALT_ROOT/$BOOT_ARCHIVE" [ "$compress" = yes ] && \ echo "updating $archive (UFS)" || \ echo "updating $archive (UFS-nocompress)" # # We use /tmp/ for scratch space now. This will be changed later to # $ALT_ROOT/var/tmp if there is insufficient space in /tmp/. # rddir="/tmp/create_ramdisk.$$.tmp" new_rddir= rm -rf "$rddir" mkdir "$rddir" || fatal_error "Could not create directory $rddir" # Clean up upon exit. trap 'ufs_cleanup' EXIT list="$rddir/filelist" cd "/$ALT_ROOT" || fatal_error "Cannot chdir to $ALT_ROOT" calculate_sizes_and_locations rdfile="$rddir/rd.file" rdmnt="$rddir/rd.mount" errlog="$rddir/rd.errlog" lofidev="" mkfile ${total_size}k "$rdfile" || \ fatal_error "Could not create backing file" lofidev=`lofiadm -a "$rdfile"` || \ fatal_error "Could not create lofi device" NOINUSE_CHECK=1 newfs -m 0 $lofidev < /dev/null 2> /dev/null mkdir "$rdmnt" mount -F mntfs mnttab /etc/mnttab > /dev/null 2>&1 mount -F ufs -o nologging $lofidev "$rdmnt" rm -rf "$rdmnt/lost+found" # do the actual copy copy_files "$list" umount -f "$rdmnt" rmdir "$rdmnt" if [ $ISA = sparc ] ; then rlofidev="${lofidev/lofi/rlofi}" bb="/$ALT_ROOT/platform/$PLATFORM/lib/fs/ufs/bootblk" # installboot is not available on all platforms dd if=$bb of=$rlofidev bs=1b oseek=1 count=15 conv=sync 2>&1 fi lofiadm -d "$rdfile" # # Check if gzip exists in /usr/bin, so we only try to run gzip # on systems that have gzip. Then run gzip out of the patch to # pick it up from bfubin or something like that if needed. # # If compress is set, the individual files in the archive are # compressed, and the final compression will accomplish very # little. To save time, we skip the gzip in this case. # if [ $ISA = i386 ] && [ $compress = no ] && [ -x $GZIP_CMD ] ; then $GZIP_CMD -c "$rdfile" > "${archive}-new" else cat "$rdfile" > "${archive}-new" fi if [ $? -ne 0 ] ; then rm -f "${archive}-new" fi # sanity check the archive before moving it into place # ARCHIVE_SIZE=`ls -l "${archive}-new" 2> /dev/null | nawk '{ print $5 }'` if [ $compress = yes ] || [ $ISA = sparc ] ; then # # 'file' will report "English text" for uncompressed # boot_archives. Checking for that doesn't seem stable, # so we just check that the file exists. # ls "${archive}-new" >/dev/null 2>&1 else # # the file type check also establishes that the # file exists at all # LC_MESSAGES=C file "${archive}-new" | grep gzip > /dev/null fi if [ $? = 1 ] && [ -x $GZIP_CMD ] || [ "$ARCHIVE_SIZE" -lt 10000 ] then fatal_error "update of $archive failed" else lockfs -f "/$ALT_ROOT" 2>/dev/null rm -f "$archive.hash" mv "${archive}-new" "$archive" digest -a sha1 "$rdfile" > "$archive.hash" lockfs -f "/$ALT_ROOT" 2>/dev/null fi [ -n "$rddir" ] && rm -rf "$rddir" } function cpio_cleanup { rm -f "$tarchive" "$tarchive.cpio" "$tarchive.hash" "$tarchive.head" [ -n "$rddir" ] && rm -fr "$rddir" 2> /dev/null } function create_hash { [ -x /usr/bin/digest ] \ && /usr/bin/digest -a sha1 "$tarchive.cpio" > "$tarchive.hash" \ || print -u2 "Failed to create sha1 hash of $tarchive" } function create_cpio_archive { typeset archive="$ALT_ROOT/$BOOT_ARCHIVE" echo "updating $archive (CPIO)" rddir="/tmp/create_ramdisk.$$.tmp" tarchive="$archive.$$.new" rm -rf "$rddir" mkdir "$rddir" || fatal_error "Could not create directory $rddir" # Clean up upon exit. trap 'cpio_cleanup' EXIT cd "/$ALT_ROOT" || fatal_error "Cannot chdir to $ALT_ROOT" touch "$tarchive" \ || fatal_error "Cannot create temporary archive $tarchive" if [ $ISA = sparc ] ; then # compression does not work (yet?). # The krtld does not support gzip but fiocompress # does not seem to work either. compress="no" list="$rddir/filelist" calculate_sizes_and_locations rdmnt="$rddir/rd.mount" mkdir "$rdmnt" copy_files "$list" cd "$rdmnt" find . 2>/dev/null | \ cpio -qo -H odc > "$tarchive.cpio" \ || fatal_error "Problem creating archive" cd "/$ALT_ROOT" || fatal_error "Cannot chdir to $ALT_ROOT" bb="/$ALT_ROOT/platform/$PLATFORM/lib/fs/cpio/bootblk" # The SPARC boot code is assuming 8KB of boot data. # This is originating from disk layout and UFS limits. # Therefore we have 512B reserved space for disk label, # and 7.5KB for boot program. With 512B blocks, this is # 1 + 15 blocks. dd if=/dev/zero of="$tarchive.head" bs=512 count=16 2>&1 \ || fatal_error "Cannot create header" dd if=$bb of="$tarchive.head" bs=512 oseek=1 count=15 \ conv=sync 2>&1 \ || fatal_error "Cannot install boot block" cat "$tarchive.head" "$tarchive.cpio" > "$tarchive" \ || fatal_error "Cannot update boot archive" rm -f "$tarchive.head" "$tarchive.cpio" else find $filelist 2>/dev/null | \ cpio -qo -H odc > "$tarchive.cpio" \ || fatal_error "Problem creating archive" # If hash is supported, it must be created before gzipping the archive. # The boot loader will uncompress the archive, and the hash # will be verified against the uncompressed data. create_hash if [ -x "$GZIP_CMD" ]; then $GZIP_CMD -c "$tarchive.cpio" > "$tarchive" rm -f "$tarchive.cpio" else mv "$tarchive.cpio" "$tarchive" fi fi # Move new archive into place [ -f "$archive.hash" ] && rm -f "$archive.hash" mv "$tarchive" "$archive" [ $? -eq 0 -a -f "$tarchive.hash" ] \ && mv "$tarchive.hash" "$archive.hash" } # # get filelist # if [ ! -f "$ALT_ROOT/boot/solaris/filelist.ramdisk" ] && [ ! -f "$ALT_ROOT/etc/boot/solaris/filelist.ramdisk" ] then print -u2 "Can't find filelist.ramdisk" exit 1 fi filelist=$($EXTRACT_FILELIST $EXTRACT_ARGS \ /boot/solaris/filelist.ramdisk \ /etc/boot/solaris/filelist.ramdisk \ 2>/dev/null | sort -u) # Now that we have the list of files, we can create the archive. case "$FORMAT" in cpio) create_cpio_archive ;; ufs) create_ufs_archive ;; *) print -u2 "Unknown boot archive format, $FORMAT" exit 1 ;; esac # # For the diskless case, hardlink archive to /boot to make it # visible via tftp. /boot is lofs mounted under /tftpboot/. # NOTE: this script must work on both client and server. # grep "[ ]/[ ]*nfs[ ]" "$ALT_ROOT/etc/vfstab" > /dev/null if [ $? = 0 ]; then rm -f "$ALT_ROOT/boot/$BOOT_ARCHIVE_SUFFIX" mkdir -p "$ALT_ROOT/boot/`dirname $BOOT_ARCHIVE_SUFFIX`" ln "$ALT_ROOT/$BOOT_ARCHIVE" "$ALT_ROOT/boot/$BOOT_ARCHIVE_SUFFIX" fi #!/bin/ksh -p # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2008 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # # set path, but inherit /tmp/bfubin if it is sane # if [ "`echo $PATH | cut -f 1 -d :`" = /tmp/bfubin ] && \ [ -O /tmp/bfubin ] ; then export PATH=/tmp/bfubin:/usr/sbin:/usr/bin:/sbin:/bin else export PATH=/usr/sbin:/usr/bin:/sbin:/bin fi usage() { echo "This utility is a component of the bootadm(8) implementation" echo "and it is not recommended for stand-alone use." echo "Please use bootadm(8) instead." echo "" echo "Usage: ${0##*/}: [-R ] [-p ] ..." echo "where is amd64" exit 2 } build_platform() { altroot=$1 ( cd $altroot/ if [ -z "$STRIP" ] ; then ls -d platform/*/kernel else ls -d platform/*/kernel | grep -v $STRIP fi ) } # default platform is what we're running on PLATFORM=`uname -m` altroot="" filelists= platform_provided=no OPTIND=1 while getopts R:p: FLAG do case $FLAG in R) if [ "$OPTARG" != "/" ]; then altroot="$OPTARG" fi ;; p) platform_provided=yes PLATFORM="$OPTARG" ;; *) usage ;; esac done shift `expr $OPTIND - 1` if [ $# -eq 0 ]; then usage fi filelists=$* # # If the target platform is provided, as is the case for diskless, # or we're building an archive for this machine, we can build # a smaller archive by not including unnecessary components. # filtering=no if [ "$altroot" == "" ] || [ $platform_provided = yes ]; then case $PLATFORM in amd64) STRIP= ;; *) STRIP= ;; esac fi for list in $filelists do if [ -f $altroot/$list ]; then grep ^platform$ $altroot/$list > /dev/null if [ $? = 0 ] ; then build_platform $altroot if [ -z "$STRIP" ] ; then cat $altroot/$list | grep -v ^platform$ else cat $altroot/$list | grep -v ^platform$ | \ grep -v $STRIP fi else if [ -z "$STRIP" ] ; then cat $altroot/$list else cat $altroot/$list | grep -v $STRIP fi fi fi done exit 0 #!/bin/ksh -p # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # Copyright 2010 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # # Copyright 2012 Nexenta Systems, Inc. All rights reserved. # utility to pack and unpack a boot/root archive # both ufs and hsfs (iso9660) format archives are unpacked # only ufs archives are generated # # usage: pack # unpack # # Where is the directory to unpack to and will be cleaned out # if it exists. # usage() { printf "usage: root_archive pack \n" printf " root_archive unpack \n" exit 1 } cleanup() { if [ -d $MNT ] ; then umount $MNT 2> /dev/null rmdir $MNT fi lofiadm -d "$TMR" 2>/dev/null if [ "$REALTHING" != true ] ; then rm -f "$TMR" fi rm -f "$TMR.gz" rm -f /tmp/flist$$ } do_unpack() { ( cd $MNT find . -print | cpio -pdum "$UNPACKED_ROOT" 2> /dev/null ) # increase the chances the unmount will succeed umount -f $MNT } unpack() { MR=$1 if [ ! -f "$MR" ] ; then printf "$MR: not found\n" usage fi if [ `uname -i` = amd64 ] || [ `uname -p` = amd64 ] ; then gzcat "$MR" > $TMR else REALTHING=true ; export REALTHING TMR="$MR" fi LOFIDEV=`/usr/sbin/lofiadm -a $TMR` if [ $? != 0 ] ; then echo lofi plumb failed exit 2 fi mkdir -p $MNT FSTYP=`fstyp $LOFIDEV` if [ "$FSTYP" = ufs ] ; then /sbin/mount -o ro,nologging $LOFIDEV $MNT do_unpack elif [ "$FSTYP" = hsfs ] ; then /sbin/mount -F hsfs -o ro $LOFIDEV $MNT do_unpack else printf "invalid root archive\n" fi rmdir $MNT lofiadm -d $TMR ; LOFIDEV= if [ "$REALTHING" != true ] ; then rm $TMR fi } compress() { SRC=$1 DST=$2 ( cd $SRC filelist=`find .` for file in $filelist ; do file=`echo $file | sed s#^./##` # copy all files over to preserve hard links # echo $file | cpio -pdum $DST 2> /dev/null if [ -f $file ] && [ -s $file ] && [ ! -h $file ] ; then fiocompress -mc $file $DST/$file & fi done wait `pgrep fiocompress` # now re-copy a couple of uncompressed files if [ -d "$SRC/kernel" ] ; then find `cat boot/solaris/filelist.ramdisk` -type file \ -print 2> /dev/null > /tmp/flist$$ find usr/kernel -type file -print 2> /dev/null \ >> /tmp/flist$$ # some of the files are replaced with links into # tmp/root on the miniroot, so find the backing files # from there as well and add them to the list ti # be copied uncompressed ( cd $SRC/tmp/root find `cat ../../boot/solaris/filelist.ramdisk` \ -type file -print 2> /dev/null | \ sed 's#^#tmp/root/#' >> /tmp/flist$$ ) flist=`cat /tmp/flist$$` ( cd $DST rm -f $flist ) for file in $flist ; do echo $file | cpio -pdum $DST 2> /dev/null done else find kernel platform -name unix | \ cpio -pdum $DST 2> /dev/null find kernel platform -name genunix | cpio -pdum $DST \ 2> /dev/null find kernel platform -name platmod | cpio -pdum $DST \ 2> /dev/null find `find kernel platform -name cpu` | \ cpio -pdum $DST 2> /dev/null find `find kernel platform -name kmdb\*` | \ cpio -pdum $DST 2> /dev/null find kernel/misc/sparcv9/ctf kernel/fs/sparcv9/dcfs \ etc/system etc/name_to_major etc/path_to_inst \ etc/name_to_sysnum etc/driver_aliases \ etc/driver_classes etc/minor_perm | \ cpio -pdum $DST 2> /dev/null fi ) } root_is_ramdisk() { grep -v "set root_is_ramdisk=" "$UNPACKED_ROOT"/etc/system | \ grep -v "set ramdisk_size=" > /tmp/system.$$ cat /tmp/system.$$ > "$UNPACKED_ROOT"/etc/system rm /tmp/system.$$ echo set root_is_ramdisk=1 >> "$UNPACKED_ROOT"/etc/system echo set ramdisk_size=$1 >> "$UNPACKED_ROOT"/etc/system } pack() { MR="$1" [ -d "$UNPACKED_ROOT" ] || usage # always compress if fiocompress exists # if [ -x /sbin/fiocompress ] ; then COMPRESS=true fi # Estimate image size and add %10 overhead for ufs stuff. # Note, we can't use du here in case $UNPACKED_ROOT is on a filesystem, # e.g. zfs, in which the disk usage is less than the sum of the file # sizes. The nawk code # # {t += ($7 % 1024) ? (int($7 / 1024) + 1) * 1024 : $7} # # below rounds up the size of a file/directory, in bytes, to the # next multiple of 1024. This mimics the behavior of ufs especially # with directories. This results in a total size that's slightly # bigger than if du was called on a ufs directory. # # if the operation in turn is compressing the files the amount # of typical shrinkage is used to come up with a useful archive # size size=$(find "$UNPACKED_ROOT" -ls | nawk ' {t += ($7 % 1024) ? (int($7 / 1024) + 1) * 1024 : $7} END {print int(t * 1.10 / 1024)}') if [ "$COMPRESS" = true ] ; then size=`echo $size | nawk '{s = $1} END {print int(s * 0.6)}'` fi /usr/sbin/mkfile ${size}k "$TMR" LOFIDEV=`/usr/sbin/lofiadm -a "$TMR"` if [ $? != 0 ] ; then echo lofi plumb failed exit 2 fi RLOFIDEV=`echo $LOFIDEV | sed s/lofi/rlofi/` newfs $RLOFIDEV < /dev/null 2> /dev/null mkdir -p $MNT mount -o nologging $LOFIDEV $MNT rmdir $MNT/lost+found if [ -d "$UNPACKED_ROOT/kernel/drv/sparcv9" ] ; then root_is_ramdisk $size fi ( cd "$UNPACKED_ROOT" if [ "$COMPRESS" = true ] ; then compress . $MNT else find . -print | cpio -pdum $MNT 2> /dev/null fi ) lockfs -f $MNT umount $MNT rmdir $MNT if [ -d "$UNPACKED_ROOT/kernel/drv/sparcv9" ] ; then "$UNPACKED_ROOT/usr/sbin/installboot" \ "$UNPACKED_ROOT/platform/sun4u/lib/fs/ufs/bootblk" \ $RLOFIDEV fi lofiadm -d $LOFIDEV LOFIDEV= rm -f "$TMR.gz" if [ -d "$UNPACKED_ROOT/kernel/drv/sparcv9" ] ; then mv "$TMR" "$MR" else gzip -f "$TMR" mv "$TMR.gz" "$MR" fi chmod a+r "$MR" } strip_amd64() { find "$UNPACKED_ROOT" -name amd64 -type directory | xargs rm -rf } # main # EXTRA_SPACE=0 STRIP_AMD64= COMPRESS= PATH=/bin:/sbin:/usr/bin:/usr/sbin ; export PATH while getopts s:6c opt ; do case $opt in s) EXTRA_SPACE="$OPTARG" ;; 6) STRIP_AMD64=false ;; c) COMPRESS=true ;; *) usage ;; esac done shift `expr $OPTIND - 1` [ $# == 3 ] || usage UNPACKED_ROOT="$3" BASE="`pwd`" MNT=/tmp/mnt$$ TMR=/tmp/mr$$ LOFIDEV= MR="$2" # sanity check [ "$UNPACKED_ROOT" != "/" ] || usage if [ "`dirname $MR`" = . ] ; then MR="$BASE/$MR" fi if [ "`dirname $UNPACKED_ROOT`" = . ] ; then UNPACKED_ROOT="$BASE/$UNPACKED_ROOT" fi trap cleanup EXIT # always unpack into a fresh root case $1 in unpack) rm -rf "$UNPACKED_ROOT" mkdir -p "$UNPACKED_ROOT" ;; esac [ -d "$UNPACKED_ROOT" ] || usage case $1 in pack) pack "$MR" ;; unpack) unpack "$MR" ;; *) usage ;; esac # # CDDL HEADER START # # The contents of this file are subject to the terms of the # Common Development and Distribution License (the "License"). # You may not use this file except in compliance with the License. # # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE # or http://www.opensolaris.org/os/licensing. # See the License for the specific language governing permissions # and limitations under the License. # # When distributing Covered Code, include this CDDL HEADER in each # file and include the License file at usr/src/OPENSOLARIS.LICENSE. # If applicable, add the following below this CDDL HEADER, with the # fields enclosed by brackets "[]" replaced with your own identifying # information: Portions Copyright [yyyy] [name of copyright owner] # # CDDL HEADER END # # # Copyright 2007 Sun Microsystems, Inc. All rights reserved. # Use is subject to license terms. # BOOTPROG= symdef OBJS= $(BOOTPROG).o SRCS = $(OBJS:.o=.c) include ../Makefile.com .KEEP_STATE: LDLIBS += -lelf CLOBBERFILES= $(BOOTPROG) all: $(BOOTPROG) install: all $(ROOTBOOTSOLARISBINPROG) clean: -$(RM) $(OBJS) _msg: lint: lint_SRCS include ../Makefile.targ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2007 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include #include #include #include #include #include #include #include #include /* * symdef is a very simplified version of nm. It is used by upgrade and * create_ramdisk in situations where we can't guarantee that nm will be around. * * Two arguments are expected: a binary and a symbol name. If the symbol is * found in the name table of the binary, 0 is returned. If it is not found, * 1 is returned. If an error occurs, a message is printed to stderr and -1 * is returned. */ static void usage(void) { (void) fprintf(stderr, "USAGE: symdef file_name symbol\n"); } int main(int argc, char *argv[]) { int fd = 0; int rv = 1; uint_t cnt, symcnt; Elf *elfp = NULL; Elf_Scn *scn = NULL; size_t shstrndx; GElf_Ehdr ehdr; GElf_Shdr shdr; GElf_Sym sym; Elf32_Word shndx; Elf_Data *symdata, *shndxdata; if (argc != 3) { usage(); return (-1); } fd = open(argv[1], O_RDONLY); if (fd == -1) { (void) fprintf(stderr, "%s\n", strerror(errno)); rv = -1; goto done; } if (elf_version(EV_CURRENT) == EV_NONE) { (void) fprintf(stderr, "Elf library version out of date\n"); rv = -1; goto done; } elfp = elf_begin(fd, ELF_C_READ, NULL); if ((elfp == NULL) || (elf_kind(elfp) != ELF_K_ELF) || ((gelf_getehdr(elfp, &ehdr)) == NULL) || (elf_getshstrndx(elfp, &shstrndx) == 0)) goto done; while ((scn = elf_nextscn(elfp, scn)) != NULL) { if ((gelf_getshdr(scn, &shdr) == NULL) || ((shdr.sh_type != SHT_SYMTAB) && (shdr.sh_type != SHT_DYNSYM)) || ((symdata = elf_getdata(scn, NULL)) == NULL)) continue; symcnt = shdr.sh_size / shdr.sh_entsize; shndxdata = NULL; for (cnt = 0; cnt < symcnt; cnt++) { if ((gelf_getsymshndx(symdata, shndxdata, cnt, &sym, &shndx) != NULL) && (strcmp(argv[2], elf_strptr(elfp, shdr.sh_link, sym.st_name)) == 0)) { rv = 0; goto done; } } } done: if (elfp) (void) elf_end(elfp); if (fd != -1) (void) close(fd); return (rv); }