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