reboot.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. /*-
  2. * SPDX-License-Identifier: BSD-3-Clause
  3. *
  4. * Copyright (c) 1980, 1986, 1993
  5. * The Regents of the University of California. All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions
  9. * are met:
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. * 3. Neither the name of the University nor the names of its contributors
  16. * may be used to endorse or promote products derived from this software
  17. * without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  20. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  21. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  22. * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  23. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  24. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  25. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  26. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  27. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  28. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  29. * SUCH DAMAGE.
  30. */
  31. #include <sys/boottrace.h>
  32. #include <sys/mount.h>
  33. #include <sys/reboot.h>
  34. #include <sys/stat.h>
  35. #include <sys/sysctl.h>
  36. #include <sys/time.h>
  37. #include <sys/wait.h>
  38. #include <err.h>
  39. #include <errno.h>
  40. #include <fcntl.h>
  41. #include <pwd.h>
  42. #include <signal.h>
  43. #include <spawn.h>
  44. #include <stdbool.h>
  45. #include <stdio.h>
  46. #include <stdlib.h>
  47. #include <string.h>
  48. #include <syslog.h>
  49. #include <unistd.h>
  50. #include <utmpx.h>
  51. extern char **environ;
  52. #define PATH_NEXTBOOT "/boot/nextboot.conf"
  53. static void usage(void) __dead2;
  54. static uint64_t get_pageins(void);
  55. static bool dohalt;
  56. static bool donextboot;
  57. #define E(...) do { \
  58. if (force) { \
  59. warn( __VA_ARGS__ ); \
  60. return; \
  61. } \
  62. err(1, __VA_ARGS__); \
  63. } while (0) \
  64. static void
  65. zfsbootcfg(const char *pool, bool force)
  66. {
  67. const char * const av[] = {
  68. "zfsbootcfg",
  69. "-z",
  70. pool,
  71. "-n",
  72. "freebsd:nvstore",
  73. "-k",
  74. "nextboot_enable",
  75. "-v",
  76. "YES",
  77. NULL
  78. };
  79. int rv, status;
  80. pid_t p;
  81. rv = posix_spawnp(&p, av[0], NULL, NULL, __DECONST(char **, av),
  82. environ);
  83. if (rv == -1)
  84. E("system zfsbootcfg");
  85. if (waitpid(p, &status, WEXITED) < 0) {
  86. if (errno == EINTR)
  87. return;
  88. E("waitpid zfsbootcfg");
  89. }
  90. if (WIFEXITED(status)) {
  91. int e = WEXITSTATUS(status);
  92. if (e == 0)
  93. return;
  94. if (e == 127)
  95. E("zfsbootcfg not found in path");
  96. E("zfsbootcfg returned %d", e);
  97. }
  98. if (WIFSIGNALED(status))
  99. E("zfsbootcfg died with signal %d", WTERMSIG(status));
  100. E("zfsbootcfg unexpected status %d", status);
  101. }
  102. static void
  103. write_nextboot(const char *fn, const char *env, bool force)
  104. {
  105. char tmp[PATH_MAX];
  106. FILE *fp;
  107. struct statfs sfs;
  108. int tmpfd;
  109. bool supported = false;
  110. bool zfs = false;
  111. if (statfs("/boot", &sfs) != 0)
  112. err(1, "statfs /boot");
  113. if (strcmp(sfs.f_fstypename, "ufs") == 0) {
  114. /*
  115. * Only UFS supports the full nextboot protocol.
  116. */
  117. supported = true;
  118. } else if (strcmp(sfs.f_fstypename, "zfs") == 0) {
  119. zfs = true;
  120. }
  121. if (zfs) {
  122. char *slash;
  123. slash = strchr(sfs.f_mntfromname, '/');
  124. if (slash != NULL)
  125. *slash = '\0';
  126. zfsbootcfg(sfs.f_mntfromname, force);
  127. }
  128. if (strlcpy(tmp, fn, sizeof(tmp)) >= sizeof(tmp))
  129. E("Path too long %s", fn);
  130. if (strlcat(tmp, ".XXXXXX", sizeof(tmp)) >= sizeof(tmp))
  131. E("Path too long %s", fn);
  132. tmpfd = mkstemp(tmp);
  133. if (tmpfd == -1)
  134. E("mkstemp %s", tmp);
  135. fp = fdopen(tmpfd, "w");
  136. if (fp == NULL)
  137. E("fdopen %s", tmp);
  138. if (fprintf(fp, "%s%s",
  139. supported ? "nextboot_enable=\"YES\"\n" : "",
  140. env != NULL ? env : "") < 0) {
  141. int e;
  142. e = errno;
  143. if (unlink(tmp))
  144. warn("unlink %s", tmp);
  145. errno = e;
  146. E("Can't write %s", tmp);
  147. }
  148. if (fsync(fileno(fp)) != 0)
  149. E("Can't fsync %s", fn);
  150. if (rename(tmp, fn) != 0) {
  151. int e;
  152. e = errno;
  153. if (unlink(tmp))
  154. warn("unlink %s", tmp);
  155. errno = e;
  156. E("Can't rename %s to %s", tmp, fn);
  157. }
  158. fclose(fp);
  159. }
  160. static char *
  161. split_kv(char *raw)
  162. {
  163. char *eq;
  164. int len;
  165. eq = strchr(raw, '=');
  166. if (eq == NULL)
  167. errx(1, "No = in environment string %s", raw);
  168. *eq++ = '\0';
  169. len = strlen(eq);
  170. if (len == 0)
  171. errx(1, "Invalid null value %s=", raw);
  172. if (eq[0] == '"') {
  173. if (len < 2 || eq[len - 1] != '"')
  174. errx(1, "Invalid string '%s'", eq);
  175. eq[len - 1] = '\0';
  176. return (eq + 1);
  177. }
  178. return (eq);
  179. }
  180. static void
  181. add_env(char **env, const char *key, const char *value)
  182. {
  183. char *oldenv;
  184. oldenv = *env;
  185. asprintf(env, "%s%s=\"%s\"\n", oldenv != NULL ? oldenv : "", key, value);
  186. if (env == NULL)
  187. errx(1, "No memory to build env array");
  188. free(oldenv);
  189. }
  190. /*
  191. * Different options are valid for different programs.
  192. */
  193. #define GETOPT_REBOOT "cDde:fk:lNno:pqr"
  194. #define GETOPT_NEXTBOOT "De:fk:o:"
  195. int
  196. main(int argc, char *argv[])
  197. {
  198. struct utmpx utx;
  199. const struct passwd *pw;
  200. int ch, howto = 0, i, sverrno;
  201. bool Dflag, fflag, lflag, Nflag, nflag, qflag;
  202. uint64_t pageins;
  203. const char *user, *kernel = NULL, *getopts = GETOPT_REBOOT;
  204. char *env = NULL, *v;
  205. if (strstr(getprogname(), "halt") != NULL) {
  206. dohalt = true;
  207. howto = RB_HALT;
  208. } else if (strcmp(getprogname(), "nextboot") == 0) {
  209. donextboot = true;
  210. getopts = GETOPT_NEXTBOOT; /* Note: reboot's extra opts return '?' */
  211. } else {
  212. /* reboot */
  213. howto = 0;
  214. }
  215. Dflag = fflag = lflag = Nflag = nflag = qflag = false;
  216. while ((ch = getopt(argc, argv, getopts)) != -1) {
  217. switch(ch) {
  218. case 'c':
  219. howto |= RB_POWERCYCLE;
  220. break;
  221. case 'D':
  222. Dflag = true;
  223. break;
  224. case 'd':
  225. howto |= RB_DUMP;
  226. break;
  227. case 'e':
  228. v = split_kv(optarg);
  229. add_env(&env, optarg, v);
  230. break;
  231. case 'f':
  232. fflag = true;
  233. break;
  234. case 'k':
  235. kernel = optarg;
  236. break;
  237. case 'l':
  238. lflag = true;
  239. break;
  240. case 'n':
  241. nflag = true;
  242. howto |= RB_NOSYNC;
  243. break;
  244. case 'N':
  245. nflag = true;
  246. Nflag = true;
  247. break;
  248. case 'o':
  249. add_env(&env, "kernel_options", optarg);
  250. break;
  251. case 'p':
  252. howto |= RB_POWEROFF;
  253. break;
  254. case 'q':
  255. qflag = true;
  256. break;
  257. case 'r':
  258. howto |= RB_REROOT;
  259. break;
  260. case '?':
  261. default:
  262. usage();
  263. }
  264. }
  265. argc -= optind;
  266. argv += optind;
  267. if (argc != 0)
  268. usage();
  269. if (Dflag && ((howto & ~RB_HALT) != 0 || kernel != NULL))
  270. errx(1, "cannot delete existing nextboot config and do anything else");
  271. if ((howto & (RB_DUMP | RB_HALT)) == (RB_DUMP | RB_HALT))
  272. errx(1, "cannot dump (-d) when halting; must reboot instead");
  273. if (Nflag && (howto & RB_NOSYNC) != 0)
  274. errx(1, "-N cannot be used with -n");
  275. if ((howto & RB_POWEROFF) && (howto & RB_POWERCYCLE))
  276. errx(1, "-c and -p cannot be used together");
  277. if ((howto & RB_REROOT) != 0 && howto != RB_REROOT)
  278. errx(1, "-r cannot be used with -c, -d, -n, or -p");
  279. if ((howto & RB_REROOT) != 0 && kernel != NULL)
  280. errx(1, "-r and -k cannot be used together, there is no next kernel");
  281. if (Dflag) {
  282. if (unlink(PATH_NEXTBOOT) != 0 && errno != ENOENT)
  283. warn("unlink " PATH_NEXTBOOT);
  284. exit(0);
  285. }
  286. if (!donextboot && geteuid() != 0) {
  287. errno = EPERM;
  288. err(1, NULL);
  289. }
  290. if (qflag) {
  291. reboot(howto);
  292. err(1, NULL);
  293. }
  294. if (kernel != NULL) {
  295. if (!fflag) {
  296. char *k;
  297. struct stat sb;
  298. asprintf(&k, "/boot/%s/kernel", kernel);
  299. if (k == NULL)
  300. errx(1, "No memory to check %s", kernel);
  301. if (stat(k, &sb) != 0)
  302. err(1, "stat %s", k);
  303. if (!S_ISREG(sb.st_mode))
  304. errx(1, "%s is not a file", k);
  305. free(k);
  306. }
  307. add_env(&env, "kernel", kernel);
  308. }
  309. if (env != NULL)
  310. write_nextboot(PATH_NEXTBOOT, env, fflag);
  311. if (donextboot)
  312. exit (0);
  313. /* Log the reboot. */
  314. if (!lflag) {
  315. if ((user = getlogin()) == NULL)
  316. user = (pw = getpwuid(getuid())) ?
  317. pw->pw_name : "???";
  318. if (dohalt) {
  319. openlog("halt", 0, LOG_AUTH | LOG_CONS);
  320. syslog(LOG_CRIT, "halted by %s", user);
  321. } else if (howto & RB_REROOT) {
  322. openlog("reroot", 0, LOG_AUTH | LOG_CONS);
  323. syslog(LOG_CRIT, "rerooted by %s", user);
  324. } else if (howto & RB_POWEROFF) {
  325. openlog("reboot", 0, LOG_AUTH | LOG_CONS);
  326. syslog(LOG_CRIT, "powered off by %s", user);
  327. } else if (howto & RB_POWERCYCLE) {
  328. openlog("reboot", 0, LOG_AUTH | LOG_CONS);
  329. syslog(LOG_CRIT, "power cycled by %s", user);
  330. } else {
  331. openlog("reboot", 0, LOG_AUTH | LOG_CONS);
  332. syslog(LOG_CRIT, "rebooted by %s", user);
  333. }
  334. }
  335. utx.ut_type = SHUTDOWN_TIME;
  336. gettimeofday(&utx.ut_tv, NULL);
  337. pututxline(&utx);
  338. /*
  339. * Do a sync early on, so disks start transfers while we're off
  340. * killing processes. Don't worry about writes done before the
  341. * processes die, the reboot system call syncs the disks.
  342. */
  343. if (!nflag)
  344. sync();
  345. /*
  346. * Ignore signals that we can get as a result of killing
  347. * parents, group leaders, etc.
  348. */
  349. (void)signal(SIGHUP, SIG_IGN);
  350. (void)signal(SIGINT, SIG_IGN);
  351. (void)signal(SIGQUIT, SIG_IGN);
  352. (void)signal(SIGTERM, SIG_IGN);
  353. (void)signal(SIGTSTP, SIG_IGN);
  354. /*
  355. * If we're running in a pipeline, we don't want to die
  356. * after killing whatever we're writing to.
  357. */
  358. (void)signal(SIGPIPE, SIG_IGN);
  359. /*
  360. * Only init(8) can perform rerooting.
  361. */
  362. if (howto & RB_REROOT) {
  363. if (kill(1, SIGEMT) == -1)
  364. err(1, "SIGEMT init");
  365. return (0);
  366. }
  367. /* Just stop init -- if we fail, we'll restart it. */
  368. BOOTTRACE("SIGTSTP to init(8)...");
  369. if (kill(1, SIGTSTP) == -1)
  370. err(1, "SIGTSTP init");
  371. /* Send a SIGTERM first, a chance to save the buffers. */
  372. BOOTTRACE("SIGTERM to all other processes...");
  373. if (kill(-1, SIGTERM) == -1 && errno != ESRCH)
  374. err(1, "SIGTERM processes");
  375. /*
  376. * After the processes receive the signal, start the rest of the
  377. * buffers on their way. Wait 5 seconds between the SIGTERM and
  378. * the SIGKILL to give everybody a chance. If there is a lot of
  379. * paging activity then wait longer, up to a maximum of approx
  380. * 60 seconds.
  381. */
  382. sleep(2);
  383. for (i = 0; i < 20; i++) {
  384. pageins = get_pageins();
  385. if (!nflag)
  386. sync();
  387. sleep(3);
  388. if (get_pageins() == pageins)
  389. break;
  390. }
  391. for (i = 1;; ++i) {
  392. BOOTTRACE("SIGKILL to all other processes(%d)...", i);
  393. if (kill(-1, SIGKILL) == -1) {
  394. if (errno == ESRCH)
  395. break;
  396. goto restart;
  397. }
  398. if (i > 5) {
  399. (void)fprintf(stderr,
  400. "WARNING: some process(es) wouldn't die\n");
  401. break;
  402. }
  403. (void)sleep(2 * i);
  404. }
  405. reboot(howto);
  406. /* FALLTHROUGH */
  407. restart:
  408. BOOTTRACE("SIGHUP to init(8)...");
  409. sverrno = errno;
  410. errx(1, "%s%s", kill(1, SIGHUP) == -1 ? "(can't restart init): " : "",
  411. strerror(sverrno));
  412. /* NOTREACHED */
  413. }
  414. static void
  415. usage(void)
  416. {
  417. (void)fprintf(stderr, dohalt ?
  418. "usage: halt [-clNnpq] [-k kernel]\n" :
  419. "usage: reboot [-cdlNnpqr] [-k kernel]\n");
  420. exit(1);
  421. }
  422. static uint64_t
  423. get_pageins(void)
  424. {
  425. uint64_t pageins;
  426. size_t len;
  427. len = sizeof(pageins);
  428. if (sysctlbyname("vm.stats.vm.v_swappgsin", &pageins, &len, NULL, 0)
  429. != 0) {
  430. warn("v_swappgsin");
  431. return (0);
  432. }
  433. return (pageins);
  434. }