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