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