diff --git a/sbin/reboot/reboot.c b/sbin/reboot/reboot.c --- a/sbin/reboot/reboot.c +++ b/sbin/reboot/reboot.c @@ -49,17 +49,59 @@ #include #include +#define PATH_NEXTBOOT "/boot/nextboot.conf" + static void usage(void) __dead2; static uint64_t get_pageins(void); static bool dohalt; +static void +write_nextboot(const char *fn, const char *kernel, bool force) +{ + char *k; + int fd; + +#define E(...) do { \ + if (force) { \ + warn( __VA_ARGS__ ); \ + return; \ + } \ + err(1, __VA_ARGS__); \ + } while (0) \ + + fd = open(fn, O_WRONLY | O_CREAT | O_TRUNC, 0444); + if (fd < 0) + E("Can't create %s to boot %s", fn, kernel); + + asprintf(&k, + "nextboot_enable=\"YES\"\n" + "kernel=\"%s\"\n", kernel); + if (k == NULL) + E("No memory to write %s", fn); + + if (write(fd, k, strlen(k)) != (ssize_t)strlen(k)) { + int e = errno; + + if (unlink(fn)) + warn("unlink %s", fn); + close(fd); + free(k); + errno = e; + E("Can't write %s", fn); + } + free(k); + close(fd); +#undef E +} + + int main(int argc, char *argv[]) { struct utmpx utx; const struct passwd *pw; - int ch, howto, i, fd, sverrno; + int ch, howto, i, sverrno; bool fflag, lflag, nflag, qflag, Nflag; uint64_t pageins; const char *user, *kernel = NULL; @@ -147,15 +189,7 @@ errx(1, "%s is not a file.", k); free(k); } - fd = open("/boot/nextboot.conf", O_WRONLY | O_CREAT | O_TRUNC, - 0444); - if (fd > -1) { - (void)write(fd, "nextboot_enable=\"YES\"\n", 22); - (void)write(fd, "kernel=\"", 8L); - (void)write(fd, kernel, strlen(kernel)); - (void)write(fd, "\"\n", 2); - close(fd); - } + write_nextboot(PATH_NEXTBOOT, kernel, fflag); } /* Log the reboot. */