xref: /freebsd/sbin/reboot/reboot.c (revision 33a2406eed009dbffd7dfa44285c23f0db5a3750)
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 
32 #include <sys/boottrace.h>
33 #include <sys/mount.h>
34 #include <sys/reboot.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 
41 #include <err.h>
42 #include <errno.h>
43 #include <fcntl.h>
44 #include <pwd.h>
45 #include <signal.h>
46 #include <spawn.h>
47 #include <stdbool.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <syslog.h>
52 #include <unistd.h>
53 #include <utmpx.h>
54 
55 #define PATH_NEXTBOOT "/boot/nextboot.conf"
56 
57 static void usage(void) __dead2;
58 static uint64_t get_pageins(void);
59 
60 static bool dohalt;
61 static bool donextboot;
62 
63 #define E(...) do {				\
64 		if (force) {			\
65 			warn( __VA_ARGS__ );	\
66 			return;			\
67 		}				\
68 		err(1, __VA_ARGS__);		\
69 	} while (0)				\
70 
71 static void
72 zfsbootcfg(const char *pool, bool force)
73 {
74 	const char * const av[] = {
75 		"zfsbootcfg",
76 		"-z",
77 		pool,
78 		"-n",
79 		"freebsd:nvstore",
80 		"-k",
81 		"nextboot_enable"
82 		"-v",
83 		"YES",
84 		NULL
85 	};
86 	int rv, status;
87 	pid_t p;
88 	extern char **environ;
89 
90 	rv = posix_spawnp(&p, av[0], NULL, NULL, __DECONST(char **, av),
91 	    environ);
92 	if (rv == -1)
93 		E("system zfsbootcfg");
94 	if (waitpid(p, &status, WEXITED) < 0) {
95 		if (errno == EINTR)
96 			return;
97 		E("waitpid zfsbootcfg");
98 	}
99 	if (WIFEXITED(status)) {
100 		int e = WEXITSTATUS(status);
101 
102 		if (e == 0)
103 			return;
104 		if (e == 127)
105 			E("zfsbootcfg not found in path");
106 		E("zfsbootcfg returned %d", e);
107 	}
108 	if (WIFSIGNALED(status))
109 		E("zfsbootcfg died with signal %d", WTERMSIG(status));
110 	E("zfsbootcfg unexpected status %d", status);
111 }
112 
113 static void
114 write_nextboot(const char *fn, const char *env, bool force)
115 {
116 	FILE *fp;
117 	struct statfs sfs;
118 	bool supported = false;
119 	bool zfs = false;
120 
121 	if (statfs("/boot", &sfs) != 0)
122 		err(1, "statfs /boot");
123 	if (strcmp(sfs.f_fstypename, "ufs") == 0) {
124 		/*
125 		 * Only UFS supports the full nextboot protocol.
126 		 */
127 		supported = true;
128 	} else if (strcmp(sfs.f_fstypename, "zfs") == 0) {
129 		zfs = true;
130 	}
131 
132 	if (zfs) {
133 		zfsbootcfg(sfs.f_mntfromname, force);
134 	}
135 
136 	fp = fopen(fn, "w");
137 	if (fp == NULL)
138 		E("Can't create %s", fn);
139 
140 	if (fprintf(fp,"%s%s",
141 	    supported ? "nextboot_enable=\"YES\"\n" : "",
142 	    env != NULL ? env : "") < 0) {
143 		int e;
144 
145 		e = errno;
146 		fclose(fp);
147 		if (unlink(fn))
148 			warn("unlink %s", fn);
149 		errno = e;
150 		E("Can't write %s", fn);
151 	}
152 	fclose(fp);
153 }
154 
155 static char *
156 split_kv(char *raw)
157 {
158 	char *eq;
159 	int len;
160 
161 	eq = strchr(raw, '=');
162 	if (eq == NULL)
163 		errx(1, "No = in environment string %s", raw);
164 	*eq++ = '\0';
165 	len = strlen(eq);
166 	if (len == 0)
167 		errx(1, "Invalid null value %s=", raw);
168 	if (eq[0] == '"') {
169 		if (len < 2 || eq[len - 1] != '"')
170 			errx(1, "Invalid string '%s'", eq);
171 		eq[len - 1] = '\0';
172 		return (eq + 1);
173 	}
174 	return (eq);
175 }
176 
177 static void
178 add_env(char **env, const char *key, const char *value)
179 {
180 	char *oldenv;
181 
182 	oldenv = *env;
183 	asprintf(env, "%s%s=\"%s\"\n", oldenv != NULL ? oldenv : "", key, value);
184 	if (env == NULL)
185 		errx(1, "No memory to build env array");
186 	free(oldenv);
187 }
188 
189 /*
190  * Different options are valid for different programs.
191  */
192 #define GETOPT_REBOOT "cDde:k:lNno:pqr"
193 #define GETOPT_NEXTBOOT "De:k:o:"
194 
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 
206 	if (strstr(getprogname(), "halt") != NULL) {
207 		dohalt = true;
208 		howto = RB_HALT;
209 	} else if (strcmp(getprogname(), "nextboot") == 0) {
210 		donextboot = true;
211 		getopts = GETOPT_NEXTBOOT; /* Note: reboot's extra opts return '?' */
212 	} else {
213 		/* reboot */
214 		howto = 0;
215 	}
216 	Dflag = fflag = lflag = Nflag = nflag = qflag = false;
217 	while ((ch = getopt(argc, argv, getopts)) != -1) {
218 		switch(ch) {
219 		case 'c':
220 			howto |= RB_POWERCYCLE;
221 			break;
222 		case 'D':
223 			Dflag = true;
224 			break;
225 		case 'd':
226 			howto |= RB_DUMP;
227 			break;
228 		case 'e':
229 			v = split_kv(optarg);
230 			add_env(&env, optarg, v);
231 			break;
232 		case 'f':
233 			fflag = true;
234 			break;
235 		case 'k':
236 			kernel = optarg;
237 			break;
238 		case 'l':
239 			lflag = true;
240 			break;
241 		case 'n':
242 			nflag = true;
243 			howto |= RB_NOSYNC;
244 			break;
245 		case 'N':
246 			nflag = true;
247 			Nflag = true;
248 			break;
249 		case 'o':
250 			add_env(&env, "kernel_options", optarg);
251 			break;
252 		case 'p':
253 			howto |= RB_POWEROFF;
254 			break;
255 		case 'q':
256 			qflag = true;
257 			break;
258 		case 'r':
259 			howto |= RB_REROOT;
260 			break;
261 		case '?':
262 		default:
263 			usage();
264 		}
265 	}
266 
267 	argc -= optind;
268 	argv += optind;
269 	if (argc != 0)
270 		usage();
271 
272 	if (Dflag && ((howto & ~RB_HALT) != 0  || kernel != NULL))
273 		errx(1, "cannot delete existing nextboot config and do anything else");
274 	if ((howto & (RB_DUMP | RB_HALT)) == (RB_DUMP | RB_HALT))
275 		errx(1, "cannot dump (-d) when halting; must reboot instead");
276 	if (Nflag && (howto & RB_NOSYNC) != 0)
277 		errx(1, "-N cannot be used with -n");
278 	if ((howto & RB_POWEROFF) && (howto & RB_POWERCYCLE))
279 		errx(1, "-c and -p cannot be used together");
280 	if ((howto & RB_REROOT) != 0 && howto != RB_REROOT)
281 		errx(1, "-r cannot be used with -c, -d, -n, or -p");
282 	if ((howto & RB_REROOT) != 0 && kernel != NULL)
283 		errx(1, "-r and -k cannot be used together, there is no next kernel");
284 
285 	if (Dflag) {
286 		if (unlink(PATH_NEXTBOOT) != 0)
287 			err(1, "unlink %s", PATH_NEXTBOOT);
288 		exit(0);
289 	}
290 
291 	if (!donextboot && geteuid() != 0) {
292 		errno = EPERM;
293 		err(1, NULL);
294 	}
295 
296 	if (qflag) {
297 		reboot(howto);
298 		err(1, NULL);
299 	}
300 
301 	if (kernel != NULL) {
302 		if (!fflag) {
303 			char *k;
304 			struct stat sb;
305 
306 			asprintf(&k, "/boot/%s/kernel", kernel);
307 			if (k == NULL)
308 				errx(1, "No memory to check %s", kernel);
309 			if (stat(k, &sb) != 0)
310 				err(1, "stat %s", k);
311 			if (!S_ISREG(sb.st_mode))
312 				errx(1, "%s is not a file", k);
313 			free(k);
314 		}
315 		add_env(&env, "kernel", kernel);
316 	}
317 
318 	if (env != NULL)
319 		write_nextboot(PATH_NEXTBOOT, env, fflag);
320 	if (donextboot)
321 		exit (0);
322 
323 	/* Log the reboot. */
324 	if (!lflag)  {
325 		if ((user = getlogin()) == NULL)
326 			user = (pw = getpwuid(getuid())) ?
327 			    pw->pw_name : "???";
328 		if (dohalt) {
329 			openlog("halt", 0, LOG_AUTH | LOG_CONS);
330 			syslog(LOG_CRIT, "halted by %s", user);
331 		} else if (howto & RB_REROOT) {
332 			openlog("reroot", 0, LOG_AUTH | LOG_CONS);
333 			syslog(LOG_CRIT, "rerooted by %s", user);
334 		} else if (howto & RB_POWEROFF) {
335 			openlog("reboot", 0, LOG_AUTH | LOG_CONS);
336 			syslog(LOG_CRIT, "powered off by %s", user);
337 		} else if (howto & RB_POWERCYCLE) {
338 			openlog("reboot", 0, LOG_AUTH | LOG_CONS);
339 			syslog(LOG_CRIT, "power cycled by %s", user);
340 		} else {
341 			openlog("reboot", 0, LOG_AUTH | LOG_CONS);
342 			syslog(LOG_CRIT, "rebooted by %s", user);
343 		}
344 	}
345 	utx.ut_type = SHUTDOWN_TIME;
346 	gettimeofday(&utx.ut_tv, NULL);
347 	pututxline(&utx);
348 
349 	/*
350 	 * Do a sync early on, so disks start transfers while we're off
351 	 * killing processes.  Don't worry about writes done before the
352 	 * processes die, the reboot system call syncs the disks.
353 	 */
354 	if (!nflag)
355 		sync();
356 
357 	/*
358 	 * Ignore signals that we can get as a result of killing
359 	 * parents, group leaders, etc.
360 	 */
361 	(void)signal(SIGHUP,  SIG_IGN);
362 	(void)signal(SIGINT,  SIG_IGN);
363 	(void)signal(SIGQUIT, SIG_IGN);
364 	(void)signal(SIGTERM, SIG_IGN);
365 	(void)signal(SIGTSTP, SIG_IGN);
366 
367 	/*
368 	 * If we're running in a pipeline, we don't want to die
369 	 * after killing whatever we're writing to.
370 	 */
371 	(void)signal(SIGPIPE, SIG_IGN);
372 
373 	/*
374 	 * Only init(8) can perform rerooting.
375 	 */
376 	if (howto & RB_REROOT) {
377 		if (kill(1, SIGEMT) == -1)
378 			err(1, "SIGEMT init");
379 
380 		return (0);
381 	}
382 
383 	/* Just stop init -- if we fail, we'll restart it. */
384 	BOOTTRACE("SIGTSTP to init(8)...");
385 	if (kill(1, SIGTSTP) == -1)
386 		err(1, "SIGTSTP init");
387 
388 	/* Send a SIGTERM first, a chance to save the buffers. */
389 	BOOTTRACE("SIGTERM to all other processes...");
390 	if (kill(-1, SIGTERM) == -1 && errno != ESRCH)
391 		err(1, "SIGTERM processes");
392 
393 	/*
394 	 * After the processes receive the signal, start the rest of the
395 	 * buffers on their way.  Wait 5 seconds between the SIGTERM and
396 	 * the SIGKILL to give everybody a chance. If there is a lot of
397 	 * paging activity then wait longer, up to a maximum of approx
398 	 * 60 seconds.
399 	 */
400 	sleep(2);
401 	for (i = 0; i < 20; i++) {
402 		pageins = get_pageins();
403 		if (!nflag)
404 			sync();
405 		sleep(3);
406 		if (get_pageins() == pageins)
407 			break;
408 	}
409 
410 	for (i = 1;; ++i) {
411 		BOOTTRACE("SIGKILL to all other processes(%d)...", i);
412 		if (kill(-1, SIGKILL) == -1) {
413 			if (errno == ESRCH)
414 				break;
415 			goto restart;
416 		}
417 		if (i > 5) {
418 			(void)fprintf(stderr,
419 			    "WARNING: some process(es) wouldn't die\n");
420 			break;
421 		}
422 		(void)sleep(2 * i);
423 	}
424 
425 	reboot(howto);
426 	/* FALLTHROUGH */
427 
428 restart:
429 	BOOTTRACE("SIGHUP to init(8)...");
430 	sverrno = errno;
431 	errx(1, "%s%s", kill(1, SIGHUP) == -1 ? "(can't restart init): " : "",
432 	    strerror(sverrno));
433 	/* NOTREACHED */
434 }
435 
436 static void
437 usage(void)
438 {
439 
440 	(void)fprintf(stderr, dohalt ?
441 	    "usage: halt [-clNnpq] [-k kernel]\n" :
442 	    "usage: reboot [-cdlNnpqr] [-k kernel]\n");
443 	exit(1);
444 }
445 
446 static uint64_t
447 get_pageins(void)
448 {
449 	uint64_t pageins;
450 	size_t len;
451 
452 	len = sizeof(pageins);
453 	if (sysctlbyname("vm.stats.vm.v_swappgsin", &pageins, &len, NULL, 0)
454 	    != 0) {
455 		warn("v_swappgsin");
456 		return (0);
457 	}
458 	return (pageins);
459 }
460