xref: /freebsd/sbin/bectl/bectl.c (revision 94ffff68c8e84d4983e3d803575cfdb3e5782515)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2017 Kyle J. Kneitinger <kyle@kneit.in>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/param.h>
32 #include <sys/mount.h>
33 #include <errno.h>
34 #include <libutil.h>
35 #include <stdbool.h>
36 #include <stdio.h>
37 #include <stdint.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <sysexits.h>
41 #include <time.h>
42 #include <unistd.h>
43 
44 #include <be.h>
45 
46 #include "bectl.h"
47 
48 static int bectl_cmd_activate(int argc, char *argv[]);
49 static int bectl_cmd_check(int argc, char *argv[]);
50 static int bectl_cmd_create(int argc, char *argv[]);
51 static int bectl_cmd_destroy(int argc, char *argv[]);
52 static int bectl_cmd_export(int argc, char *argv[]);
53 static int bectl_cmd_import(int argc, char *argv[]);
54 #if SOON
55 static int bectl_cmd_add(int argc, char *argv[]);
56 #endif
57 static int bectl_cmd_mount(int argc, char *argv[]);
58 static int bectl_cmd_rename(int argc, char *argv[]);
59 static int bectl_cmd_unmount(int argc, char *argv[]);
60 
61 libbe_handle_t *be;
62 
63 int aok;
64 
65 int
66 usage(bool explicit)
67 {
68 	FILE *fp;
69 
70 	fp =  explicit ? stdout : stderr;
71 	fprintf(fp, "%s",
72 	    "Usage:\tbectl {-h | -? | subcommand [args...]}\n"
73 #if SOON
74 	    "\tbectl add (path)*\n"
75 #endif
76 	    "\tbectl activate [-t] beName\n"
77 	    "\tbectl activate [-T]\n"
78 	    "\tbectl check\n"
79 	    "\tbectl create [-r] [-e {nonActiveBe | beName@snapshot}] beName\n"
80 	    "\tbectl create [-r] beName@snapshot\n"
81 	    "\tbectl destroy [-Fo] {beName | beName@snapshot}\n"
82 	    "\tbectl export sourceBe\n"
83 	    "\tbectl import targetBe\n"
84 	    "\tbectl jail [-bU] [{-o key=value | -u key}]... beName\n"
85 	    "\t      [utility [argument ...]]\n"
86 	    "\tbectl list [-aDHs] [{-c property | -C property}]\n"
87 	    "\tbectl mount beName [mountpoint]\n"
88 	    "\tbectl rename origBeName newBeName\n"
89 	    "\tbectl {ujail | unjail} {jailID | jailName | beName}\n"
90 	    "\tbectl {umount | unmount} [-f] beName\n");
91 
92 	return (explicit ? 0 : EX_USAGE);
93 }
94 
95 
96 /*
97  * Represents a relationship between the command name and the parser action
98  * that handles it.
99  */
100 struct command_map_entry {
101 	const char *command;
102 	int (*fn)(int argc, char *argv[]);
103 	/* True if libbe_print_on_error should be disabled */
104 	bool silent;
105 };
106 
107 static struct command_map_entry command_map[] =
108 {
109 	{ "activate", bectl_cmd_activate,false   },
110 	{ "create",   bectl_cmd_create,  false   },
111 	{ "destroy",  bectl_cmd_destroy, false   },
112 	{ "export",   bectl_cmd_export,  false   },
113 	{ "import",   bectl_cmd_import,  false   },
114 #if SOON
115 	{ "add",      bectl_cmd_add,     false   },
116 #endif
117 	{ "jail",     bectl_cmd_jail,    false   },
118 	{ "list",     bectl_cmd_list,    false   },
119 	{ "mount",    bectl_cmd_mount,   false   },
120 	{ "rename",   bectl_cmd_rename,  false   },
121 	{ "unjail",   bectl_cmd_unjail,  false   },
122 	{ "unmount",  bectl_cmd_unmount, false   },
123 	{ "check",    bectl_cmd_check,   true    },
124 };
125 
126 static struct command_map_entry *
127 get_cmd_info(const char *cmd)
128 {
129 	size_t i;
130 
131 	for (i = 0; i < nitems(command_map); ++i) {
132 		if (strcmp(cmd, command_map[i].command) == 0)
133 			return (&command_map[i]);
134 	}
135 
136 	return (NULL);
137 }
138 
139 
140 static int
141 bectl_cmd_activate(int argc, char *argv[])
142 {
143 	int err, opt;
144 	bool temp, reset;
145 
146 	temp = false;
147 	reset = false;
148 	while ((opt = getopt(argc, argv, "tT")) != -1) {
149 		switch (opt) {
150 		case 't':
151 			if (reset)
152 				return (usage(false));
153 			temp = true;
154 			break;
155 		case 'T':
156 			if (temp)
157 				return (usage(false));
158 			reset = true;
159 			break;
160 		default:
161 			fprintf(stderr, "bectl activate: unknown option '-%c'\n",
162 			    optopt);
163 			return (usage(false));
164 		}
165 	}
166 
167 	argc -= optind;
168 	argv += optind;
169 
170 	if (argc != 1 && (!reset || argc != 0)) {
171 		fprintf(stderr, "bectl activate: wrong number of arguments\n");
172 		return (usage(false));
173 	}
174 
175 	if (reset) {
176 		if ((err = be_deactivate(be, NULL, reset)) == 0)
177 			printf("Temporary activation removed\n");
178 		else
179 			printf("Failed to remove temporary activation\n");
180 		return (err);
181 	}
182 
183 	/* activate logic goes here */
184 	if ((err = be_activate(be, argv[0], temp)) != 0)
185 		/* XXX TODO: more specific error msg based on err */
186 		printf("Did not successfully activate boot environment %s\n",
187 		    argv[0]);
188 	else
189 		printf("Successfully activated boot environment %s\n", argv[0]);
190 
191 	if (temp)
192 		printf("for next boot\n");
193 
194 	return (err);
195 }
196 
197 
198 /*
199  * TODO: when only one arg is given, and it contains an "@" the this should
200  * create that snapshot
201  */
202 static int
203 bectl_cmd_create(int argc, char *argv[])
204 {
205 	char snapshot[BE_MAXPATHLEN];
206 	char *atpos, *bootenv, *snapname;
207 	int err, opt;
208 	bool recursive;
209 
210 	snapname = NULL;
211 	recursive = false;
212 	while ((opt = getopt(argc, argv, "e:r")) != -1) {
213 		switch (opt) {
214 		case 'e':
215 			snapname = optarg;
216 			break;
217 		case 'r':
218 			recursive = true;
219 			break;
220 		default:
221 			fprintf(stderr, "bectl create: unknown option '-%c'\n",
222 			    optopt);
223 			return (usage(false));
224 		}
225 	}
226 
227 	argc -= optind;
228 	argv += optind;
229 
230 	if (argc != 1) {
231 		fprintf(stderr, "bectl create: wrong number of arguments\n");
232 		return (usage(false));
233 	}
234 
235 	bootenv = *argv;
236 
237 	err = BE_ERR_SUCCESS;
238 	if ((atpos = strchr(bootenv, '@')) != NULL) {
239 		/*
240 		 * This is the "create a snapshot variant". No new boot
241 		 * environment is to be created here.
242 		 */
243 		*atpos++ = '\0';
244 		err = be_snapshot(be, bootenv, atpos, recursive, NULL);
245 	} else {
246 		if (snapname == NULL)
247 			/* Create from currently booted BE */
248 			err = be_snapshot(be, be_active_path(be), NULL,
249 			    recursive, snapshot);
250 		else if (strchr(snapname, '@') != NULL)
251 			/* Create from given snapshot */
252 			strlcpy(snapshot, snapname, sizeof(snapshot));
253 		else
254 			/* Create from given BE */
255 			err = be_snapshot(be, snapname, NULL, recursive,
256 			    snapshot);
257 
258 		if (err == BE_ERR_SUCCESS)
259 			err = be_create_depth(be, bootenv, snapshot,
260 					      recursive == true ? -1 : 0);
261 	}
262 
263 	switch (err) {
264 	case BE_ERR_SUCCESS:
265 		break;
266 	default:
267 		if (atpos != NULL)
268 			fprintf(stderr,
269 			    "Failed to create a snapshot '%s' of '%s'\n",
270 			    atpos, bootenv);
271 		else if (snapname == NULL)
272 			fprintf(stderr,
273 			    "Failed to create bootenv %s\n", bootenv);
274 		else
275 			fprintf(stderr,
276 			    "Failed to create bootenv %s from snapshot %s\n",
277 			    bootenv, snapname);
278 	}
279 
280 	return (err);
281 }
282 
283 
284 static int
285 bectl_cmd_export(int argc, char *argv[])
286 {
287 	char *bootenv;
288 
289 	if (argc == 1) {
290 		fprintf(stderr, "bectl export: missing boot environment name\n");
291 		return (usage(false));
292 	}
293 
294 	if (argc > 2) {
295 		fprintf(stderr, "bectl export: extra arguments provided\n");
296 		return (usage(false));
297 	}
298 
299 	bootenv = argv[1];
300 
301 	if (isatty(STDOUT_FILENO)) {
302 		fprintf(stderr, "bectl export: must redirect output\n");
303 		return (EX_USAGE);
304 	}
305 
306 	be_export(be, bootenv, STDOUT_FILENO);
307 
308 	return (0);
309 }
310 
311 
312 static int
313 bectl_cmd_import(int argc, char *argv[])
314 {
315 	char *bootenv;
316 	int err;
317 
318 	if (argc == 1) {
319 		fprintf(stderr, "bectl import: missing boot environment name\n");
320 		return (usage(false));
321 	}
322 
323 	if (argc > 2) {
324 		fprintf(stderr, "bectl import: extra arguments provided\n");
325 		return (usage(false));
326 	}
327 
328 	bootenv = argv[1];
329 
330 	if (isatty(STDIN_FILENO)) {
331 		fprintf(stderr, "bectl import: input can not be from terminal\n");
332 		return (EX_USAGE);
333 	}
334 
335 	err = be_import(be, bootenv, STDIN_FILENO);
336 
337 	return (err);
338 }
339 
340 #if SOON
341 static int
342 bectl_cmd_add(int argc, char *argv[])
343 {
344 
345 	if (argc < 2) {
346 		fprintf(stderr, "bectl add: must provide at least one path\n");
347 		return (usage(false));
348 	}
349 
350 	for (int i = 1; i < argc; ++i) {
351 		printf("arg %d: %s\n", i, argv[i]);
352 		/* XXX TODO catch err */
353 		be_add_child(be, argv[i], true);
354 	}
355 
356 	return (0);
357 }
358 #endif
359 
360 static int
361 bectl_cmd_destroy(int argc, char *argv[])
362 {
363 	nvlist_t *props;
364 	char *origin, *target, targetds[BE_MAXPATHLEN];
365 	int err, flags, opt;
366 
367 	flags = 0;
368 	while ((opt = getopt(argc, argv, "Fo")) != -1) {
369 		switch (opt) {
370 		case 'F':
371 			flags |= BE_DESTROY_FORCE;
372 			break;
373 		case 'o':
374 			flags |= BE_DESTROY_ORIGIN;
375 			break;
376 		default:
377 			fprintf(stderr, "bectl destroy: unknown option '-%c'\n",
378 			    optopt);
379 			return (usage(false));
380 		}
381 	}
382 
383 	argc -= optind;
384 	argv += optind;
385 
386 	if (argc != 1) {
387 		fprintf(stderr, "bectl destroy: wrong number of arguments\n");
388 		return (usage(false));
389 	}
390 
391 	target = argv[0];
392 
393 	/* We'll emit a notice if there's an origin to be cleaned up */
394 	if ((flags & BE_DESTROY_ORIGIN) == 0 && strchr(target, '@') == NULL) {
395 		flags |= BE_DESTROY_AUTOORIGIN;
396 		if (be_root_concat(be, target, targetds) != 0)
397 			goto destroy;
398 		if (be_prop_list_alloc(&props) != 0)
399 			goto destroy;
400 		if (be_get_dataset_props(be, targetds, props) != 0) {
401 			be_prop_list_free(props);
402 			goto destroy;
403 		}
404 		if (nvlist_lookup_string(props, "origin", &origin) == 0 &&
405 		    !be_is_auto_snapshot_name(be, origin))
406 			fprintf(stderr, "bectl destroy: leaving origin '%s' intact\n",
407 			    origin);
408 		be_prop_list_free(props);
409 	}
410 
411 destroy:
412 	err = be_destroy(be, target, flags);
413 
414 	return (err);
415 }
416 
417 static int
418 bectl_cmd_mount(int argc, char *argv[])
419 {
420 	char result_loc[BE_MAXPATHLEN];
421 	char *bootenv, *mountpoint;
422 	int err, mntflags;
423 
424 	/* XXX TODO: Allow shallow */
425 	mntflags = BE_MNT_DEEP;
426 	if (argc < 2) {
427 		fprintf(stderr, "bectl mount: missing argument(s)\n");
428 		return (usage(false));
429 	}
430 
431 	if (argc > 3) {
432 		fprintf(stderr, "bectl mount: too many arguments\n");
433 		return (usage(false));
434 	}
435 
436 	bootenv = argv[1];
437 	mountpoint = ((argc == 3) ? argv[2] : NULL);
438 
439 	err = be_mount(be, bootenv, mountpoint, mntflags, result_loc);
440 
441 	switch (err) {
442 	case BE_ERR_SUCCESS:
443 		printf("Successfully mounted %s at %s\n", bootenv, result_loc);
444 		break;
445 	default:
446 		fprintf(stderr,
447 		    (argc == 3) ? "Failed to mount bootenv %s at %s\n" :
448 		    "Failed to mount bootenv %s at temporary path %s\n",
449 		    bootenv, mountpoint);
450 	}
451 
452 	return (err);
453 }
454 
455 
456 static int
457 bectl_cmd_rename(int argc, char *argv[])
458 {
459 	char *dest, *src;
460 	int err;
461 
462 	if (argc < 3) {
463 		fprintf(stderr, "bectl rename: missing argument\n");
464 		return (usage(false));
465 	}
466 
467 	if (argc > 3) {
468 		fprintf(stderr, "bectl rename: too many arguments\n");
469 		return (usage(false));
470 	}
471 
472 	src = argv[1];
473 	dest = argv[2];
474 
475 	err = be_rename(be, src, dest);
476 
477 	switch (err) {
478 	case BE_ERR_SUCCESS:
479 		break;
480 	default:
481 		fprintf(stderr, "Failed to rename bootenv %s to %s\n",
482 		    src, dest);
483 	}
484 
485 	return (0);
486 }
487 
488 static int
489 bectl_cmd_unmount(int argc, char *argv[])
490 {
491 	char *bootenv, *cmd;
492 	int err, flags, opt;
493 
494 	/* Store alias used */
495 	cmd = argv[0];
496 
497 	flags = 0;
498 	while ((opt = getopt(argc, argv, "f")) != -1) {
499 		switch (opt) {
500 		case 'f':
501 			flags |= BE_MNT_FORCE;
502 			break;
503 		default:
504 			fprintf(stderr, "bectl %s: unknown option '-%c'\n",
505 			    cmd, optopt);
506 			return (usage(false));
507 		}
508 	}
509 
510 	argc -= optind;
511 	argv += optind;
512 
513 	if (argc != 1) {
514 		fprintf(stderr, "bectl %s: wrong number of arguments\n", cmd);
515 		return (usage(false));
516 	}
517 
518 	bootenv = argv[0];
519 
520 	err = be_unmount(be, bootenv, flags);
521 
522 	switch (err) {
523 	case BE_ERR_SUCCESS:
524 		break;
525 	default:
526 		fprintf(stderr, "Failed to unmount bootenv %s\n", bootenv);
527 	}
528 
529 	return (err);
530 }
531 
532 static int
533 bectl_cmd_check(int argc, char *argv[] __unused)
534 {
535 
536 	/* The command is left as argv[0] */
537 	if (argc != 1) {
538 		fprintf(stderr, "bectl check: wrong number of arguments\n");
539 		return (usage(false));
540 	}
541 
542 	return (0);
543 }
544 
545 int
546 main(int argc, char *argv[])
547 {
548 	struct command_map_entry *cmd;
549 	const char *command;
550 	char *root;
551 	int rc;
552 
553 	cmd = NULL;
554 	root = NULL;
555 	if (argc < 2)
556 		return (usage(false));
557 
558 	if (strcmp(argv[1], "-r") == 0) {
559 		if (argc < 4)
560 			return (usage(false));
561 		root = strdup(argv[2]);
562 		command = argv[3];
563 		argc -= 3;
564 		argv += 3;
565 	} else {
566 		command = argv[1];
567 		argc -= 1;
568 		argv += 1;
569 	}
570 
571 	/* Handle command aliases */
572 	if (strcmp(command, "umount") == 0)
573 		command = "unmount";
574 
575 	if (strcmp(command, "ujail") == 0)
576 		command = "unjail";
577 
578 	if ((strcmp(command, "-?") == 0) || (strcmp(command, "-h") == 0))
579 		return (usage(true));
580 
581 	if ((cmd = get_cmd_info(command)) == NULL) {
582 		fprintf(stderr, "Unknown command: %s\n", command);
583 		return (usage(false));
584 	}
585 
586 	if ((be = libbe_init(root)) == NULL) {
587 		if (!cmd->silent)
588 			fprintf(stderr, "libbe_init(\"%s\") failed.\n",
589 			    root != NULL ? root : "");
590 		return (-1);
591 	}
592 
593 	libbe_print_on_error(be, !cmd->silent);
594 
595 	rc = cmd->fn(argc, argv);
596 
597 	libbe_close(be);
598 	return (rc);
599 }
600